File size: 1,105 Bytes
0a50834
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import fcntl
import hashlib
import json
import sqlite3
from contextlib import contextmanager
from pathlib import Path


def fingerprint(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()


@contextmanager
def locked_state(directory):
    directory = Path(directory)
    directory.mkdir(parents=True, exist_ok=True)
    with (directory / 'worker.lock').open('a') as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            raise RuntimeError('Another vector worker is using this state volume.') from None
        with sqlite3.connect(directory / 'cache.sqlite') as db:
            db.execute('CREATE TABLE IF NOT EXISTS vectors (key TEXT PRIMARY KEY, value TEXT NOT NULL)')
            yield db


def cached_vectors(db, key, produce):
    row = db.execute('SELECT value FROM vectors WHERE key=?', (key,)).fetchone()
    if row:
        return json.loads(row[0])
    vectors = produce()
    db.execute('INSERT INTO vectors VALUES (?,?)', (key, json.dumps(vectors)))
    db.commit()
    return vectors