2024-09-08 05:48:28 +02:00
|
|
|
"""Inventory implementation using sqlite"""
|
|
|
|
|
2024-10-14 15:49:05 +02:00
|
|
|
import base64
|
2024-09-11 04:33:10 +02:00
|
|
|
import logging
|
2024-09-08 05:48:28 +02:00
|
|
|
import os
|
|
|
|
import sqlite3
|
2024-09-08 23:11:58 +02:00
|
|
|
import threading
|
2024-09-08 05:48:28 +02:00
|
|
|
import time
|
|
|
|
|
|
|
|
from . import shared, structure
|
|
|
|
|
|
|
|
sqlite3.threadsafety = 3
|
|
|
|
|
|
|
|
|
|
|
|
class Inventory():
|
|
|
|
"""sqlite inventory"""
|
|
|
|
def __init__(self):
|
2024-09-08 23:11:58 +02:00
|
|
|
self._lock = threading.Lock()
|
2024-09-11 04:33:10 +02:00
|
|
|
self._deleted = 0
|
2024-10-14 15:49:05 +02:00
|
|
|
self._last = {}
|
2024-09-12 19:26:57 +02:00
|
|
|
self._pending = set()
|
2024-09-08 05:48:28 +02:00
|
|
|
self._db = sqlite3.connect(
|
|
|
|
os.path.join(shared.data_directory, 'objects.dat'),
|
|
|
|
check_same_thread=False
|
|
|
|
)
|
|
|
|
self._db.executescript("""
|
|
|
|
BEGIN;
|
|
|
|
CREATE TABLE IF NOT EXISTS status
|
|
|
|
(key text, value integer, UNIQUE(key) ON CONFLICT REPLACE);
|
|
|
|
INSERT INTO status VALUES ('version', 1);
|
|
|
|
CREATE TABLE IF NOT EXISTS objects
|
|
|
|
(vector unique, expires integer, type integer, version integer,
|
|
|
|
stream integer, tag, data, offset integer);
|
|
|
|
COMMIT;
|
|
|
|
""")
|
|
|
|
self.rowid = len(self) or None
|
|
|
|
try:
|
2024-09-11 04:33:10 +02:00
|
|
|
self.lastvacuumtime = self._db.execute(
|
|
|
|
"SELECT value FROM status WHERE key='lastvacuumtime'"
|
|
|
|
).fetchone()[0]
|
2024-09-08 05:48:28 +02:00
|
|
|
except TypeError:
|
2024-09-11 04:33:10 +02:00
|
|
|
self.lastvacuumtime = int(time.time())
|
|
|
|
self._db.execute(
|
|
|
|
"INSERT INTO status VALUES ('lastvacuumtime', ?)",
|
|
|
|
(self.lastvacuumtime,)
|
|
|
|
)
|
2024-09-08 05:48:28 +02:00
|
|
|
self._db.commit()
|
2024-09-11 01:35:09 +02:00
|
|
|
self._db.row_factory = self.__object
|
2024-09-08 05:48:28 +02:00
|
|
|
|
2024-09-11 01:35:09 +02:00
|
|
|
@staticmethod
|
|
|
|
def __object(cursor, row):
|
|
|
|
if len(cursor.description) != 8:
|
|
|
|
return row
|
|
|
|
vector, expires, obj_type, version, stream, tag, data, offset = row
|
|
|
|
return structure.Object(
|
|
|
|
expires, obj_type, version, stream, data, offset,
|
|
|
|
tag=tag, vector=vector)
|
2024-09-08 05:48:28 +02:00
|
|
|
|
2024-09-12 19:26:57 +02:00
|
|
|
def check(self, *vectors):
|
|
|
|
with self._lock:
|
|
|
|
for vector in vectors:
|
|
|
|
self._pending.discard(vector)
|
|
|
|
|
2024-09-08 05:48:28 +02:00
|
|
|
def cleanup(self):
|
2024-09-12 19:26:57 +02:00
|
|
|
if len(self._pending) > 100:
|
|
|
|
logging.warning(
|
|
|
|
'Not cleaning up, %s objects pending', len(self._pending))
|
|
|
|
return
|
2024-10-14 15:49:05 +02:00
|
|
|
for vector in set(self._last):
|
|
|
|
if self._last[vector].is_expired():
|
|
|
|
logging.debug(
|
|
|
|
'Deleted expired object: %s',
|
|
|
|
base64.b16encode(vector).decode())
|
|
|
|
with self._lock:
|
|
|
|
del self._last[vector]
|
|
|
|
if len(self._last) > 1000:
|
|
|
|
self.flush()
|
|
|
|
return
|
2024-09-08 23:11:58 +02:00
|
|
|
with self._lock:
|
2024-09-11 04:33:10 +02:00
|
|
|
now = int(time.time())
|
|
|
|
cur = self._db.execute(
|
|
|
|
'DELETE FROM objects WHERE expires < ?', (now - 3 * 3600,))
|
2024-09-08 05:48:28 +02:00
|
|
|
self._db.commit()
|
2024-09-11 04:33:10 +02:00
|
|
|
self._deleted += cur.rowcount
|
2024-09-12 19:26:57 +02:00
|
|
|
logging.debug(
|
|
|
|
'Deleted %s expired objects, %s pending',
|
|
|
|
cur.rowcount, len(self._pending))
|
2024-09-11 04:33:10 +02:00
|
|
|
# conditional vacuum and validity check (TODO)
|
|
|
|
# every 24 hours or after deleting a lot of items
|
|
|
|
if self._deleted > 10000 or self.lastvacuumtime < now - 86400:
|
|
|
|
logging.info('Doing VACUUM for objects')
|
|
|
|
cur.execute('VACUUM')
|
|
|
|
cur.execute(
|
|
|
|
"INSERT INTO status VALUES ('lastvacuumtime', ?)", (now,))
|
|
|
|
self._db.commit()
|
|
|
|
self._deleted = 0
|
|
|
|
self.lastvacuumtime = now
|
2024-09-08 05:48:28 +02:00
|
|
|
|
2024-10-14 15:49:05 +02:00
|
|
|
def flush(self):
|
|
|
|
with self._lock:
|
|
|
|
cur = self._db.executemany(
|
|
|
|
'INSERT INTO objects VALUES (?,?,?,?,?,?,?,?)',
|
|
|
|
((obj.vector, obj.expires_time, obj.object_type,
|
|
|
|
obj.version, obj.stream_number, obj.tag, obj.data,
|
|
|
|
obj.offset) for obj in self._last.values()))
|
|
|
|
self._db.commit()
|
|
|
|
self.rowid = cur.lastrowid
|
|
|
|
self._last = {}
|
|
|
|
|
2024-09-08 05:48:28 +02:00
|
|
|
def filter(self, stream=None, object_type=None, tag=None):
|
2024-10-14 15:49:05 +02:00
|
|
|
def fits(obj):
|
|
|
|
if stream and obj.stream_number != stream:
|
|
|
|
return False
|
|
|
|
if object_type is not None and obj.object_type != object_type:
|
|
|
|
return False
|
|
|
|
if tag and obj.tag != tag:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
yield from filter(fits, self._last.values())
|
|
|
|
|
2024-09-08 05:48:28 +02:00
|
|
|
clauses = []
|
|
|
|
if stream:
|
|
|
|
clauses.append(('stream = ?', stream))
|
|
|
|
if object_type is not None:
|
|
|
|
clauses.append(('type = ?', object_type))
|
|
|
|
if tag:
|
|
|
|
clauses.append(('tag = ?', tag))
|
|
|
|
|
|
|
|
clauses, params = zip(*clauses)
|
|
|
|
|
2024-10-14 15:49:05 +02:00
|
|
|
yield from self._db.execute(
|
2024-09-08 05:48:28 +02:00
|
|
|
'SELECT * FROM objects WHERE ' # nosec B608
|
|
|
|
+ ' AND '.join(clauses), params)
|
|
|
|
|
2024-09-12 19:26:57 +02:00
|
|
|
def select(self, vectors):
|
|
|
|
chunk_size = 999
|
|
|
|
with self._lock:
|
2024-10-14 15:49:05 +02:00
|
|
|
vectors.difference_update(self._last)
|
|
|
|
keys = tuple(vectors)
|
2024-09-12 19:26:57 +02:00
|
|
|
for i in range(0, len(vectors), chunk_size):
|
|
|
|
chunk = keys[i:i+chunk_size]
|
|
|
|
cur = self._db.execute(
|
|
|
|
'SELECT vector FROM objects WHERE vector IN' # nosec B608
|
|
|
|
' ({})'.format(','.join('?' * len(chunk))),
|
|
|
|
chunk)
|
|
|
|
for v, in cur:
|
|
|
|
vectors.remove(v)
|
2024-10-14 15:49:05 +02:00
|
|
|
self._pending.update(vectors)
|
2024-09-12 19:26:57 +02:00
|
|
|
return vectors
|
|
|
|
|
2024-10-31 06:22:41 +01:00
|
|
|
def biginv_chunks(self, chunk_size=10000, stream=None):
|
2024-10-13 04:09:47 +02:00
|
|
|
if stream is None:
|
|
|
|
stream = shared.stream
|
|
|
|
now = int(time.time())
|
2024-09-08 05:48:28 +02:00
|
|
|
cur = self._db.execute(
|
|
|
|
'SELECT vector FROM objects WHERE expires > ? AND stream = ?'
|
2024-10-13 04:09:47 +02:00
|
|
|
' ORDER BY random()', (now, stream)
|
2024-09-08 05:48:28 +02:00
|
|
|
)
|
2024-10-13 04:09:47 +02:00
|
|
|
cur.arraysize = chunk_size
|
|
|
|
while True:
|
|
|
|
vectors = cur.fetchmany()
|
|
|
|
if not vectors:
|
2024-10-14 15:49:05 +02:00
|
|
|
# TODO: append to the last short result,
|
|
|
|
# check that _last is shorter than the chunk_size
|
|
|
|
# (should be < 1000)
|
|
|
|
if self._last:
|
|
|
|
yield [
|
|
|
|
obj.vector for obj in self._last.values()
|
|
|
|
if obj.stream_number == stream
|
|
|
|
and obj.expires_time > now]
|
2024-10-13 04:09:47 +02:00
|
|
|
return
|
|
|
|
yield [v for v, in vectors]
|
2024-09-08 05:48:28 +02:00
|
|
|
|
|
|
|
def get(self, vector, default=None):
|
|
|
|
try:
|
|
|
|
return self[vector]
|
|
|
|
except KeyError:
|
|
|
|
return default
|
|
|
|
|
|
|
|
def keys(self):
|
2024-10-14 15:49:05 +02:00
|
|
|
yield from self._last
|
|
|
|
for vector, in self._db.execute('SELECT vector FROM objects'):
|
|
|
|
yield vector
|
2024-09-08 05:48:28 +02:00
|
|
|
|
|
|
|
def values(self):
|
2024-10-14 15:49:05 +02:00
|
|
|
yield from self._last.values()
|
|
|
|
yield from self._db.execute('SELECT * FROM objects')
|
2024-09-08 05:48:28 +02:00
|
|
|
|
|
|
|
def popitem(self):
|
2024-10-14 15:49:05 +02:00
|
|
|
try:
|
|
|
|
return self._last.popitem()
|
|
|
|
except KeyError:
|
|
|
|
pass
|
2024-09-08 05:48:28 +02:00
|
|
|
if not self.rowid:
|
|
|
|
raise KeyError('empty')
|
|
|
|
cur = self._db.execute(
|
|
|
|
'SELECT vector FROM objects WHERE ROWID = ?', (self.rowid,))
|
|
|
|
vector = cur.fetchone()[0]
|
|
|
|
obj = self.get(vector)
|
|
|
|
del self[vector]
|
|
|
|
return (vector, obj)
|
|
|
|
|
|
|
|
def __contains__(self, vector):
|
2024-10-14 15:49:05 +02:00
|
|
|
if vector in self._last:
|
|
|
|
return True
|
|
|
|
return self._db.execute(
|
|
|
|
'SELECT vector FROM objects WHERE vector = ?', (vector,)
|
|
|
|
).fetchone() is not None
|
2024-09-08 05:48:28 +02:00
|
|
|
|
|
|
|
def __getitem__(self, vector):
|
2024-10-14 15:49:05 +02:00
|
|
|
try:
|
|
|
|
return self._last[vector]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
2024-09-11 01:35:09 +02:00
|
|
|
item = self._db.execute(
|
|
|
|
'SELECT * FROM objects WHERE vector = ?', (vector,)).fetchone()
|
2024-09-08 05:48:28 +02:00
|
|
|
if item is None:
|
|
|
|
raise KeyError(vector)
|
2024-09-11 01:35:09 +02:00
|
|
|
return item
|
2024-09-08 05:48:28 +02:00
|
|
|
|
|
|
|
def __delitem__(self, vector):
|
2024-10-14 15:49:05 +02:00
|
|
|
try:
|
|
|
|
del self._last[vector]
|
|
|
|
return
|
|
|
|
except KeyError:
|
|
|
|
pass
|
2024-09-08 23:11:58 +02:00
|
|
|
with self._lock: # KeyError
|
2024-09-08 05:48:28 +02:00
|
|
|
self._db.execute('DELETE FROM objects WHERE vector = ?', (vector,))
|
|
|
|
self._db.commit()
|
|
|
|
self.rowid = len(self)
|
|
|
|
|
|
|
|
def __setitem__(self, vector, obj):
|
2024-10-14 15:49:05 +02:00
|
|
|
if vector in self:
|
|
|
|
return
|
2024-09-08 23:11:58 +02:00
|
|
|
with self._lock:
|
2024-10-14 15:49:05 +02:00
|
|
|
self._last[vector] = obj
|
2024-09-08 05:48:28 +02:00
|
|
|
|
|
|
|
def __bool__(self):
|
2024-10-14 15:49:05 +02:00
|
|
|
if self._last:
|
|
|
|
return True
|
2024-09-08 05:48:28 +02:00
|
|
|
return self._db.execute(
|
|
|
|
'SELECT vector from objects LIMIT 1').fetchone() is not None
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
cur = self._db.execute('SELECT count(*) FROM objects')
|
2024-10-14 15:49:05 +02:00
|
|
|
return cur.fetchone()[0] + len(self._last)
|
2024-09-08 05:48:28 +02:00
|
|
|
|
|
|
|
def __del__(self):
|
2024-10-14 15:49:05 +02:00
|
|
|
self.flush()
|
2024-09-08 05:48:28 +02:00
|
|
|
self._db.close()
|