Chulinz's picture
ICJ Citation Graph release with Parquet and Docker runtime
0a50834
Raw History Blame Contribute Delete
1.11 kB
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