text
stringlengths
0
1.47k
return None
try:
base = float(body.get("ts") or time.time())
except (TypeError, ValueError):
base = time.time()
return base + ttl
class SqliteContainer:
"""Async-shaped container over one SQLite file.
The methods are `async def` purely to match the hosted client's surface — the work is
synchronous and fast (single-row, indexed). Making it genuinely async would buy
nothing here and would add a thread hop to every lease heartbeat.
"""
def __init__(self, path: str):
self._path = path
os.makedirs(os.path.dirname(os.path.abspath(path)) or ".", exist_ok=True)
_connect(path).close() # create schema up front, surface I/O errors early
# -- helpers ---------------------------------------------------------------
@staticmethod
def _row_to_doc(row) -> dict:
doc = json.loads(row[0])
doc["_etag"] = str(row[1])
return doc
def _live(self, con, item_id: str):
"""Fetch a row, treating an expired document as absent (and sweeping it)."""
row = con.execute("SELECT body, etag, expires FROM control WHERE id=?",
(item_id,)).fetchone()
if row is None:
return None
if row[2] is not None and row[2] <= time.time():
con.execute("DELETE FROM control WHERE id=?", (item_id,))
return None
return row
# -- container operations --------------------------------------------------
async def read_item(self, item: str, partition_key: str = "", **_kw) -> dict:
con = _connect(self._path)
try:
row = self._live(con, item)
if row is None:
raise CosmosResourceNotFoundError(item)
return self._row_to_doc(row)
finally:
con.close()
async def create_item(self, body: dict, **_kw) -> dict:
"""Insert, or raise Exists — this is the atom idempotency reservation rides on."""
item_id = str(body.get("id") or "")
con = _connect(self._path)
try:
con.execute("BEGIN IMMEDIATE")
if self._live(con, item_id) is not None:
con.execute("ROLLBACK")
raise CosmosResourceExistsError(item_id)
# An expired row may still occupy the primary key — _live swept it above.
con.execute("INSERT OR REPLACE INTO control(id, pk, body, etag, expires) "
"VALUES(?,?,?,?,?)",
(item_id, str(body.get("pk") or ""), json.dumps(body), 1,
_expires_at(body)))
con.execute("COMMIT")
return {**body, "_etag": "1"}
except CosmosResourceExistsError:
raise
except Exception as e: # noqa: BLE001
try:
con.execute("ROLLBACK")
except Exception: # noqa: BLE001
pass
raise CosmosHttpResponseError(str(e)) from e
finally:
con.close()
async def replace_item(self, item: str, body: dict, etag: str | None = None,
match_condition=None, **_kw) -> dict:
"""Replace; when `etag` is supplied this is a compare-and-swap.
Losing the CAS raises the access-condition error rather than overwriting — the
fencing logic in control_store depends on that being a hard failure, because a
silent overwrite would let two owners believe they hold the same lease.
"""
con = _connect(self._path)
try:
con.execute("BEGIN IMMEDIATE")
row = self._live(con, item)
if row is None:
con.execute("ROLLBACK")
raise CosmosResourceNotFoundError(item)
if etag is not None and str(row[1]) != str(etag):
con.execute("ROLLBACK")
raise CosmosAccessConditionFailedError(item)
new_etag = int(row[1]) + 1
stored = {k: v for k, v in body.items() if k != "_etag"}
con.execute("UPDATE control SET pk=?, body=?, etag=?, expires=? WHERE id=?",
(str(body.get("pk") or ""), json.dumps(stored), new_etag,
_expires_at(stored), item))