dsh-feiyu-memgate 0.3.2 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +73 -12
- package/README.md +68 -11
- package/README.zh.md +93 -36
- package/client/README.md +267 -0
- package/client/art/mascot-asleep.webp +0 -0
- package/client/art/mascot-busy.webp +0 -0
- package/client/art/mascot-nag.webp +0 -0
- package/client/art/mascot-ready.webp +0 -0
- package/client/art/mascot-trouble.webp +0 -0
- package/client/client.js +4226 -1269
- package/client/src/clipboard.cjs +52 -0
- package/client/src/constants.cjs +43 -0
- package/client/src/fields.cjs +960 -0
- package/client/src/hooks.cjs +220 -0
- package/client/src/i18n.cjs +444 -0
- package/client/src/index.cjs +69 -0
- package/client/src/kit/controls.cjs +189 -0
- package/client/src/kit/icons.cjs +40 -0
- package/client/src/kit/layout.cjs +124 -0
- package/client/src/layout.cjs +143 -0
- package/client/src/model/changelog.cjs +29 -0
- package/client/src/model/feedback.cjs +168 -0
- package/client/src/model/form.cjs +83 -0
- package/client/src/model/models.cjs +87 -0
- package/client/src/model/overview.cjs +111 -0
- package/client/src/model/page.cjs +104 -0
- package/client/src/model/status.cjs +57 -0
- package/client/src/model/trial.cjs +111 -0
- package/client/src/net.cjs +101 -0
- package/client/src/react.cjs +11 -0
- package/client/src/theme/page.css +1284 -0
- package/client/src/theme/styles.cjs +43 -0
- package/client/src/view/feedback.cjs +180 -0
- package/client/src/view/field-row.cjs +98 -0
- package/client/src/view/hero.cjs +54 -0
- package/client/src/view/markdown.cjs +96 -0
- package/client/src/view/models.cjs +154 -0
- package/client/src/view/page.cjs +199 -0
- package/client/src/view/settings-tab.cjs +78 -0
- package/client/src/view/tabs.cjs +71 -0
- package/client/src/view/trial.cjs +84 -0
- package/docs/DETAIL.en.md +55 -6
- package/docs/DETAIL.md +63 -14
- package/locale/zh.json +1 -1
- package/package.json +2 -1
- package/python/GATEWAY_VERSION.json +37 -31
- package/python/feiyu_memgate/backends/_sqlfile.py +293 -0
- package/python/feiyu_memgate/backends/base.py +121 -6
- package/python/feiyu_memgate/backends/embedding.py +265 -178
- package/python/feiyu_memgate/backends/hybrid.py +330 -83
- package/python/feiyu_memgate/backends/inmemory.py +115 -24
- package/python/feiyu_memgate/backends/openviking.py +7 -10
- package/python/feiyu_memgate/backends/sqlite.py +129 -145
- package/python/feiyu_memgate/builtins.py +1 -0
- package/python/feiyu_memgate/cli.py +124 -20
- package/python/feiyu_memgate/client/block.py +4 -2
- package/python/feiyu_memgate/client/http.py +106 -19
- package/python/feiyu_memgate/client/local.py +4 -3
- package/python/feiyu_memgate/config.py +118 -24
- package/python/feiyu_memgate/core/limits.py +2 -1
- package/python/feiyu_memgate/core/pool.py +29 -2
- package/python/feiyu_memgate/core/recall.py +179 -10
- package/python/feiyu_memgate/core/redact.py +4 -2
- package/python/feiyu_memgate/core/stages.py +52 -9
- package/python/feiyu_memgate/core/tidy.py +2 -1
- package/python/feiyu_memgate/core/watch.py +3 -2
- package/python/feiyu_memgate/core/write.py +9 -3
- package/python/feiyu_memgate/forgetting/archive.py +38 -10
- package/python/feiyu_memgate/forgetting/engine.py +46 -10
- package/python/feiyu_memgate/forgetting/stage.py +4 -2
- package/python/feiyu_memgate/gateway/app.py +168 -272
- package/python/feiyu_memgate/gateway/fields.py +121 -0
- package/python/feiyu_memgate/gateway/policies.py +162 -0
- package/python/feiyu_memgate/gateway/server.py +12 -4
- package/python/feiyu_memgate/gateway/tokens.py +137 -0
- package/python/feiyu_memgate/gateway/validate.py +120 -0
- package/python/feiyu_memgate/identity.py +152 -0
- package/python/feiyu_memgate/model.py +170 -2
- package/python/feiyu_memgate/registry.py +6 -3
- package/python/feiyu_memgate/tools/crypto.py +5 -4
- package/python/feiyu_memgate/tools/evaluate.py +2 -1
- package/python/feiyu_memgate/tools/tenants.py +2 -0
- package/src/block.js +9 -3
- package/src/capture.js +98 -0
- package/src/catalogue.js +4 -4
- package/src/changelog.js +72 -0
- package/src/client.js +145 -10
- package/src/commands.js +112 -62
- package/src/config.js +139 -62
- package/src/followup.js +139 -0
- package/src/gateway.js +79 -4
- package/src/migrate.py +54 -9
- package/src/mirror.py +44 -7
- package/src/plugin.js +416 -412
- package/src/pool.js +298 -0
- package/src/recent.js +68 -0
- package/src/relevance.js +80 -0
- package/src/routes.js +320 -0
- package/src/setup.js +36 -36
- package/src/shared.js +77 -0
- package/src/tiers.js +4 -4
- package/src/time.js +27 -0
- package/src/tools.js +164 -0
|
@@ -55,13 +55,17 @@ from .errors import ConfigError
|
|
|
55
55
|
from .forgetting.archive import Archive
|
|
56
56
|
from .forgetting.engine import REQUIRED as FORGETTING_CAPABILITIES, Forgetting
|
|
57
57
|
from .forgetting.ledger import Ledger
|
|
58
|
+
from .gateway import policies
|
|
58
59
|
from .gateway.app import Gateway, stderr_log, usable_token, MIN_TOKEN_CHARS
|
|
59
|
-
from .model import TENANT_BINDINGS, ClientPolicy
|
|
60
|
+
from .model import (AUDIENCES, DEFAULT_ORIGINS, FIELDS, ORIGINS, TENANT_BINDINGS, ClientPolicy, valid_person,
|
|
61
|
+
valid_platform)
|
|
60
62
|
|
|
61
63
|
SERVER_DEFAULTS = {"host": "127.0.0.1", "port": 8080}
|
|
62
64
|
_POLICY_KEYS = {"token_env", "recall", "write", "tenants", "public", "daily_writes", "daily_writes_total",
|
|
63
|
-
"rate_limit", "rate_limit_total", "pin_writes", "tenant_binding", "tenant_token_generation"
|
|
64
|
-
|
|
65
|
+
"rate_limit", "rate_limit_total", "pin_writes", "tenant_binding", "tenant_token_generation",
|
|
66
|
+
"audience", "explain", "origins", "fields", "platforms", "only_for"}
|
|
67
|
+
_TOP_KEYS = {"server", "stores", "tenants", "clients", "recall", "write", "redaction", "forgetting", "identity"}
|
|
68
|
+
_IDENTITY_KEYS = {"type", "hash_key_env", "people"}
|
|
65
69
|
|
|
66
70
|
# What each fixed section may hold: key -> checker(where, value). "stages"/"guards" are piece lists.
|
|
67
71
|
_POSITIVE_INT, _POSITIVE_NUMBER, _NUMBER_AT_LEAST_0 = "positive integer", "positive number", "number >= 0"
|
|
@@ -165,6 +169,40 @@ def _limit(where, value):
|
|
|
165
169
|
return value
|
|
166
170
|
|
|
167
171
|
|
|
172
|
+
def _audience(where, value):
|
|
173
|
+
"""A declared audience level, or ConfigError naming the setting."""
|
|
174
|
+
if value not in AUDIENCES:
|
|
175
|
+
raise ConfigError("%s.audience must be one of %s" % (where, ", ".join('"%s"' % level for level in AUDIENCES)))
|
|
176
|
+
return value
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _split_audience(kind, name, spec):
|
|
180
|
+
"""(spec without its audience key, the audience or None): the key is the loader's, never the backend's."""
|
|
181
|
+
if "audience" not in spec:
|
|
182
|
+
return spec, None
|
|
183
|
+
rest = {key: value for key, value in spec.items() if key != "audience"}
|
|
184
|
+
return rest, _audience("%s.%s" % (kind, name), spec["audience"])
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _names_of(where, key, value, known, default, kind):
|
|
188
|
+
"""A list setting whose entries are each one of `known`, as a tuple (`default` when absent)."""
|
|
189
|
+
if value is None:
|
|
190
|
+
return default
|
|
191
|
+
if not isinstance(value, list) or not all(isinstance(item, str) and item in known for item in value):
|
|
192
|
+
raise ConfigError("%s.%s must be a list of %s, each one of %s" % (
|
|
193
|
+
where, key, kind, ", ".join('"%s"' % item for item in known)))
|
|
194
|
+
return tuple(value)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _checked_names(where, key, value, valid, kind):
|
|
198
|
+
"""A list setting whose entries each pass `valid`, as a tuple (empty when absent)."""
|
|
199
|
+
if value is None:
|
|
200
|
+
return ()
|
|
201
|
+
if not isinstance(value, list) or not all(valid(item) for item in value):
|
|
202
|
+
raise ConfigError("%s.%s must be a list of %s" % (where, key, kind))
|
|
203
|
+
return tuple(value)
|
|
204
|
+
|
|
205
|
+
|
|
168
206
|
def client_policy(name, spec):
|
|
169
207
|
"""The ClientPolicy of one [clients.<name>] table, every setting checked (ConfigError naming it)."""
|
|
170
208
|
where = "clients.%s" % name
|
|
@@ -178,7 +216,7 @@ def client_policy(name, spec):
|
|
|
178
216
|
if not isinstance(recall, list) or not all(isinstance(s, str) for s in recall):
|
|
179
217
|
raise ConfigError("%s.recall must be a list of store names" % where)
|
|
180
218
|
recall = tuple(recall)
|
|
181
|
-
for key, kind in (("write", str), ("tenants", str), ("public", bool), ("pin_writes", bool)):
|
|
219
|
+
for key, kind in (("write", str), ("tenants", str), ("public", bool), ("pin_writes", bool), ("explain", bool)):
|
|
182
220
|
value = spec.get(key)
|
|
183
221
|
if value is not None and not isinstance(value, kind):
|
|
184
222
|
raise ConfigError("%s.%s must be %s" % (where, key, kind.__name__))
|
|
@@ -200,12 +238,24 @@ def client_policy(name, spec):
|
|
|
200
238
|
if token_env is None and binding == "token":
|
|
201
239
|
raise ConfigError("%s.token_env is required with tenant_binding = \"token\": it names the minting secret"
|
|
202
240
|
% where)
|
|
241
|
+
origins = _names_of(where, "origins", spec.get("origins"), ORIGINS, DEFAULT_ORIGINS, "an origin")
|
|
242
|
+
fields = _names_of(where, "fields", spec.get("fields"), FIELDS, (), "a record field")
|
|
243
|
+
platforms = _checked_names(where, "platforms", spec.get("platforms"), valid_platform,
|
|
244
|
+
"platform names (lower case letters, digits, _ . -)")
|
|
245
|
+
only_for = _checked_names(where, "only_for", spec.get("only_for"), valid_person,
|
|
246
|
+
"names of people in [identity.people]")
|
|
247
|
+
audience = _audience(where, spec["audience"]) if "audience" in spec else None
|
|
248
|
+
public = spec.get("public")
|
|
249
|
+
if public is None:
|
|
250
|
+
public = audience is not None and audience != "owner" # derived; a stated one is checked by the Gateway
|
|
203
251
|
return ClientPolicy(
|
|
204
252
|
name=name, recall=recall, write=spec.get("write"), tenants=spec.get("tenants"),
|
|
205
|
-
public=
|
|
253
|
+
public=public, audience=audience, daily_writes=spec.get("daily_writes"),
|
|
206
254
|
daily_writes_total=spec.get("daily_writes_total"), rate_limit=spec.get("rate_limit", 60),
|
|
207
255
|
rate_limit_total=spec.get("rate_limit_total"), pin_writes=spec.get("pin_writes", False),
|
|
208
|
-
|
|
256
|
+
explain=spec.get("explain", False), tenant_binding=binding,
|
|
257
|
+
tenant_token_generation=spec.get("tenant_token_generation", 1), origins=origins, fields=fields,
|
|
258
|
+
platforms=platforms, only_for=only_for,
|
|
209
259
|
)
|
|
210
260
|
|
|
211
261
|
|
|
@@ -234,13 +284,15 @@ def _pieces(kind, specs, env, where, defaults, services=None):
|
|
|
234
284
|
return out
|
|
235
285
|
|
|
236
286
|
|
|
237
|
-
_PROFILE_STAGES = ("min_score", "relative_score")
|
|
287
|
+
_PROFILE_STAGES = ("min_score", "relative_score", "linked")
|
|
238
288
|
|
|
239
289
|
|
|
240
290
|
def _with_profile(specs, profile):
|
|
241
|
-
"""`specs` (a recall stage list, or None for the default one) with `profile` added to every min_score
|
|
242
|
-
relative_score entry that does not set its own `profile
|
|
243
|
-
|
|
291
|
+
"""`specs` (a recall stage list, or None for the default one) with `profile` added to every min_score,
|
|
292
|
+
relative_score and linked entry that does not set its own `profile` (for linked it only decides the default of
|
|
293
|
+
max_added: 0 under "precise"). No profile (None) leaves the entries alone: the
|
|
294
|
+
stages then use their own default, "broad". An explicit "precise" is added like any other. Entries that are not a
|
|
295
|
+
name or a table are left for _pieces to refuse."""
|
|
244
296
|
if profile is None:
|
|
245
297
|
return specs
|
|
246
298
|
if specs is None:
|
|
@@ -281,14 +333,16 @@ def _check_enforced(clients, stages, guards):
|
|
|
281
333
|
and not _enforced(guards, "daily_writes"):
|
|
282
334
|
raise ConfigError("%s has a daily write cap, but no write guard enforces daily_writes: "
|
|
283
335
|
"add \"daily_cap\" to [write] guards" % where)
|
|
284
|
-
if
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
336
|
+
if policy.public:
|
|
337
|
+
if policy.can_recall and not _enforced(stages, "redaction"):
|
|
338
|
+
raise ConfigError("%s is public and may recall, but no recall stage enforces redaction: "
|
|
339
|
+
"add \"redact\" to [recall] stages" % where)
|
|
340
|
+
if policy.can_write and not _enforced(guards, "redaction"):
|
|
341
|
+
raise ConfigError("%s is public and may write, but no write guard enforces redaction: "
|
|
342
|
+
"add \"redact\" to [write] guards" % where)
|
|
343
|
+
if policy.reach != "owner" and policy.can_recall and not _enforced(stages, "record_audience"):
|
|
344
|
+
raise ConfigError("%s shows what it recalls to other people, but no recall stage checks each record's "
|
|
345
|
+
"audience: add \"record_audience\" to [recall] stages" % where)
|
|
292
346
|
|
|
293
347
|
|
|
294
348
|
_FORGETTING_KEYS = {"ledger", "archive", "stores", "demote_below", "forget_below", "archive_days",
|
|
@@ -303,7 +357,7 @@ def _number(where, value, low=None, high=None):
|
|
|
303
357
|
return value
|
|
304
358
|
|
|
305
359
|
|
|
306
|
-
def _forgetting(cfg, stores, tenants, wall):
|
|
360
|
+
def _forgetting(cfg, stores, tenants, wall, audiences=None):
|
|
307
361
|
"""The Forgetting service from [forgetting], or None when there is no such section.
|
|
308
362
|
Returns (forgetting, sweep_every_hours)."""
|
|
309
363
|
if "forgetting" not in cfg:
|
|
@@ -349,11 +403,38 @@ def _forgetting(cfg, stores, tenants, wall):
|
|
|
349
403
|
raise ConfigError("forgetting: cannot open the ledger or archive file: %s" % type(error).__name__) from None
|
|
350
404
|
forgetting = Forgetting(ledger, archive, curve, stores=managed, demote_below=demote, forget_below=forget,
|
|
351
405
|
archive_days=days, pin_refs=pin_refs, max_forget_fraction=max_fraction,
|
|
352
|
-
max_forget_min=int(max_min),
|
|
406
|
+
max_forget_min=int(max_min), audiences=audiences,
|
|
353
407
|
wall=wall or time.time)
|
|
354
408
|
return forgetting, hours
|
|
355
409
|
|
|
356
410
|
|
|
411
|
+
def _identity(cfg, env, clients):
|
|
412
|
+
"""The identity provider from [identity], or None when there is no such section.
|
|
413
|
+
|
|
414
|
+
A client that may write can meet an account nobody listed, so then the key named by hash_key_env must be
|
|
415
|
+
set; for a gateway whose clients only read it is optional (a variable that is not set is then no key)."""
|
|
416
|
+
if "identity" not in cfg:
|
|
417
|
+
return None
|
|
418
|
+
spec = _table(cfg, "identity")
|
|
419
|
+
if spec.get("type") == "table":
|
|
420
|
+
unknown = set(spec) - _IDENTITY_KEYS
|
|
421
|
+
if unknown:
|
|
422
|
+
raise ConfigError("identity: unknown setting %s (known: %s)" % (
|
|
423
|
+
", ".join(sorted(unknown)), ", ".join(sorted(_IDENTITY_KEYS))))
|
|
424
|
+
name = spec.get("hash_key_env")
|
|
425
|
+
if name is not None:
|
|
426
|
+
if not isinstance(name, str) or not name:
|
|
427
|
+
raise ConfigError("identity.hash_key_env must name an environment variable")
|
|
428
|
+
if not env.get(name) and not any(policy.can_write for policy in clients.values()):
|
|
429
|
+
spec = {key: value for key, value in spec.items() if key != "hash_key_env"}
|
|
430
|
+
# The table of people is not resolved: nothing in it names the environment, and an error about a stray
|
|
431
|
+
# "<name>_env" key there would quote its value, which may be an account.
|
|
432
|
+
resolved = resolve_env({key: value for key, value in spec.items() if key != "people"}, env, "identity")
|
|
433
|
+
if "people" in spec:
|
|
434
|
+
resolved["people"] = spec["people"]
|
|
435
|
+
return registry.create("identity", resolved)
|
|
436
|
+
|
|
437
|
+
|
|
357
438
|
def _close_all(pieces):
|
|
358
439
|
"""Close what a failed build already opened (files, connections). Never raises."""
|
|
359
440
|
for piece in pieces:
|
|
@@ -375,14 +456,18 @@ def build_gateway(cfg, env=None, log=stderr_log, wall=None, **overrides):
|
|
|
375
456
|
if unknown:
|
|
376
457
|
raise ConfigError("unknown section %s" % ", ".join(sorted(unknown)))
|
|
377
458
|
# The fixed sections first: a typo there is found before anything is opened.
|
|
378
|
-
server, recall_cfg, write_cfg, redaction = (
|
|
459
|
+
server, recall_cfg, write_cfg, redaction = (
|
|
460
|
+
_section(cfg, name) for name in ("server", "recall", "write", "redaction"))
|
|
379
461
|
|
|
380
462
|
opened = []
|
|
381
463
|
try:
|
|
382
|
-
stores = {}
|
|
464
|
+
stores, audiences = {}, {}
|
|
383
465
|
for name, spec in _table(cfg, "stores").items():
|
|
384
466
|
if not isinstance(spec, dict):
|
|
385
467
|
raise ConfigError("[stores.%s] must be a table" % name)
|
|
468
|
+
spec, audience = _split_audience("stores", name, spec)
|
|
469
|
+
if audience is not None:
|
|
470
|
+
audiences[name] = audience
|
|
386
471
|
stores[name] = registry.create("backend", resolve_env(spec, env, "stores." + name))
|
|
387
472
|
opened.append(stores[name])
|
|
388
473
|
|
|
@@ -392,6 +477,9 @@ def build_gateway(cfg, env=None, log=stderr_log, wall=None, **overrides):
|
|
|
392
477
|
raise ConfigError("[tenants.%s] must be a table" % name)
|
|
393
478
|
if name in stores:
|
|
394
479
|
raise ConfigError("tenants.%s has the same name as a store" % name)
|
|
480
|
+
spec, audience = _split_audience("tenants", name, spec)
|
|
481
|
+
if audience is not None:
|
|
482
|
+
audiences[name] = audience
|
|
395
483
|
tenants[name] = registry.create("tenants", resolve_env(spec, env, "tenants." + name))
|
|
396
484
|
opened.append(tenants[name])
|
|
397
485
|
|
|
@@ -408,13 +496,15 @@ def build_gateway(cfg, env=None, log=stderr_log, wall=None, **overrides):
|
|
|
408
496
|
# For a tenant-bound client the variable holds the minting secret, not a token.
|
|
409
497
|
what = "minting secret" if clients[name].token_bound else "token"
|
|
410
498
|
if raw and not tokens[name]:
|
|
411
|
-
log("%s of client %s ignored: placeholder or shorter than %d characters"
|
|
499
|
+
log("%s of client %s ignored: placeholder or shorter than %d characters"
|
|
500
|
+
% (what, name, MIN_TOKEN_CHARS))
|
|
412
501
|
elif not raw:
|
|
413
502
|
log("client %s has no %s (%s is not set): it cannot authenticate" % (name, what, token_env))
|
|
414
503
|
if not clients:
|
|
415
504
|
raise ConfigError("no clients configured: add a [clients.<name>] table")
|
|
416
505
|
|
|
417
|
-
|
|
506
|
+
levels, _ = policies.load_audiences(stores, tenants, audiences) # a restored memory gets its store's level
|
|
507
|
+
forgetting, sweep_hours = _forgetting(cfg, stores, tenants, wall, levels)
|
|
418
508
|
if forgetting is not None:
|
|
419
509
|
opened.append(forgetting)
|
|
420
510
|
services = {"forgetting": forgetting}
|
|
@@ -425,8 +515,10 @@ def build_gateway(cfg, env=None, log=stderr_log, wall=None, **overrides):
|
|
|
425
515
|
write_module.DEFAULT_GUARDS, services)
|
|
426
516
|
opened.extend(stages + guards)
|
|
427
517
|
_check_enforced(clients, stages, guards)
|
|
518
|
+
identity = _identity(cfg, env, clients)
|
|
428
519
|
options = {
|
|
429
520
|
"tenants": tenants,
|
|
521
|
+
"audiences": audiences,
|
|
430
522
|
"stages": stages,
|
|
431
523
|
"guards": guards,
|
|
432
524
|
"redactors": {
|
|
@@ -435,6 +527,8 @@ def build_gateway(cfg, env=None, log=stderr_log, wall=None, **overrides):
|
|
|
435
527
|
},
|
|
436
528
|
"log": log,
|
|
437
529
|
}
|
|
530
|
+
if identity is not None:
|
|
531
|
+
options["identity"] = identity
|
|
438
532
|
if forgetting is not None:
|
|
439
533
|
options["forgetting"] = forgetting
|
|
440
534
|
options["sweep_every_hours"] = sweep_hours
|
|
@@ -5,6 +5,7 @@ Standard library only, in memory only: a restart clears every count.
|
|
|
5
5
|
import collections
|
|
6
6
|
import threading
|
|
7
7
|
import time
|
|
8
|
+
from typing import Any
|
|
8
9
|
|
|
9
10
|
RATE_LIMIT = 60
|
|
10
11
|
RATE_WINDOW = 60.0
|
|
@@ -127,7 +128,7 @@ class TenantBudget:
|
|
|
127
128
|
def __init__(self, total=3, per_tenant=2):
|
|
128
129
|
self.total = total
|
|
129
130
|
self.per_tenant = per_tenant
|
|
130
|
-
self._held = collections.Counter()
|
|
131
|
+
self._held: collections.Counter[Any] = collections.Counter()
|
|
131
132
|
self._lock = threading.Lock()
|
|
132
133
|
|
|
133
134
|
def acquire(self, tenant_key):
|
|
@@ -14,10 +14,13 @@ import queue
|
|
|
14
14
|
import socket
|
|
15
15
|
import threading
|
|
16
16
|
import time
|
|
17
|
+
from typing import Any
|
|
17
18
|
|
|
18
19
|
from ..errors import BackendError
|
|
19
20
|
|
|
20
21
|
POOL_SIZE = 8
|
|
22
|
+
NOTE_MAX = 8 # a call keeps at most this many distinct notes
|
|
23
|
+
NOTE_WORD = 32 # and each at most this many characters
|
|
21
24
|
|
|
22
25
|
|
|
23
26
|
def _kill(sock):
|
|
@@ -51,6 +54,13 @@ class NullCtl:
|
|
|
51
54
|
def on_cancel(self, fn):
|
|
52
55
|
pass # never cancelled, so fn is never called
|
|
53
56
|
|
|
57
|
+
def note(self, word):
|
|
58
|
+
pass # nobody collects the notes of a call outside the pool
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def notes(self):
|
|
62
|
+
return ()
|
|
63
|
+
|
|
54
64
|
|
|
55
65
|
NULL_CTL = NullCtl()
|
|
56
66
|
# The old private name: backends written before NULL_CTL existed import it and call it.
|
|
@@ -67,6 +77,7 @@ class Task:
|
|
|
67
77
|
self._cancelled = False
|
|
68
78
|
self._finished = False
|
|
69
79
|
self._hooks = []
|
|
80
|
+
self._notes = []
|
|
70
81
|
self.done = threading.Event()
|
|
71
82
|
self.result = None
|
|
72
83
|
self.error = None
|
|
@@ -102,6 +113,22 @@ class Task:
|
|
|
102
113
|
return
|
|
103
114
|
_call_quietly(fn)
|
|
104
115
|
|
|
116
|
+
def note(self, word):
|
|
117
|
+
"""A backend's word for the access log of the request (a reason, a few characters: never a query
|
|
118
|
+
or a memory text). Distinct words only, a few at most; thread-safe."""
|
|
119
|
+
if not isinstance(word, str) or not word:
|
|
120
|
+
return
|
|
121
|
+
word = word[:NOTE_WORD]
|
|
122
|
+
with self._lock:
|
|
123
|
+
if word not in self._notes and len(self._notes) < NOTE_MAX:
|
|
124
|
+
self._notes.append(word)
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def notes(self):
|
|
128
|
+
"""The words noted so far, in order."""
|
|
129
|
+
with self._lock:
|
|
130
|
+
return list(self._notes)
|
|
131
|
+
|
|
105
132
|
def cancel(self):
|
|
106
133
|
with self._lock:
|
|
107
134
|
self._cancelled = True
|
|
@@ -140,7 +167,7 @@ class Pool:
|
|
|
140
167
|
|
|
141
168
|
def __init__(self, size=POOL_SIZE):
|
|
142
169
|
self.size = size
|
|
143
|
-
self._queue = queue.SimpleQueue()
|
|
170
|
+
self._queue: queue.SimpleQueue[Any] = queue.SimpleQueue()
|
|
144
171
|
self._workers = []
|
|
145
172
|
self._busy = 0
|
|
146
173
|
self._closed = False
|
|
@@ -176,7 +203,7 @@ class Pool:
|
|
|
176
203
|
self._workers.append(worker)
|
|
177
204
|
try:
|
|
178
205
|
worker.start()
|
|
179
|
-
except Exception:
|
|
206
|
+
except Exception: # noqa: BLE001 - a failed thread start is rolled back and reported as no capacity
|
|
180
207
|
# Roll everything back so a failed start cannot leak capacity.
|
|
181
208
|
self._workers.remove(worker)
|
|
182
209
|
self._busy -= 1
|