@uuaid/pillar 2.6.1 → 2.7.1
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/README.md +325 -7
- package/bin/carrier.mjs +21 -0
- package/bin/pillar-ask.mjs +4 -1
- package/bin/pillar-blob.mjs +6 -0
- package/bin/pillar-directory.mjs +282 -16
- package/bin/pillar-escrow.mjs +4 -1
- package/bin/pillar-group-v2.mjs +6 -0
- package/bin/pillar-notify.mjs +13 -0
- package/bin/pillar-responder.mjs +266 -23
- package/bin/pillar.mjs +512 -257
- package/package.json +17 -25
- package/src/cli-help.mjs +23 -0
- package/src/group-v2-cli.mjs +1 -1
- package/src/identity/trust.mjs +72 -6
- package/src/mailbox/mailbox.mjs +313 -12
- package/src/net/carrier-server.mjs +34 -2
- package/src/net/refusals.mjs +2 -0
- package/src/net/seed-registry.mjs +2 -1
- package/src/net/transport.mjs +320 -91
- package/src/node-check.mjs +29 -8
- package/src/notify-events.mjs +148 -0
- package/src/notify-log.mjs +124 -0
- package/src/notify-runner.mjs +372 -0
- package/src/notify-store.mjs +736 -0
- package/src/notify.mjs +350 -0
- package/src/pillar.mjs +382 -27
- package/src/readers.mjs +2 -2
- package/src/registry/federation.mjs +3056 -0
- package/src/registry/gossip.mjs +294 -0
- package/src/registry/heartbeats.mjs +205 -0
- package/src/registry/lineage-verifier.mjs +972 -0
- package/src/registry/lineage.mjs +984 -0
- package/src/registry/listings.mjs +612 -0
- package/src/registry/resolve.mjs +376 -0
- package/src/registry/stats.mjs +508 -0
- package/src/sqlite-loader.mjs +40 -0
- package/src/vendor/pillar-core.mjs +22 -0
- package/src/vendor/uuaid-soul.mjs +2246 -0
- package/src/vnext/a6b-common.mjs +270 -0
- package/src/vnext/b1-cli.mjs +970 -0
- package/src/vnext/card-cli.mjs +370 -0
- package/src/vnext/greeter-operator.mjs +160 -0
- package/src/vnext/greeter-suggest.mjs +318 -0
- package/src/vnext/greeter.mjs +571 -0
- package/src/vnext/homes.mjs +48 -0
- package/src/vnext/init-cli.mjs +489 -0
- package/src/vnext/intro-cli.mjs +81 -0
- package/src/vnext/json-dir-mailbox.mjs +304 -0
- package/src/vnext/jsonl-mailbox.mjs +1132 -0
- package/src/vnext/knock-answer.mjs +162 -0
- package/src/vnext/knock-cli.mjs +520 -0
- package/src/vnext/knock-lane.mjs +312 -0
- package/src/vnext/knock-responder.mjs +344 -0
- package/src/vnext/lineage-cli.mjs +653 -0
- package/src/vnext/listing-cli.mjs +323 -0
- package/src/vnext/resolve-cli.mjs +104 -0
- package/src/vnext/soul-cli.mjs +666 -0
- package/src/vnext/verify-cli.mjs +333 -0
- package/src/vnext/w4-redirect.mjs +178 -0
- package/src/vnext/wave-a.mjs +193 -0
- package/src/vnext/witness-cli.mjs +547 -0
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pillar vNext Plan Row B7 — Greeter suggestions by a published deterministic rule.
|
|
3
|
+
*
|
|
4
|
+
* Rule (published in docs/vnext/AMENDMENT-B7-knock-answer-suggestions.md, `pillar-greeter-suggest/1`):
|
|
5
|
+
* - Overlap = number of distinct knocker-card `wants[]` `tag`/`action` values equal to a
|
|
6
|
+
* listing card's `does[]` `tag`/`action` values.
|
|
7
|
+
* - Candidates = registry listings with status `live` at `now`, minus the knocker, the greeter,
|
|
8
|
+
* every card tagged `greeter`, and zero-overlap listings.
|
|
9
|
+
* - Order = overlap descending, then `sha256(knockerUuaid + "\n" + listingUuaid)` ascending.
|
|
10
|
+
* - Return at most 3. Fewer than 3 candidates returns fewer. Never pad.
|
|
11
|
+
* - No randomness. No clock except the `now` input.
|
|
12
|
+
*
|
|
13
|
+
* `selectGreeterSuggestions` is the one pure function. `fetchSuggestionListings` and
|
|
14
|
+
* `makeGreeterSuggester` are the runtime adapter that reads the greeter's registry; a suggestion
|
|
15
|
+
* is only a UUAID, and the knocker resolves and verifies it like any stranger.
|
|
16
|
+
*
|
|
17
|
+
* Fix round 2 (RedTeam 3e56eb): the adapter is optional and must never hold an accept or reach
|
|
18
|
+
* past the registry. Every network call goes through `makeRegistryReadFetch` (read-only GETs of
|
|
19
|
+
* `/directory.json`, `/v1/resolve/*`, `/v1/lineage/*` on the configured registry origin, redirects
|
|
20
|
+
* off, `SUGGESTION_REQUEST_TIMEOUT_MS` each). One scan has `SUGGESTION_SCAN_BUDGET_MS`; at the
|
|
21
|
+
* deadline it is aborted, its pending slot is cleared, and its late result is discarded. A knock
|
|
22
|
+
* waits at most `SUGGESTION_WAIT_MS` (KnockResponder `suggestBudgetMs`), so a slow scan can only
|
|
23
|
+
* omit suggestions; it can never delay the accept past that wait.
|
|
24
|
+
*
|
|
25
|
+
* Fix round 3 (V1 F1): a scan that times out or fails writes a negative cache entry. For
|
|
26
|
+
* `SUGGESTION_CACHE_TTL_MS` of knock `now` after it, knocks get no suggestions and neither scan nor
|
|
27
|
+
* wait, so a registry too large for the scan budget costs at most one scan per TTL window.
|
|
28
|
+
*/
|
|
29
|
+
import { createHash } from "node:crypto";
|
|
30
|
+
import { LINEAGE_SKEW_MS, resolve as coreResolve } from "../vendor/pillar-core.mjs";
|
|
31
|
+
import { computeListingStatus } from "../registry/listings.mjs";
|
|
32
|
+
import { isPlainObject, isStrictDateTime } from "../registry/lineage.mjs";
|
|
33
|
+
import { hasGreeterTag } from "./greeter.mjs";
|
|
34
|
+
import { isValidUuaid } from "./knock-lane.mjs";
|
|
35
|
+
|
|
36
|
+
export const GREETER_SUGGEST_RULE = "pillar-greeter-suggest/1";
|
|
37
|
+
export const MAX_GREETER_SUGGESTIONS = 3;
|
|
38
|
+
export const MAX_SUGGESTION_SCAN = 256;
|
|
39
|
+
const RESOLVE_CONCURRENCY = 8;
|
|
40
|
+
/** The longest one accept waits for suggestions (wall clock). Past it, the accept goes out without them. */
|
|
41
|
+
export const SUGGESTION_WAIT_MS = 2_000;
|
|
42
|
+
/** Wall-clock limit for one directory scan. At the deadline the scan is aborted and cleared, and a negative cache entry is written. */
|
|
43
|
+
export const SUGGESTION_SCAN_BUDGET_MS = 30_000;
|
|
44
|
+
/** Wall-clock limit for each registry request (headers and body). */
|
|
45
|
+
export const SUGGESTION_REQUEST_TIMEOUT_MS = 5_000;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Distinct `tag`/`action` values of a card capability list. A tag value equals only a tag value
|
|
49
|
+
* and an action value equals only an action value (the two formats are disjoint in `pillar-card/1`).
|
|
50
|
+
*/
|
|
51
|
+
export function capabilityValues(list) {
|
|
52
|
+
const out = new Set();
|
|
53
|
+
if (!Array.isArray(list)) return out;
|
|
54
|
+
for (const item of list) {
|
|
55
|
+
if (!isPlainObject(item)) continue;
|
|
56
|
+
if (typeof item.tag === "string") out.add(`tag:${item.tag}`);
|
|
57
|
+
if (typeof item.action === "string") out.add(`action:${item.action}`);
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Overlap between a knocker card's `wants[]` and a listing card's `does[]`. */
|
|
63
|
+
export function suggestionOverlap(knockerCard, listingCard) {
|
|
64
|
+
const wants = capabilityValues(knockerCard?.wants);
|
|
65
|
+
const does = capabilityValues(listingCard?.does);
|
|
66
|
+
let n = 0;
|
|
67
|
+
for (const v of wants) if (does.has(v)) n++;
|
|
68
|
+
return n;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Tie-break key: lowercase hex `sha256(knockerUuaid + "\n" + listingUuaid)`. */
|
|
72
|
+
export function suggestionTieKey(knockerUuaid, listingUuaid) {
|
|
73
|
+
return createHash("sha256").update(`${knockerUuaid}\n${listingUuaid}`, "utf8").digest("hex");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function compareCandidates(a, b) {
|
|
77
|
+
if (a.overlap !== b.overlap) return b.overlap - a.overlap;
|
|
78
|
+
if (a.key < b.key) return -1;
|
|
79
|
+
if (a.key > b.key) return 1;
|
|
80
|
+
return 0;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The B7 rule. Pure and deterministic: the output depends only on the arguments.
|
|
85
|
+
*
|
|
86
|
+
* @param {object} input
|
|
87
|
+
* @param {string} input.knocker knocker UUAID (the knock envelope sender)
|
|
88
|
+
* @param {object} input.knockerCard knocker `pillar-card/1` (its `wants[]` and `lineage` are read)
|
|
89
|
+
* @param {string} input.greeter greeter UUAID (the greeter's own lineage is also excluded)
|
|
90
|
+
* @param {string} input.now strict ISO date-time; the only clock
|
|
91
|
+
* @param {Array<{uuaid: string, lineage?: string, status?: string, lastSeen: string,
|
|
92
|
+
* withdrawn?: boolean, tombstoned?: boolean, card: object}>} input.listings
|
|
93
|
+
* @returns {string[]} 0..3 distinct listing UUAIDs
|
|
94
|
+
*/
|
|
95
|
+
export function selectGreeterSuggestions({ knocker, knockerCard, greeter, now, listings } = {}) {
|
|
96
|
+
if (!isValidUuaid(knocker)) throw new TypeError("selectGreeterSuggestions: knocker must be a UUAID"); // @rule suggest.knocker-uuaid
|
|
97
|
+
if (!isValidUuaid(greeter)) throw new TypeError("selectGreeterSuggestions: greeter must be a UUAID"); // @rule suggest.greeter-uuaid
|
|
98
|
+
if (!isStrictDateTime(now)) throw new TypeError("selectGreeterSuggestions: now must be a strict date-time"); // @rule suggest.now
|
|
99
|
+
if (!Array.isArray(listings)) throw new TypeError("selectGreeterSuggestions: listings must be an array"); // @rule suggest.listings-array
|
|
100
|
+
|
|
101
|
+
const nowMs = Date.parse(now);
|
|
102
|
+
const knockerIds = new Set([knocker]);
|
|
103
|
+
if (isValidUuaid(knockerCard?.lineage)) knockerIds.add(knockerCard.lineage);
|
|
104
|
+
const ranked = [];
|
|
105
|
+
for (const e of listings) {
|
|
106
|
+
if (!isPlainObject(e) || !isValidUuaid(e.uuaid) || !isPlainObject(e.card)) continue; // @rule suggest.entry-shape
|
|
107
|
+
if (e.status !== undefined && e.status !== "live") continue; // @rule suggest.reported-live
|
|
108
|
+
if (!isStrictDateTime(e.lastSeen) || Date.parse(e.lastSeen) > nowMs + LINEAGE_SKEW_MS) continue; // @rule suggest.last-seen-valid
|
|
109
|
+
if (computeListingStatus(e.lastSeen, { withdrawn: e.withdrawn === true, tombstoned: e.tombstoned === true, now }) !== "live") continue; // @rule suggest.computed-live
|
|
110
|
+
const ids = [e.uuaid, e.lineage, e.card.lineage, e.card.uuaid].filter((x) => typeof x === "string");
|
|
111
|
+
if (ids.some((x) => knockerIds.has(x))) continue; // @rule suggest.exclude-knocker
|
|
112
|
+
if (ids.includes(greeter)) continue; // @rule suggest.exclude-greeter
|
|
113
|
+
if (hasGreeterTag(e.card)) continue; // @rule suggest.exclude-greeter-tag
|
|
114
|
+
const overlap = suggestionOverlap(knockerCard, e.card);
|
|
115
|
+
if (overlap === 0) continue; // @rule suggest.exclude-zero-overlap
|
|
116
|
+
ranked.push({ uuaid: e.uuaid, lineage: typeof e.lineage === "string" ? e.lineage : e.card.lineage, overlap, key: suggestionTieKey(knocker, e.uuaid) });
|
|
117
|
+
}
|
|
118
|
+
ranked.sort(compareCandidates); // @rule suggest.order
|
|
119
|
+
|
|
120
|
+
const out = [];
|
|
121
|
+
const seen = new Set();
|
|
122
|
+
for (const c of ranked) {
|
|
123
|
+
if (out.length === MAX_GREETER_SUGGESTIONS) break; // @rule suggest.max-three
|
|
124
|
+
if (seen.has(c.uuaid) || (typeof c.lineage === "string" && seen.has(c.lineage))) continue; // @rule suggest.dedupe
|
|
125
|
+
seen.add(c.uuaid);
|
|
126
|
+
if (typeof c.lineage === "string") seen.add(c.lineage);
|
|
127
|
+
out.push(c.uuaid);
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Thrown when the B7 lookup tries a request that is not a permitted registry read. */
|
|
133
|
+
export class RegistryReadRefusedError extends Error {
|
|
134
|
+
constructor(reason, url) {
|
|
135
|
+
super(`B7 registry read refused (${reason}): ${url}`);
|
|
136
|
+
this.name = "RegistryReadRefusedError";
|
|
137
|
+
this.code = "registry-read-refused";
|
|
138
|
+
this.reason = reason;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Thrown at once (no scan, no wait) while a negative cache entry is fresh: the scan started at
|
|
144
|
+
* `failedAtMs` (knock `now`) timed out or failed, and no new scan starts before `retryAtMs`.
|
|
145
|
+
*/
|
|
146
|
+
export class SuggestionScanUnavailableError extends Error {
|
|
147
|
+
constructor(failedAtMs, retryAtMs) {
|
|
148
|
+
super(`B7 suggestions unavailable: the scan started at ${new Date(failedAtMs).toISOString()} failed; next scan from ${new Date(retryAtMs).toISOString()}`);
|
|
149
|
+
this.name = "SuggestionScanUnavailableError";
|
|
150
|
+
this.code = "suggestion-scan-unavailable";
|
|
151
|
+
this.failedAtMs = failedAtMs;
|
|
152
|
+
this.retryAtMs = retryAtMs;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Thrown when one directory scan passes `SUGGESTION_SCAN_BUDGET_MS`. */
|
|
157
|
+
export class SuggestionScanTimeoutError extends Error {
|
|
158
|
+
constructor(budgetMs) {
|
|
159
|
+
super(`B7 suggestion scan passed its ${budgetMs} ms budget`);
|
|
160
|
+
this.name = "SuggestionScanTimeoutError";
|
|
161
|
+
this.code = "suggestion-scan-timeout";
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* The only fetch the B7 lookup uses. It forwards a request only when it is a GET of
|
|
167
|
+
* `/directory.json`, `/v1/resolve/<id>`, or `/v1/lineage/<id>` under the configured registry URL,
|
|
168
|
+
* on the same origin, with no credentials, query, or fragment. It sends no body, refuses redirects,
|
|
169
|
+
* and aborts at `requestTimeoutMs` or when `signal` aborts. Anything else throws
|
|
170
|
+
* `RegistryReadRefusedError` before the underlying fetch runs. The core `resolve()` treats that
|
|
171
|
+
* throw like an unreachable lineage home, so observer sync for presented homes makes no request.
|
|
172
|
+
* Normal client lineage sync does not use this wrapper and is unchanged.
|
|
173
|
+
*/
|
|
174
|
+
export function makeRegistryReadFetch({ registryUrl, fetchImpl = globalThis.fetch, signal = undefined, requestTimeoutMs = SUGGESTION_REQUEST_TIMEOUT_MS } = {}) {
|
|
175
|
+
const base = new URL(String(registryUrl ?? "").replace(/\/+$/, ""));
|
|
176
|
+
const prefix = base.pathname.replace(/\/+$/, "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
177
|
+
const readPath = new RegExp(`^${prefix}/(?:directory\\.json|v1/(?:resolve|lineage)/[^/]+)$`);
|
|
178
|
+
return async (input, init = undefined) => {
|
|
179
|
+
const url = new URL(typeof input === "string" ? input : String(input?.href ?? ""));
|
|
180
|
+
const method = String(init?.method ?? "GET").toUpperCase();
|
|
181
|
+
if (method !== "GET") throw new RegistryReadRefusedError("method", url.href); // @rule suggest.read-get-only
|
|
182
|
+
if (url.origin !== base.origin || url.username || url.password || url.search || url.hash) throw new RegistryReadRefusedError("origin", url.href); // @rule suggest.read-same-origin
|
|
183
|
+
if (!readPath.test(url.pathname)) throw new RegistryReadRefusedError("path", url.href); // @rule suggest.read-path
|
|
184
|
+
const signals = [];
|
|
185
|
+
signals.push(AbortSignal.timeout(requestTimeoutMs)); // @rule suggest.read-request-timeout
|
|
186
|
+
if (signal) signals.push(signal); // @rule suggest.read-scan-signal
|
|
187
|
+
if (init?.signal) signals.push(init.signal);
|
|
188
|
+
const out = { method: "GET", headers: { accept: "application/json" } };
|
|
189
|
+
out.redirect = "error"; // @rule suggest.read-no-redirect
|
|
190
|
+
if (signals.length > 0) out.signal = signals.length === 1 ? signals[0] : AbortSignal.any(signals);
|
|
191
|
+
return fetchImpl(url.href, out);
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Runtime adapter: read the greeter's registry and return `selectGreeterSuggestions` entries.
|
|
197
|
+
* Candidate UUAIDs come from `/directory.json` `agents[]` (the registry's live projection). Each one
|
|
198
|
+
* is re-resolved and verified with the core `resolve()`; anything that fails resolution is dropped.
|
|
199
|
+
* Every request, including the ones inside `resolve()`, goes through `makeRegistryReadFetch`.
|
|
200
|
+
*/
|
|
201
|
+
export async function fetchSuggestionListings({
|
|
202
|
+
registryUrl,
|
|
203
|
+
now,
|
|
204
|
+
fetchImpl = globalThis.fetch,
|
|
205
|
+
resolveImpl = coreResolve,
|
|
206
|
+
maxAgents = MAX_SUGGESTION_SCAN,
|
|
207
|
+
signal = undefined,
|
|
208
|
+
requestTimeoutMs = SUGGESTION_REQUEST_TIMEOUT_MS,
|
|
209
|
+
} = {}) {
|
|
210
|
+
const base = String(registryUrl ?? "").replace(/\/+$/, "");
|
|
211
|
+
const readFetch = makeRegistryReadFetch({ registryUrl: base, fetchImpl, signal, requestTimeoutMs });
|
|
212
|
+
const res = await readFetch(`${base}/directory.json`, { method: "GET", headers: { accept: "application/json" } });
|
|
213
|
+
if (!res.ok) throw new Error(`fetchSuggestionListings: GET /directory.json failed (${res.status})`); // @rule suggest.adapter-directory-ok
|
|
214
|
+
const dir = await res.json();
|
|
215
|
+
const agents = Array.isArray(dir?.agents) ? dir.agents : [];
|
|
216
|
+
let ids = [...new Set(agents.map((a) => a?.uuaid).filter((u) => isValidUuaid(u)))].sort();
|
|
217
|
+
ids = ids.slice(0, maxAgents); // @rule suggest.adapter-scan-cap
|
|
218
|
+
|
|
219
|
+
const entries = [];
|
|
220
|
+
for (let i = 0; i < ids.length; i += RESOLVE_CONCURRENCY) {
|
|
221
|
+
signal?.throwIfAborted();
|
|
222
|
+
const chunk = ids.slice(i, i + RESOLVE_CONCURRENCY);
|
|
223
|
+
const results = await Promise.all(chunk.map(async (u) => {
|
|
224
|
+
try { return await resolveImpl(u, { registryUrl: base, now, fetch: readFetch }); } catch { return null; }
|
|
225
|
+
}));
|
|
226
|
+
for (const r of results) {
|
|
227
|
+
if (!r?.ok || !isPlainObject(r.card) || r.card.uuaid !== r.current) continue; // @rule suggest.adapter-resolve-verified
|
|
228
|
+
entries.push({
|
|
229
|
+
uuaid: r.current,
|
|
230
|
+
lineage: r.lineage,
|
|
231
|
+
status: r.status,
|
|
232
|
+
lastSeen: r.answer?.lastSeen,
|
|
233
|
+
withdrawn: r.answer?.evidence?.listing?.withdrawn === true,
|
|
234
|
+
card: r.card,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return entries;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** How long one directory scan stays fresh, measured with each knock's `now` input (not a clock). */
|
|
242
|
+
export const SUGGESTION_CACHE_TTL_MS = 60_000;
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Build the greeter's `suggest({ knocker, knockerCard, now })` hook for `KnockResponder`.
|
|
246
|
+
*
|
|
247
|
+
* Each hook binds one `registryUrl` and keeps one cache entry for its last scan:
|
|
248
|
+
* - good: `{ atMs, listings, failed: false }` when the scan finished inside its budget;
|
|
249
|
+
* - negative: `{ atMs, listings: null, failed: true }` when the scan timed out or failed for any
|
|
250
|
+
* reason (registry 5xx, request timeout, abort, refused read, bad JSON).
|
|
251
|
+
* `atMs` is the `now` of the knock that started the scan. An entry is fresh for a knock whose `now`
|
|
252
|
+
* is 0 s to under `SUGGESTION_CACHE_TTL_MS` after `atMs`; a `now` earlier than `atMs` or at/after the
|
|
253
|
+
* TTL ignores it. A fresh good entry is reused. A fresh negative entry makes the hook reject at once
|
|
254
|
+
* with `SuggestionScanUnavailableError`: no scan, no wait, no suggestions. A knock with no fresh
|
|
255
|
+
* entry starts a scan, or joins the one in flight (single flight), and only those knocks wait.
|
|
256
|
+
* `selectGreeterSuggestions` still filters `live` at each knock's own `now`.
|
|
257
|
+
*
|
|
258
|
+
* Each scan has `scanBudgetMs` of wall-clock time and each request `requestTimeoutMs`. At the scan
|
|
259
|
+
* deadline the scan's requests are aborted, every knock still waiting gets
|
|
260
|
+
* `SuggestionScanTimeoutError` (the responder then answers without suggestions), the negative entry
|
|
261
|
+
* is written, and the in-flight slot is cleared. A result that arrives after the deadline is
|
|
262
|
+
* discarded, so it can never replace the negative entry or a newer scan's entry. The knock-side wait
|
|
263
|
+
* (`SUGGESTION_WAIT_MS`) is enforced by `KnockResponder`: a knock that stops waiting leaves the scan
|
|
264
|
+
* running to its own deadline, so later knocks can use its result.
|
|
265
|
+
*/
|
|
266
|
+
export function makeGreeterSuggester({
|
|
267
|
+
registryUrl,
|
|
268
|
+
greeter,
|
|
269
|
+
fetchImpl = globalThis.fetch,
|
|
270
|
+
resolveImpl = coreResolve,
|
|
271
|
+
maxAgents = MAX_SUGGESTION_SCAN,
|
|
272
|
+
scanBudgetMs = SUGGESTION_SCAN_BUDGET_MS,
|
|
273
|
+
requestTimeoutMs = SUGGESTION_REQUEST_TIMEOUT_MS,
|
|
274
|
+
} = {}) {
|
|
275
|
+
if (typeof registryUrl !== "string" || registryUrl.length === 0) throw new TypeError("makeGreeterSuggester: registryUrl is required"); // @rule suggest.adapter-registry-required
|
|
276
|
+
let cache = null; // { atMs, listings, failed } from the last scan: good, or negative (listings: null)
|
|
277
|
+
let inflight = null; // the one scan in progress, shared by concurrent knocks
|
|
278
|
+
const refresh = (now, nowMs) => {
|
|
279
|
+
if (inflight !== null) return inflight.promise; // @rule suggest.cache-single-flight
|
|
280
|
+
const scan = { promise: null };
|
|
281
|
+
const ac = new AbortController();
|
|
282
|
+
let timer = null;
|
|
283
|
+
const deadline = new Promise((_, reject) => {
|
|
284
|
+
timer = setTimeout(() => {
|
|
285
|
+
const err = new SuggestionScanTimeoutError(scanBudgetMs);
|
|
286
|
+
ac.abort(err); // @rule suggest.scan-abort
|
|
287
|
+
reject(err);
|
|
288
|
+
}, scanBudgetMs);
|
|
289
|
+
});
|
|
290
|
+
deadline.catch(() => {}); // waiting knocks see the rejection through the race below
|
|
291
|
+
let work = fetchSuggestionListings({ registryUrl, now, fetchImpl, resolveImpl, maxAgents, signal: ac.signal, requestTimeoutMs }).then((listings) => {
|
|
292
|
+
if (ac.signal.aborted) throw ac.signal.reason; // @rule suggest.scan-late-discard
|
|
293
|
+
cache = { atMs: nowMs, listings, failed: false }; // @rule suggest.cache-store
|
|
294
|
+
return listings;
|
|
295
|
+
});
|
|
296
|
+
work = Promise.race([work, deadline]); // @rule suggest.scan-deadline
|
|
297
|
+
scan.promise = work.catch((err) => {
|
|
298
|
+
cache = { atMs: nowMs, listings: null, failed: true }; // @rule suggest.cache-store-failed
|
|
299
|
+
throw err;
|
|
300
|
+
}).finally(() => {
|
|
301
|
+
clearTimeout(timer);
|
|
302
|
+
if (inflight === scan) inflight = null; // @rule suggest.cache-inflight-clear
|
|
303
|
+
});
|
|
304
|
+
inflight = scan;
|
|
305
|
+
return scan.promise;
|
|
306
|
+
};
|
|
307
|
+
return async ({ knocker, knockerCard, now }) => {
|
|
308
|
+
if (!isStrictDateTime(now)) throw new TypeError("makeGreeterSuggester: now must be a strict date-time"); // @rule suggest.cache-now
|
|
309
|
+
const nowMs = Date.parse(now);
|
|
310
|
+
let entry = null;
|
|
311
|
+
if (cache !== null) entry = cache; // @rule suggest.cache-reuse
|
|
312
|
+
if (entry !== null && nowMs < entry.atMs) entry = null; // @rule suggest.cache-not-before
|
|
313
|
+
if (entry !== null && nowMs - entry.atMs >= SUGGESTION_CACHE_TTL_MS) entry = null; // @rule suggest.cache-ttl
|
|
314
|
+
if (entry !== null && entry.failed) throw new SuggestionScanUnavailableError(entry.atMs, entry.atMs + SUGGESTION_CACHE_TTL_MS); // @rule suggest.cache-failed-skip
|
|
315
|
+
const listings = entry !== null ? entry.listings : await refresh(now, nowMs);
|
|
316
|
+
return selectGreeterSuggestions({ knocker, knockerCard, greeter, now, listings });
|
|
317
|
+
};
|
|
318
|
+
}
|