fix: expire schedule and attendee caches after one hour
This commit is contained in:
1 parent
dd5a6ef5ae
commit
cd7924d890
5 files changed
+61
-13
No files matched your search
@@ -106,10 +106,11 @@ members' names.
|
||||
| `payloads` | raw action responses, keyed e.g. `schedule:2026-07-25`, stamped with the local date |
|
||||
| `classes` | one row per class occurrence, so an ID resolves to date + program + limit |
|
||||
|
||||
Freshness is **per local calendar day**: a payload fetched today is reused, one from
|
||||
yesterday is a miss. Past days never change, so this is generous rather than risky; today's
|
||||
schedule can shift, which is what `--refresh` is for. Every command prints whether the answer
|
||||
came from cache or the wire.
|
||||
Schedules and attendee rosters have a **one-hour TTL**; workout content remains cached
|
||||
for the local calendar day. All payloads expire at midnight. The class-ID index is not
|
||||
subject to the hourly TTL. `bookings` queries bypass the payload cache entirely.
|
||||
Use `--refresh` before attendance decisions: even an hourly cache can predate a recent
|
||||
sign-in. Every command prints whether the answer came from cache or the wire.
|
||||
|
||||
Only `service.py` fetches, so caching cannot be forgotten at a call site.
|
||||
|
||||
|
||||
@@ -74,9 +74,12 @@ you never listed and it says so rather than guessing.
|
||||
## Local SQLite cache
|
||||
|
||||
`~/.cache/wodify/wodify.db` (override with `WODIFY_DB`), created mode `600` because it holds
|
||||
other members' names. Responses are stamped with the local date they were fetched on and
|
||||
reused for the rest of that day; anything older is a miss. Past days never change, so this is
|
||||
safe. Today's schedule can shift — that is what `--refresh` is for.
|
||||
other members' names. Schedules (including your reservation/sign-in status) and attendee
|
||||
rosters expire after **one hour**; the next query automatically fetches fresh data. Workout
|
||||
content stays cached for the local calendar day. All payloads expire at midnight.
|
||||
Use `--refresh` for immediate updates, especially before deciding attendance for a diary:
|
||||
a one-hour cache can still predate a recent sign-in. `bookings` queries already go directly
|
||||
to Wodify without this payload cache.
|
||||
|
||||
Every command states whether the answer came from cache or the network.
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
## 任务
|
||||
|
||||
1. 获取今天的日期(YYYY-MM-DD)
|
||||
2. 运行 `~/.local/bin/wodify list date <今天日期>` 查看当天课程
|
||||
2. 运行 `~/.local/bin/wodify list date <今天日期> --refresh` 查看当天课程(签到状态必须实时获取,一小时缓存也可能早于刚发生的签到)
|
||||
3. 检查是否有「你」预约了的课(YOU 列显示 booked / signed in)
|
||||
|
||||
## 判断逻辑
|
||||
|
||||
+13
-5
@@ -1,9 +1,8 @@
|
||||
"""Local SQLite cache.
|
||||
|
||||
Wodify data for a past day does not change, and even today's schedule changes
|
||||
slowly, so a same-day cache removes almost all network reads. Anything fetched
|
||||
is stored with the local date it was fetched on; a later query on that same date
|
||||
is served from disk.
|
||||
Schedules and attendee rosters expire after one hour because reservations and
|
||||
sign-in status change during the day. Workout content keeps a same-day cache.
|
||||
All payloads also expire at the local calendar-day boundary.
|
||||
|
||||
stdlib only (``sqlite3``), keeping the query path dependency-free.
|
||||
"""
|
||||
@@ -17,6 +16,8 @@ import sqlite3
|
||||
import stat
|
||||
from typing import Any, Iterable
|
||||
|
||||
DYNAMIC_PAYLOAD_TTL = _dt.timedelta(hours=1)
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS payloads (
|
||||
key TEXT PRIMARY KEY,
|
||||
@@ -78,13 +79,20 @@ def connect(path: pathlib.Path | None = None) -> sqlite3.Connection:
|
||||
|
||||
def get_payload(conn: sqlite3.Connection, key: str,
|
||||
*, on: str | None = None) -> tuple[Any, str] | None:
|
||||
"""Return ``(data, fetched_at)`` if cached on ``on`` (default today)."""
|
||||
"""Return a same-day payload, with a one-hour TTL for dynamic data."""
|
||||
row = conn.execute(
|
||||
"SELECT body, fetched_at FROM payloads WHERE key = ? AND fetched_on = ?",
|
||||
(key, on or today()),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
if key.startswith(("schedule:", "attendees:")):
|
||||
try:
|
||||
age = _dt.datetime.now() - _dt.datetime.fromisoformat(row["fetched_at"])
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
if not _dt.timedelta(0) <= age < DYNAMIC_PAYLOAD_TTL:
|
||||
return None
|
||||
try:
|
||||
return json.loads(row["body"]), row["fetched_at"]
|
||||
except json.JSONDecodeError:
|
||||
|
||||
@@ -44,6 +44,42 @@ def test_payload_overwrite_updates_in_place(conn):
|
||||
assert conn.execute("SELECT COUNT(*) FROM payloads").fetchone()[0] == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["schedule:2026-07-20", "attendees:123"])
|
||||
@pytest.mark.parametrize("age, fresh", [(3599, True), (3600, False), (7200, False), (-1, False)])
|
||||
def test_dynamic_payload_one_hour_ttl(conn, monkeypatch, key, age, fresh):
|
||||
now = _dt.datetime.combine(_dt.date.today(), _dt.time(12))
|
||||
|
||||
class Clock(_dt.datetime):
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return now
|
||||
|
||||
monkeypatch.setattr(store._dt, "datetime", Clock)
|
||||
store.put_payload(conn, key, {"status": "Reserved"})
|
||||
stamp = (now - _dt.timedelta(seconds=age)).isoformat()
|
||||
conn.execute("UPDATE payloads SET fetched_at = ? WHERE key = ?", (stamp, key))
|
||||
conn.commit()
|
||||
assert (store.get_payload(conn, key) is not None) is fresh
|
||||
|
||||
|
||||
def test_workout_keeps_same_day_cache(conn):
|
||||
key = "workout:2026-07-20:133059"
|
||||
store.put_payload(conn, key, {"name": "Example WOD"})
|
||||
stamp = _dt.datetime.combine(_dt.date.today(), _dt.time.min).isoformat()
|
||||
conn.execute("UPDATE payloads SET fetched_at = ? WHERE key = ?", (stamp, key))
|
||||
conn.commit()
|
||||
hit = store.get_payload(conn, key)
|
||||
assert hit is not None
|
||||
assert hit[0] == {"name": "Example WOD"}
|
||||
|
||||
|
||||
def test_dynamic_payload_invalid_timestamp_is_a_miss(conn):
|
||||
store.put_payload(conn, "schedule:2026-07-20", {})
|
||||
conn.execute("UPDATE payloads SET fetched_at = 'invalid'")
|
||||
conn.commit()
|
||||
assert store.get_payload(conn, "schedule:2026-07-20") is None
|
||||
|
||||
|
||||
ROWS = [
|
||||
{"class_id": "190917816", "name": "CrossFit: 5:30 PM", "start": "17:30:00",
|
||||
"end": "18:30:00", "program_id": "133059", "coach": "Pat Doyle",
|
||||
|
||||
Reference in new issue
Block a user