Archived
132 lines
5.3 KiB
Python
132 lines
5.3 KiB
Python
import json
|
|
import os
|
|
import sqlite3
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from typing import Iterable
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class PushDelivery:
|
|
session_id: str
|
|
subscription: dict
|
|
thread_ids: tuple[int, ...]
|
|
|
|
|
|
class PushSubscriptionStore:
|
|
"""Durable, device-bound Web Push subscriptions and delivery deduplication."""
|
|
|
|
def __init__(self, path: str | Path):
|
|
self.path = Path(path)
|
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
os.chmod(self.path.parent, 0o700)
|
|
with self._connect() as connection:
|
|
connection.executescript(
|
|
"""
|
|
CREATE TABLE IF NOT EXISTS push_subscriptions (
|
|
session_id TEXT PRIMARY KEY,
|
|
endpoint TEXT NOT NULL UNIQUE,
|
|
subscription_json TEXT NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS push_deliveries (
|
|
session_id TEXT NOT NULL,
|
|
thread_id INTEGER NOT NULL,
|
|
PRIMARY KEY (session_id, thread_id),
|
|
FOREIGN KEY (session_id) REFERENCES push_subscriptions(session_id)
|
|
ON DELETE CASCADE
|
|
);
|
|
CREATE TABLE IF NOT EXISTS push_dispatch_lease (
|
|
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
|
owner TEXT NOT NULL,
|
|
expires_at REAL NOT NULL
|
|
);
|
|
"""
|
|
)
|
|
os.chmod(self.path, 0o600)
|
|
|
|
def _connect(self):
|
|
connection = sqlite3.connect(self.path, timeout=2)
|
|
connection.execute("PRAGMA foreign_keys = ON")
|
|
return connection
|
|
|
|
def acquire_dispatch_lease(
|
|
self, owner: str, *, now: float, lease_seconds: float
|
|
) -> bool:
|
|
with self._connect() as connection:
|
|
connection.execute("BEGIN IMMEDIATE")
|
|
current = connection.execute(
|
|
"SELECT owner, expires_at FROM push_dispatch_lease WHERE singleton = 1"
|
|
).fetchone()
|
|
if current is not None and current[0] != owner and current[1] > now:
|
|
return False
|
|
connection.execute(
|
|
"""INSERT INTO push_dispatch_lease(singleton, owner, expires_at)
|
|
VALUES (1, ?, ?)
|
|
ON CONFLICT(singleton) DO UPDATE SET
|
|
owner = excluded.owner, expires_at = excluded.expires_at""",
|
|
(owner, now + lease_seconds),
|
|
)
|
|
return True
|
|
|
|
def release_dispatch_lease(self, owner: str) -> bool:
|
|
with self._connect() as connection:
|
|
result = connection.execute(
|
|
"DELETE FROM push_dispatch_lease WHERE singleton = 1 AND owner = ?",
|
|
(owner,),
|
|
)
|
|
return result.rowcount == 1
|
|
|
|
def upsert(self, session_id: str, subscription: dict) -> None:
|
|
endpoint = subscription["endpoint"]
|
|
encoded = json.dumps(subscription, separators=(",", ":"), sort_keys=True)
|
|
with self._connect() as connection:
|
|
connection.execute("DELETE FROM push_subscriptions WHERE endpoint = ?", (endpoint,))
|
|
connection.execute("DELETE FROM push_subscriptions WHERE session_id = ?", (session_id,))
|
|
connection.execute(
|
|
"INSERT INTO push_subscriptions(session_id, endpoint, subscription_json) VALUES (?, ?, ?)",
|
|
(session_id, endpoint, encoded),
|
|
)
|
|
|
|
def delete_session(self, session_id: str) -> None:
|
|
with self._connect() as connection:
|
|
connection.execute("DELETE FROM push_subscriptions WHERE session_id = ?", (session_id,))
|
|
|
|
def delete_all(self) -> None:
|
|
with self._connect() as connection:
|
|
connection.execute("DELETE FROM push_subscriptions")
|
|
|
|
def is_subscribed(self, session_id: str) -> bool:
|
|
with self._connect() as connection:
|
|
return connection.execute(
|
|
"SELECT 1 FROM push_subscriptions WHERE session_id = ?", (session_id,)
|
|
).fetchone() is not None
|
|
|
|
def claim_unseen(self, thread_ids: Iterable[int]) -> list[PushDelivery]:
|
|
candidates = tuple(sorted({int(value) for value in thread_ids if int(value) > 0}))
|
|
if not candidates:
|
|
return []
|
|
with self._connect() as connection:
|
|
rows = connection.execute(
|
|
"SELECT session_id, subscription_json FROM push_subscriptions ORDER BY session_id"
|
|
).fetchall()
|
|
deliveries = []
|
|
for session_id, encoded in rows:
|
|
delivered = {
|
|
row[0]
|
|
for row in connection.execute(
|
|
"SELECT thread_id FROM push_deliveries WHERE session_id = ?",
|
|
(session_id,),
|
|
)
|
|
}
|
|
unseen = tuple(value for value in candidates if value not in delivered)
|
|
if unseen:
|
|
deliveries.append(PushDelivery(session_id, json.loads(encoded), unseen))
|
|
return deliveries
|
|
|
|
def mark_delivered(self, session_id: str, thread_ids: Iterable[int]) -> None:
|
|
with self._connect() as connection:
|
|
connection.executemany(
|
|
"INSERT OR IGNORE INTO push_deliveries(session_id, thread_id) VALUES (?, ?)",
|
|
((session_id, int(thread_id)) for thread_id in thread_ids),
|
|
)
|