Repository navigation
feat(plugins): add plugin key-value store - #557
Conversation
Give plugin hooks `ctx.store`, a small key-value store across requests: get, set (with TTL), delete and an atomic increment with an optional limit (fixed window: the TTL is set when the counter is created). - One shared `plugin_store` collection in the first database of `db.dbs` (TTL index on `expires_at`, index on `ns`, created by `create_app()`); without database, a per-process memory backend. - Namespace per distribution (PEP 503 name; built-ins: `foca`). - `plugins.defaults.store` (`enabled`, `max_entry_size`, `max_ttl`) with per-plugin overrides in `plugins.available.<id>.store`; a plugin whose store is off gets the memory backend. - Calls are bounded by the hook deadline; database errors and timeouts raise `StoreError`, which fails the alternative. - `PluginHarness.store` for plugin tests. Closes #550 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe `ctx.store` in the plugin guide (API, limits, namespaces, modes, errors, personal data, testing), the `store` settings and the `plugin_store` collection in the configuration docs, and add `foca.plugins.store` to the API reference. Refs #550 Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Increment with plain conditional updates decided by the server (`$inc` with bounds, then insert or replace of absent or expired entries, retried on races) instead of an aggregation pipeline whose result was re-derived in Python: results no longer depend on the client's datetime options, and mongomock runs it (apps' tests). - Pin time zone aware datetimes on the store collection. - Counters stay within -(2^53 - 1) as well; TTLs are at least 1 ms and expiries are stored in milliseconds; `max_ttl` is finite, at most 10 years. - Start apps with a warning if the indexes can't be created; writes create them first, so no entry is written without the TTL index. - Warn if plugins of one distribution disagree on the off switch. - `StoreEntry` is public (backend protocol); simpler `_guard` and integer checks; comments on the counter rules. - Docs: complete example, counters via `get()`, index and off-switch behaviour, mongomock. Refs #550 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Increments now replace entries whose `expires_at` is missing or no date, which all other calls already treat as absent; before, they failed with "busy" forever. Also share the counter bounds in one helper, re-wrap a docstring, clarify tests and list the remaining public names of `foca.plugins.store` in the API reference. Refs #550 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideAdds a configurable plugin-scoped key-value store exposed as ctx.store, with local memory and shared MongoDB backends, TTL-indexed persistence, atomic bounded counters, distribution namespaces, deadline-aware errors, harness support, startup integration, documentation, and comprehensive tests. Sequence diagram for a shared plugin store requestsequenceDiagram
participant Hook as Plugin hook
participant Store as ctx.store
participant Mongo as MongoStoreBackend
participant DB as MongoDB plugin_store
Hook->>Store: increment(key, by, ttl, limit)
Store->>Mongo: increment(namespace, key, by, limit)
Mongo->>DB: Conditional atomic update
alt increment within bounds
DB-->>Mongo: New counter value
Mongo-->>Store: New counter value
Store-->>Hook: New counter value
else limit exceeded or lower bound reached
DB-->>Mongo: No update
Mongo-->>Store: None
Store-->>Hook: None
end
Entity relationship diagram for plugin store documentserDiagram
PLUGIN_STORE {
string _id PK
string ns INDEX
string key
string value
integer n
datetime expires_at TTL
}
PLUGIN_STORE }o--|| NAMESPACE : belongs_to
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #557 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 55 56 +1
Lines 6667 7008 +341
==========================================
+ Hits 6667 7008 +341
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 9 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/plugins/store.py" line_range="258" />
<code_context>
+ entry: Entry.
+ now: Current time.
+ """
+ self._entries[(ns, key)] = entry
+ self._writes += 1
+ if self._writes % self._SWEEP_INTERVAL == 0:
</code_context>
<issue_to_address>
**Distinct keys exhaust storage**
When a workload writes many distinct keys before their TTLs expire, `MemoryStoreBackend._write` and `MongoStoreBackend.set` accept new keys without an aggregate limit, so retained entries grow until process memory or database storage is exhausted and the gateway or database can fail.
Enforce an aggregate entry or byte quota for writes to both backends.
Also at `foca/plugins/store.py:492-499`.
</issue_to_address>
### Comment 2
<location path="foca/plugins/store.py" line_range="805" />
<code_context>
+ """
+ _check_key(key)
+ try:
+ dumped = json.dumps(
+ value, separators=(",", ":"), ensure_ascii=False, allow_nan=False
+ )
</code_context>
<issue_to_address>
**Oversized values exhaust resources**
When a plugin passes a very large value to `set()`, `Store.set` serializes and parses the entire value before checking `max_entry_size`, creating large temporary strings and objects; the work can exhaust memory or keep the hook worker occupied past its deadline before the value is rejected.
Enforce the size limit during serialization, before building or parsing the full value.
</issue_to_address>
### Comment 3
<location path="foca/plugins/store.py" line_range="205" />
<code_context>
+ Returns:
+ Error.
+ """
+ return StoreError(f"Key {key!r} holds a value that is no counter")
+
+
</code_context>
<issue_to_address>
**Personal keys enter logs**
When a caller can make a plugin increment a key containing personal data, and that key already holds a non-counter value, `_counter_conflict` embeds the raw key in `StoreError`; `PluginHost._call` logs the exception message through `describe_error`, which does not redact keys, so the operator’s logs disclose the key.
Omit the key from the conflict error, or redact/pseudonymize it before logging.
</issue_to_address>
### Comment 4
<location path="foca/foca.py" line_range="215" />
<code_context>
+ try:
+ # the indexes of the plugins' store; writes to the store
+ # create them too, so the app may start without them
+ host.setup_store()
+ except PyMongoError as exc:
+ logger.warning(
</code_context>
<issue_to_address>
**Database stall blocks app startup**
When mongoDB accepts the connection but stops responding to the index command, `create_app()` calls `host.setup_store()`, which calls `MongoStoreBackend.setup()` and waits for `create_index()` without a timeout; the app therefore remains stuck starting instead of logging the warning and continuing.
Bound startup index creation with a finite timeout so `create_app()` can reach its existing warning-and-continue path.
Also at `foca/plugins/store.py:428`.
</issue_to_address>
### Comment 5
<location path="foca/plugins/store.py" line_range="409" />
<code_context>
+ """
+ # time zone aware UTC times whatever the client's options (e.g.,
+ # `datetime_conversion` in `MONGO_URI`), as results depend on them
+ self.collection: Collection[dict[str, Any]] = collection.with_options(
+ codec_options=CodecOptions(
+ tz_aware=True,
</code_context>
<issue_to_address>
**Stale reads fail counter increments**
When the MongoDB URI selects secondary reads and a secondary has not caught up with a store write, `MongoStoreBackend.get` and the increment recovery `find_one` inherit the secondary read preference, so they can return stale entries; a saturated counter then exhausts its retries and raises `StoreError` instead of returning `None`.
Use primary reads for store lookups and increment recovery reads.
Also at `foca/plugins/store.py:458`, `foca/plugins/store.py:579`.
</issue_to_address>
### Comment 6
<location path="foca/plugins/store.py" line_range="352" />
<code_context>
+ Whether an entry that had not expired was deleted.
+ """
+ with self._lock:
+ entry = self._live(ns, key, now)
+ if entry is None:
+ return False
</code_context>
<issue_to_address>
**Expired calls still change counters**
When a memory-backend operation waits for a contended lock long enough for the hook deadline to pass, `Store._timeout()` runs before `MemoryStoreBackend.increment()` acquires its lock, and the memory backend does not bound lock acquisition or recheck the deadline. If the lock remains contended past the deadline, an abandoned hook can still increment its counter after timing out.
Bound lock acquisition by the remaining deadline and recheck it before performing the operation.
</issue_to_address>
### Comment 7
<location path="foca/plugins/engine.py" line_range="453" />
<code_context>
self.plugins: dict[str, LoadedPlugin] = (
dict(plugins) if plugins is not None else load_plugins(conf, api=api)
)
+ self._store_backend: StoreBackend = store_backend or MemoryStoreBackend()
+ self._stores = _store_settings(self.plugins, conf, self._store_backend)
self._executor = _Executor(conf.defaults.workers)
</code_context>
<issue_to_address>
**Supplied backend is replaced**
When a caller supplies a `StoreBackend` whose truth value is false or whose length is zero, `PluginHost.__init__` replaces the supplied backend with `MemoryStoreBackend`, so plugins write to process-local storage instead of the caller's backend and lose its sharing or persistence behavior.
Choose the default backend only when `store_backend is None`.
</issue_to_address>
### Comment 8
<location path="tests/plugins/test_plugin_store.py" line_range="518" />
<code_context>
+ """`get` trusts the query's filter; `delete` checks the deleted expiry."""
+ collection = MagicMock()
+ collection.with_options.return_value = collection
+ collection.find_one.return_value = {"_id": "x", "value": "1"}
+ collection.find_one_and_delete.return_value = {"_id": "x"}
+ store = make_store(MongoStoreBackend(collection), Clock())
</code_context>
<issue_to_address>
**Expiry filter regression goes undetected**
When `MongoStoreBackend.get` stops filtering out expired entries in its query, `test_unchecked_documents` still passes: the `MagicMock` returns the document regardless of the query, and the `store.get("k") == 1` assertion checks only its decoded value. Removing the expiry predicate therefore goes undetected.
Assert that the `find_one` query includes the expiry predicate, or use a collection fake that applies the query filter.
</issue_to_address>
### Comment 9
<location path="tests/plugins/test_plugin_store.py" line_range="622" />
<code_context>
+ def test_harness(self) -> None:
+ """Hooks get a store; the harness shares its entries with tests."""
+ harness = PluginHarness(CountingPlugin)
+ harness.run_request(make_inbound({}))
+ assert harness.executions[0].annotations == {
+ "count": 1,
</code_context>
<issue_to_address>
**Cross-host sharing goes untested**
When hosts report `mode == "shared"` but their backends do not share entries, `TestEngine.test_shared` creates one harness and makes one request, so its `shared` mode and initial count assertions pass even if another host cannot see that host’s entries. `TestFromConfig.test_host` likewise checks only the mode before closing each host, not whether their entries are shared.
Have one host write an entry and a second host using the same shared backend read or increment it, including a check of the `from_config` wiring.
Also at `tests/plugins/test_plugin_store.py:750`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 9 findings to address first, and the store persists plugin values and counters in MongoDB, and its TTL index deletes expired entries; if expiry or namespace isolation is wrong, state can be lost or read across plugin distributions. Reverting removes the feature but cannot restore deleted entries or undo data already exposed.
Blocking findings: foca/plugins/store.py:258, foca/plugins/store.py:805, foca/plugins/store.py:205, foca/foca.py:215, foca/plugins/store.py:409, and 4 more
- Check the size of values before the slower I-JSON checks. - Leave keys, which may be personal data, out of counter errors. - Bound the index setup by 10 s, so that startup doesn't stall. - Read entries from the primary, whatever the client's options. - Wait for the memory backend's lock at most until the deadline. - Keep falsy backends passed to `PluginHost`. - Test the expiry filter of reads and sharing across hosts. Refs #550 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Gives gateway plugins a small key-value store,
ctx.store, across requests, processes and replicas (first part of #545).get(key, default=None),set(key, value, *, ttl=None),delete(key), and an atomicincrement(key, by=1, *, ttl=None, limit=None)that returns the new value, orNonewithout incrementing if it would exceedlimit(or go below -(2^53 - 1)). Counters get their TTL when created (fixed window, e.g. per day).key_for(*parts)derives pseudonymous keys (SHA-256 of namespace and parts) from e.g. user identifiers.plugin_storecollection in the first database ofdb.dbs, documents{_id: "<ns>\x1f<key>", ns, key, value | n, expires_at}, a TTL index onexpires_atand an index onns. Increments are conditional single-document updates decided by the server ($incwithin the bounds; else insert or replace of an absent or expired entry; retried on races, at most 5 times). Reads filter out expired entries, as MongoDB's TTL monitor runs about once a minute. Works with mongomock too (apps' tests).create_app()creates them; if that fails (e.g. database not up yet), the app logs a warning and starts, and writes create them first, so no entry is written without the TTL index.ctx.store.modeisshared,localoroff. A warning is logged if plugins of one distribution disagree on the switch.foca); plugins can't choose it.plugins.defaults.store(enabled,max_entry_size4 KiB,max_ttl30 days, at most 10 years, which entries without TTL get) with per-plugin overrides inplugins.available.<id>.store. No namespace size limit yet (feat(plugins): limit store namespace size #552).pymongo.timeout); database errors and timeouts raisefoca.plugins.StoreError(aPluginError), which fails the alternative like any other error. Argument errors raiseValueError.PluginHarness.storegives tests the same entries.storesettings, collection, indexes), API reference.Design decisions (from the design note, decided by the maintainer): one shared collection; off switch falls back to memory; namespace per distribution; no namespace size limit in v1. The listing of stored data and the storage mode follows in #551.
Note:
StoreErrorlives infoca/plugins/store.py, notfoca/plugins/errors.pyas the design note sketched:errors.pyholds the client-facing gateway errors (problem details), whileStoreErroris a plugin error.Closes #550
Verification
coverage run -m pytestwith a local MongoDB 7.0 on port 12345: 3217 passed (after the Sourcery fixes), 2 skipped (one of them pre-existing; the other is the thread test on mongomock, which isn't thread-safe), coverage 100%. The store tests run on the memory backend, mongomock and a real MongoDB (TTL expiry with an injected clock, atomic increments from 10 threads against a limit, document layout, timeouts,datetime_conversion=DATETIME_MSclients).ruff check,ruff format --check,mypy: clean.pre-commit run --all-files(incl. semgrep and ast-grep): passed.mkdocs build --strict: passed.dev(CI passed; tests on Python 3.11 to 3.15 with MongoDB 7.0 and 8.0, lowest dependencies, integration, chart, image scans, Codecov patch and project, Read the Docs).Declined review findings
PluginHost.store_settingsstays public (quality review suggested making it private): the plugin listing of feat(plugins): list plugin storage #551 uses it to show the storage mode.PluginHarness.storestays a property next to the class docstring; it is listed underAttributesnow (low, cosmetic).max_ttlat the latest, and values and keys are capped in size.Sourcery's other eight findings are fixed in 430736d: size check before the I-JSON checks, no keys in counter errors, index setup bounded by 10 s, primary reads, lock wait bounded by the deadline, falsy backends kept, and two test gaps.
Reviews: two rounds of adversarial and quality review; all high/medium findings fixed (limit bypass with
datetime_conversionclient options, increments failing under mongomock, startup failure without index rights, public backend protocol returning a private type, duplicated counter rules), as well as the cheap lows (boundedmax_ttl, lower counter bound, millisecond TTLs, namespace split warning, entries without valid expiry, docs example).Open questions
None.
🤖 Generated with Claude Code