Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 57 additions & 24 deletions core/openmate_core/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,9 @@ def __init__(self, path: str, legacy_blocked_texts: Iterable[str] = ()):
os.chmod(path, 0o600)
self._lock = threading.RLock()
self._read_lock = threading.Lock()
self._chat_lock = threading.Lock() # version publication only, never held while running SQL
self._chat_generation = 0
self._chat_versions: Dict[str, int] = {}
self.changes = 0
self.snapshot_scope = (0, "")
# the /agent runs an account switch wiped (ids are never reused): a thread of the account before that still
Expand Down Expand Up @@ -324,18 +327,25 @@ def close(self) -> None:

# ---- small helpers ----

def _tx(self, fn, *, count: bool = True):
def _tx(self, fn, *, count: bool = True, chat_ids: Optional[Iterable[str]] = None):
"""fn(db) in one write transaction. Whatever fails (fn, or the COMMIT itself: SQLITE_BUSY), the transaction is
rolled back before the error goes up. A commit that changes rows invalidates cached chat reads unless the
caller opts out for bookkeeping that cannot affect those reads."""
caller opts out for bookkeeping that cannot affect those reads. chat_ids can be filled by fn: None means
the affected chats are unknown, () means the write affects no chat or message rows."""
with self._lock:
self._db.execute("BEGIN IMMEDIATE")
try:
before = self._db.total_changes
out = fn(self._db)
self._db.execute("COMMIT")
if count and self._db.total_changes != before:
self.changes += 1
with self._chat_lock:
if chat_ids is None:
self._invalidate_chats()
else:
for cid in chat_ids:
self._chat_versions[cid] = self._chat_versions.get(cid, 0) + 1
self.changes += 1
return out
except BaseException:
if self._db.in_transaction:
Expand All @@ -345,6 +355,16 @@ def _tx(self, fn, *, count: bool = True):
pass # the original error says more
raise

def _invalidate_chats(self) -> None:
# Caller holds _chat_lock.
self._chat_generation += 1
self._chat_versions.clear()

def chat_versions(self, chat_ids: Iterable[str]) -> Tuple[int, Dict[str, int]]:
"""The current generation and committed versions of the requested chats."""
with self._chat_lock:
return self._chat_generation, {cid: self._chat_versions.get(cid, 0) for cid in chat_ids}

def _all(self, sql: str, args: Iterable = ()) -> List[sqlite3.Row]:
with self._read_lock:
return self._reader.execute(sql, tuple(args)).fetchall()
Expand Down Expand Up @@ -387,10 +407,11 @@ def meta_get(self, key: str, default: str = "") -> str:
return r["value"] if r else default

def meta_set(self, key: str, value: str) -> None:
self._tx(lambda db: db.execute("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", (key, value)))
self._tx(lambda db: db.execute("INSERT INTO meta (key, value) VALUES (?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value", (key, value)), chat_ids=())

def meta_delete(self, key: str) -> None:
self._tx(lambda db: db.execute("DELETE FROM meta WHERE key = ?", (key,)))
self._tx(lambda db: db.execute("DELETE FROM meta WHERE key = ?", (key,)), chat_ids=())

# ---- chats ----

Expand Down Expand Up @@ -423,7 +444,7 @@ def run(db):
"ON CONFLICT(open_id) DO UPDATE SET chat_id = excluded.chat_id, at = excluded.at",
(open_id, chat.id, now))

self._tx(run)
self._tx(run, chat_ids=(chat.id,))

def chat_of_open_id(self, open_id: str) -> str:
"""The chat the service said has this open-platform id ("" when none did)."""
Expand All @@ -444,7 +465,7 @@ def set_avatar(self, chat_id: str, value: str, now: Optional[float] = None) -> N
self._tx(lambda db: db.execute(
"INSERT INTO avatars (chat_id, value, checked) VALUES (?, ?, ?) "
"ON CONFLICT(chat_id) DO UPDATE SET value = excluded.value, checked = excluded.checked",
(str(chat_id), str(value or ""), now or time.time())))
(str(chat_id), str(value or ""), now or time.time())), chat_ids=())

def avatars(self, ids: Iterable[str]) -> Dict[str, Tuple[str, float]]:
"""{chat id: (picture, when it was asked)} of those of ids the service was asked about ("": it has none)."""
Expand Down Expand Up @@ -474,7 +495,7 @@ def set_mute(self, chat_id: str, state: str, owner: str = "", now: Optional[floa
self._tx(lambda db: db.execute(
"INSERT INTO mutes (chat_id, state, checked, owner) VALUES (?, ?, ?, ?) "
"ON CONFLICT(chat_id) DO UPDATE SET state = excluded.state, checked = excluded.checked, owner = excluded.owner",
(str(chat_id), state, now or time.time(), owner or "")))
(str(chat_id), state, now or time.time(), owner or "")), chat_ids=())

def mutes(self, ids: Iterable[str], owner: str = "") -> Dict[str, Tuple[str, float]]:
"""{chat id: (state, when it was asked)} of those of ids the service was asked about for the account owner."""
Expand Down Expand Up @@ -503,7 +524,7 @@ def set_people_kinds(self, kinds: Dict[str, str], now: Optional[float] = None) -
if rows:
self._tx(lambda db: db.executemany(
"INSERT INTO people (id, kind, checked) VALUES (?, ?, ?) "
"ON CONFLICT(id) DO UPDATE SET kind = excluded.kind, checked = excluded.checked", rows))
"ON CONFLICT(id) DO UPDATE SET kind = excluded.kind, checked = excluded.checked", rows), chat_ids=())

def dismissed(self, keys: Iterable[str]) -> Dict[str, str]:
"""{key: version} of those of keys the user marked 处理完."""
Expand All @@ -523,10 +544,10 @@ def run(db):
"ON CONFLICT(key) DO UPDATE SET version = excluded.version, at = excluded.at", (key, version, now))
db.execute("DELETE FROM dismissed WHERE at < ?", (now - 30 * 86400,))

self._tx(run)
self._tx(run, chat_ids=())

def undismiss(self, key: str) -> None:
self._tx(lambda db: db.execute("DELETE FROM dismissed WHERE key = ?", (key,)))
self._tx(lambda db: db.execute("DELETE FROM dismissed WHERE key = ?", (key,)), chat_ids=())

def chats_of_messages(self, message_ids: Iterable[str]) -> List[str]:
"""The chats these stored messages are in."""
Expand All @@ -553,7 +574,7 @@ def run(db):
db.execute("DELETE FROM dismissed WHERE at < ?", (now - 30 * 86400,)) # as dismiss: a month at most
out[0] = True

self._tx(run)
self._tx(run, chat_ids=())
return out[0]

def undismiss_if(self, key: str, expected: str) -> bool:
Expand All @@ -563,7 +584,7 @@ def undismiss_if(self, key: str, expected: str) -> bool:
def run(db):
out[0] = db.execute("DELETE FROM dismissed WHERE key = ? AND version = ?", (key, expected)).rowcount > 0

self._tx(run)
self._tx(run, chat_ids=())
return out[0]

def count_since(self, since: float) -> dict:
Expand Down Expand Up @@ -677,12 +698,14 @@ def add_messages(self, msgs: List[Message], from_history: bool, now: Optional[fl
also has the message's placement and same_as when the backend read them, and, with a placement, the thread and
quote of that same live reading (none of it stored: /agent keeps what it needs with its run)."""
now = now or time.time()
changed = set()

def run(db):
new = []
for m in msgs:
if not m.id or not m.chat_id:
continue
before = db.total_changes
if m.text and not m.text.strip():
m.text = "" # spaces alone are no text: it stays one to read again
cur = db.execute(
Expand Down Expand Up @@ -744,7 +767,10 @@ def run(db):
(m.chat_id, m.id)).fetchone()
if r is not None:
new.append(_live_row(r, m)) # its first live delivery
if db.total_changes != before:
changed.add(m.chat_id)
continue
changed.add(m.chat_id)
if (m.type or "").upper() != "SYSTEM":
db.execute(
"INSERT INTO chats (id, updated, last_at) VALUES (?, ?, ?) "
Expand All @@ -755,7 +781,7 @@ def run(db):
new.append(_live_row(r, m))
return new

return self._tx(run)
return self._tx(run, chat_ids=changed)

def message(self, chat_id: str, msg_id: str) -> Optional[dict]:
r = self._one("SELECT " + _MESSAGE_COLUMNS + " FROM messages WHERE chat_id = ? AND id = ?", (chat_id, msg_id))
Expand Down Expand Up @@ -904,7 +930,8 @@ def put_name(self, user_id: str, name: str, chat_id: str = "", now: Optional[flo
"INSERT INTO names (user_id, chat_id, name, updated) VALUES (?, ?, ?, ?) "
"ON CONFLICT(user_id, chat_id) DO UPDATE SET name = excluded.name, updated = excluded.updated",
(user_id, chat_id or "", name, now),
)
),
chat_ids=(),
)

def name(self, user_id: str, chat_id: str = "") -> str:
Expand Down Expand Up @@ -1018,7 +1045,7 @@ def put(db) -> bool:
)
return True

return self._tx(put)
return self._tx(put, chat_ids=())

def run_wiped(self, run_id: str) -> bool:
"""The run was the account's signed in before, wiped by the switch: nothing is said or sent for it."""
Expand Down Expand Up @@ -1093,7 +1120,7 @@ def run(db):
db.execute("INSERT OR IGNORE INTO gone (chat_id, at) VALUES (?, ?)", (chat_id, at))
db.execute("DELETE FROM autoreply WHERE chat_id = ?", (chat_id,))

self._tx(run)
self._tx(run, chat_ids=(chat_id,))

def is_gone(self, chat_id: str) -> bool:
"""The account left or deleted this chat (chat_gone), and no newer message brought it back."""
Expand All @@ -1105,14 +1132,15 @@ def chats_back(self, latest: Dict[str, float]) -> int:
latest = {c: at for c, at in latest.items() if c in gone} # nearly always none: no write then
if not latest:
return 0
n = [0]
changed = set()

def run(db):
for cid, at in latest.items():
n[0] += db.execute("DELETE FROM gone WHERE chat_id = ? AND at < ?", (cid, at)).rowcount
if db.execute("DELETE FROM gone WHERE chat_id = ? AND at < ?", (cid, at)).rowcount:
changed.add(cid)

self._tx(run)
return n[0]
self._tx(run, chat_ids=changed)
return len(changed)

def chat_ids_named(self, name: str) -> List[str]:
"""The chats (none the account left) with exactly this name."""
Expand Down Expand Up @@ -1241,9 +1269,10 @@ def autoreply_chats(self) -> List[str]:

def autoreply_set(self, chat_id: str, on: bool, now: Optional[float] = None) -> None:
if on:
self._tx(lambda db: db.execute("INSERT OR IGNORE INTO autoreply (chat_id, at) VALUES (?, ?)", (chat_id, now or time.time())))
self._tx(lambda db: db.execute("INSERT OR IGNORE INTO autoreply (chat_id, at) VALUES (?, ?)",
(chat_id, now or time.time())), chat_ids=())
else:
self._tx(lambda db: db.execute("DELETE FROM autoreply WHERE chat_id = ?", (chat_id,)))
self._tx(lambda db: db.execute("DELETE FROM autoreply WHERE chat_id = ?", (chat_id,)), chat_ids=())

def runs_prune(self, before: float, keep: int, protect=()) -> None:
"""Forget runs older than before, and all but the newest keep; never one still starting or running, nor one
Expand All @@ -1264,7 +1293,7 @@ def run(db):
now = time.time()
for rid in [r for r, at in self._pruned_runs.items() if now - at > 86400.0]:
del self._pruned_runs[rid]
for rid in self._tx(run):
for rid in self._tx(run, chat_ids=()):
self._pruned_runs[rid] = now

def run_count(self) -> int:
Expand Down Expand Up @@ -1337,7 +1366,11 @@ def run(db):
return runs

with self._lock: # no run_put between the wipe and the ids it took out
before = self.changes
self._wiped_runs.update(self._tx(run))
if self.changes == before: # an empty wipe still starts a new generation
with self._chat_lock:
self._invalidate_chats()
self.snapshot_scope = (self.snapshot_scope[0] + 1, owner or self.snapshot_scope[1])
self._wiped_runs.update(self._pruned_runs) # pruned lately: a thread may still hold one of those too
self._pruned_runs.clear()
87 changes: 74 additions & 13 deletions core/openmate_core/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@
import contextlib
import math
import sys
from collections import deque
from collections import OrderedDict, deque
import datetime as _dt
import hashlib
import json
import logging
import threading
import time
import urllib.parse
from typing import Any, Callable, Dict, List, Optional, Tuple
from typing import Any, Callable, Dict, Iterable, List, NamedTuple, Optional, Tuple

from . import views
from .agent import BOT_THREAD_MOST
Expand Down Expand Up @@ -406,6 +406,7 @@ def run():


NEEDS_HOURS = 24 # an @me or a direct message older than this no longer needs the user (setting needs_hours)
NEEDS_CACHE_CHATS = 600
TALK_GAP = 3600.0 # the other side answered within this of my last message: the talk goes on, it is not a request
DONE_SLACK = 60.0 # a service's done mark this much older than a need's latest line still covers it (clock, rounding)
REOPENED = "reopened:" # a 处理完 mark's version brought back (恢复): the service's done mark leaves that one alone
Expand Down Expand Up @@ -442,6 +443,65 @@ def _talk_closed(msgs: List[dict], run: List[dict]) -> bool:
return not any(asks_something(r) for r in run)


class _NeedsMessages(NamedTuple):
last: dict
latest_at: float
closed: bool
mentioned: bool
mentions: List[dict]
senders: set

@classmethod
def from_rows(cls, rows: List[dict]) -> Optional[_NeedsMessages]:
messages = [r for r in rows if not views.is_system(r) and views.has_content(r)]
run = views.unanswered_run(messages)
if not run:
return None
return cls(run[-1], max(r.get("at") or 0 for r in rows), _talk_closed(messages, run),
any(r["at_me"] for r in run), [r for r in rows if r.get("at_me") and not r.get("mine")],
{r.get("sender_id") for r in rows if not r.get("mine")})


class _NeedsMessagesCache:
"""Share the message-derived parts of needs(), including the older @me, as read-only data across draws."""

def __init__(self):
self._lock = threading.Lock()
self._scope = None
self._entries: OrderedDict[str, Tuple[int, int, Optional[_NeedsMessages]]] = OrderedDict()

def read(self, store, chat_ids: Iterable[str], limit: int = 60) -> Dict[str, Optional[_NeedsMessages]]:
out, missing = {}, {}
with self._lock:
generation, versions = store.chat_versions(chat_ids)
scope = (store, generation)
if scope != self._scope:
self._entries.clear()
self._scope = scope
for cid, version in versions.items():
hit = self._entries.get(cid)
if hit is not None and hit[:2] == (version, limit):
self._entries.move_to_end(cid)
out[cid] = hit[2]
else:
missing[cid] = version
if not missing:
return out

loaded = {cid: _NeedsMessages.from_rows(rows) for cid, rows in store.inbox_rows_many(missing, limit).items()}
with self._lock:
current, versions = store.chat_versions(missing)
if scope == self._scope and generation == current:
for cid, summary in loaded.items():
if missing[cid] == versions[cid]: # a newer commit may have landed during the read
self._entries[cid] = (versions[cid], limit, summary)
self._entries.move_to_end(cid)
while len(self._entries) > NEEDS_CACHE_CHATS:
self._entries.popitem(last=False)
out.update(loaded)
return out


class ChatsToday:
"""What needs the user in the chats, from the store: unanswered direct chats and @me, today's traffic."""

Expand Down Expand Up @@ -511,27 +571,28 @@ def _read_needs(self, now, hours, me, only):
oldest = now - horizon
chats = app.store.chats_since(now - window, app.timing.inbox_most if only is None else len(only), only=only)
expires = min((c["last_at"] + window for c in chats), default=float("inf"))
batched = app.store.inbox_rows_many(c["id"] for c in chats)
cache = self._cache.get("messages")
if cache is None:
cache = self._cache.setdefault("messages", _NeedsMessagesCache())
batched = cache.read(app.store, (c["id"] for c in chats))
for chat in chats:
rows = batched[chat["id"]]
messages = [r for r in rows if not views.is_system(r) and views.has_content(r)]
run = views.unanswered_run(messages)
messages = batched[chat["id"]]
dm = views.chat_kind(chat) == "dm"
if not run or not dm and not any(r["at_me"] for r in run):
if messages is None or not dm and not messages.mentioned:
continue
if dm and _talk_closed(messages, run):
if dm and messages.closed:
closed += 1
continue
last = run[-1]
last = messages.last
thing = {"kind": "dm" if dm else "mention", "title": views.chat_name(chat, chat["id"]),
"sender": views.sender_of(last, me), "preview": one_line(views.text_of(last), 200), "last": last["id"]}
thing["_at"] = max((r.get("at") or 0) for r in rows) if rows else 0
thing["_version_at"] = next((r.get("at") or 0 for r in rows if r.get("id") == thing.get("last")), thing["_at"])
thing["_at"] = messages.latest_at
thing["_version_at"] = last.get("at") or 0
thing["_chat"] = chat
if thing["kind"] == "dm":
who = {chat.get("peer_id") or ""} if chat.get("peer_id") else {r.get("sender_id") for r in rows if not r.get("mine")}
who = {chat["peer_id"]} if chat.get("peer_id") else messages.senders
else:
thing["_ats"] = [r for r in rows if r.get("at_me") and not r.get("mine")]
thing["_ats"] = messages.mentions
who = {r.get("sender_id") for r in thing["_ats"]}
thing["_who"] = {w for w in who if w}
out.append(thing)
Expand Down
Loading
Loading