69 lines
2.7 KiB
Python
69 lines
2.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Buryans agent memory: namespaced key/value with TTL and search."""
|
|
import argparse, json, os, sqlite3, time
|
|
from pathlib import Path
|
|
|
|
DB = os.environ.get("HUB_MEMORY_DB", "/var/lib/hub-memory/memory.db")
|
|
|
|
|
|
def connect(db=None):
|
|
db = db or DB
|
|
Path(db).parent.mkdir(parents=True, exist_ok=True)
|
|
c = sqlite3.connect(db)
|
|
c.execute("""create table if not exists memory(
|
|
namespace text not null, key text not null, value text not null,
|
|
source text default '', updated_at real not null, expires_at real,
|
|
primary key(namespace,key))""")
|
|
return c
|
|
|
|
|
|
def put(namespace, key, value, source="", ttl=None, db=None):
|
|
now = time.time()
|
|
exp = now + ttl if ttl else None
|
|
with connect(db) as c:
|
|
c.execute("""insert into memory(namespace,key,value,source,updated_at,expires_at)
|
|
values(?,?,?,?,?,?)
|
|
on conflict(namespace,key) do update set value=excluded.value,
|
|
source=excluded.source, updated_at=excluded.updated_at, expires_at=excluded.expires_at""",
|
|
(namespace, key, value, source, now, exp))
|
|
return {"namespace": namespace, "key": key, "expires_at": exp}
|
|
|
|
|
|
def get(namespace, key, db=None):
|
|
with connect(db) as c:
|
|
r = c.execute("select value,source,updated_at,expires_at from memory where namespace=? and key=?",
|
|
(namespace, key)).fetchone()
|
|
if not r:
|
|
return None
|
|
if r[3] and r[3] < time.time():
|
|
c.execute("delete from memory where namespace=? and key=?", (namespace, key))
|
|
return None
|
|
return {"value": r[0], "source": r[1], "updated_at": r[2], "expires_at": r[3]}
|
|
|
|
|
|
def search(namespace, query, limit=20, db=None):
|
|
with connect(db) as c:
|
|
rows = c.execute("""select namespace,key,value,source,updated_at,expires_at from memory
|
|
where namespace=? and (key like ? or value like ?) order by updated_at desc limit ?""",
|
|
(namespace, "%" + query + "%", "%" + query + "%", int(limit))).fetchall()
|
|
now = time.time()
|
|
return [{"namespace": x[0], "key": x[1], "value": x[2], "source": x[3],
|
|
"updated_at": x[4], "expires_at": x[5]} for x in rows
|
|
if not x[5] or x[5] > now]
|
|
|
|
|
|
if __name__ == "__main__":
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("cmd", choices=["put", "get", "search"])
|
|
ap.add_argument("namespace")
|
|
ap.add_argument("key")
|
|
ap.add_argument("value", nargs="?")
|
|
ap.add_argument("--ttl", type=int)
|
|
a = ap.parse_args()
|
|
if a.cmd == "put":
|
|
print(json.dumps(put(a.namespace, a.key, a.value or "", ttl=a.ttl)))
|
|
elif a.cmd == "get":
|
|
print(json.dumps(get(a.namespace, a.key)))
|
|
else:
|
|
print(json.dumps(search(a.namespace, a.key)))
|