@polycode-projects/the-mechanical-code-talker 6.0.0 → 6.0.2
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 +27 -0
- package/bin/tmct.mjs +61 -0
- package/package.json +9 -2
- package/src/adapters/corpus/courtesy.mjs +67 -3
- package/src/adapters/corpus/dbpedia-lookup-live.mjs +8 -0
- package/src/adapters/corpus/wikidata-live.mjs +8 -0
- package/src/adapters/corpus/wikipedia-live.mjs +18 -0
- package/src/adapters/corpus/wiktionary-live.mjs +8 -0
- package/src/adapters/memory/core.mjs +522 -146
- package/src/adapters/memory/corpus-bands.mjs +155 -0
- package/src/adapters/memory/dynamo-circuit-breaker.mjs +266 -0
- package/src/adapters/memory/systemic-failure.mjs +28 -0
- package/src/domain/ask.mjs +341 -75
- package/src/domain/cli-verbs.mjs +17 -0
- package/src/domain/news-feed.mjs +42 -4
- package/src/domain/retrieval-marker.mjs +120 -0
- package/src/domain/retrieval-modes.mjs +13 -0
- package/src/domain/source-breaker.mjs +259 -0
- package/src/services/chat-session.mjs +13 -2
- package/src/services/chat.mjs +314 -92
- package/src/services/corpus-loader.mjs +222 -0
- package/src/services/news-viz.mjs +213 -348
- package/src/services/news.mjs +41 -7
- package/src/services/p2p-room.mjs +35 -21
- package/src/services/subgraph-retrieval.mjs +4 -33
- package/src/surfaces/web/http-row-backend.mjs +150 -0
- package/src/surfaces/web/memory-ask-browser.bundle.js +143 -140
- package/src/surfaces/web/news-browser-entry.mjs +204 -464
package/src/services/news.mjs
CHANGED
|
@@ -59,6 +59,7 @@ import {
|
|
|
59
59
|
} from "../adapters/corpus/news-sources.mjs";
|
|
60
60
|
import { DEFAULT_MIN_INTERVAL_MS } from "../adapters/corpus/courtesy.mjs";
|
|
61
61
|
import { researchFacts } from "../adapters/corpus/research-source.mjs";
|
|
62
|
+
import { throughSourceBreaker, sourceSkipStatusLine } from "../domain/source-breaker.mjs";
|
|
62
63
|
import { ingestText, readsAsEntityTerm } from "./extract-facts.mjs";
|
|
63
64
|
|
|
64
65
|
export { NEWS_SOURCE_RECORDS, DEFAULT_NEWS_SOURCE_IDS, DEFAULT_NEWS_KB_IDS };
|
|
@@ -644,11 +645,37 @@ async function ingestResearchArticle(ctx, term, provider, article) {
|
|
|
644
645
|
return { facts: distinct.size, derived };
|
|
645
646
|
}
|
|
646
647
|
|
|
648
|
+
/** One KB lookup behind its source's circuit breaker. A source that has been
|
|
649
|
+
* timing out or throttling is skipped without a round trip, and the skip is
|
|
650
|
+
* reported so the cycle can tell "this source had nothing" from "this source
|
|
651
|
+
* was never asked". The negative cache catches the first; the breaker
|
|
652
|
+
* catches the second, and neither ever stands in for the other. */
|
|
653
|
+
async function lookupThroughBreaker(ctx, provider, sourceId, term, skipped) {
|
|
654
|
+
const source = String(provider?.name || sourceId);
|
|
655
|
+
const systemicFailuresOf = typeof provider?.stats === "function"
|
|
656
|
+
? () => provider.stats().systemicFailures ?? 0
|
|
657
|
+
: null;
|
|
658
|
+
let asked = false;
|
|
659
|
+
const article = await throughSourceBreaker(source, async () => {
|
|
660
|
+
asked = true;
|
|
661
|
+
try { provider.beginTurn?.(); } catch { /* an older provider has no budget */ }
|
|
662
|
+
try { return await provider.lookup(term); } catch { return null; }
|
|
663
|
+
}, {
|
|
664
|
+
registry: ctx?.sourceBreakers ?? undefined,
|
|
665
|
+
skipped,
|
|
666
|
+
label: provider?.label,
|
|
667
|
+
systemicFailuresOf,
|
|
668
|
+
});
|
|
669
|
+
return { article, asked };
|
|
670
|
+
}
|
|
671
|
+
|
|
647
672
|
/** Takes the top `limit` pending (negative-cache-expired) terms and walks
|
|
648
673
|
* the enabled KB sources in config order for each; first lookup hit wins.
|
|
649
674
|
* A grounded term is marked "grounded" and folded into one
|
|
650
675
|
* reprocessAfterGrounding pass over every term this cycle grounded; an
|
|
651
|
-
* all-null term enters the negative cache.
|
|
676
|
+
* all-null term enters the negative cache. A term whose sources were all
|
|
677
|
+
* skipped goes back to pending instead: nothing asked it, so nothing knows
|
|
678
|
+
* it is missing. */
|
|
652
679
|
export async function enrichTopTerms(ctx, { limit } = {}) {
|
|
653
680
|
const { memoryDir, store, state, providers, config, now } = ctx;
|
|
654
681
|
const shouldAbort = abortSignalOf(ctx);
|
|
@@ -662,6 +689,7 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
|
|
|
662
689
|
|
|
663
690
|
const enriched = [];
|
|
664
691
|
const missed = [];
|
|
692
|
+
const skippedSources = new Set();
|
|
665
693
|
let factsTotal = 0;
|
|
666
694
|
let derivedTotal = 0;
|
|
667
695
|
let aborted = false;
|
|
@@ -670,22 +698,25 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
|
|
|
670
698
|
if (shouldAbort()) { aborted = true; break; }
|
|
671
699
|
markTerm(ledger, entry.term, "enriching", nowVal);
|
|
672
700
|
let hit = null;
|
|
701
|
+
let askedAnySource = false;
|
|
673
702
|
for (const sourceId of config.kbSources) {
|
|
674
703
|
if (shouldAbort()) { aborted = true; break; }
|
|
675
704
|
const choice = KB_SOURCE_TO_RESEARCH_CHOICE[sourceId];
|
|
676
705
|
if (!choice || typeof providers?.getResearchProvider !== "function") continue;
|
|
677
706
|
const provider = providers.getResearchProvider({ source: choice });
|
|
678
707
|
if (!provider) continue;
|
|
679
|
-
|
|
680
|
-
|
|
708
|
+
const { article, asked } = await lookupThroughBreaker(ctx, provider, sourceId, entry.term, skippedSources);
|
|
709
|
+
if (asked) askedAnySource = true;
|
|
681
710
|
if (article) { hit = { provider, article }; break; }
|
|
682
711
|
}
|
|
683
712
|
// A stop mid-lookup is not a verdict on the term: it goes back to
|
|
684
713
|
// pending so the next cycle picks it up, never into the negative cache.
|
|
685
714
|
if (aborted) { markTerm(ledger, entry.term, "pending", nowVal); break; }
|
|
686
715
|
if (!hit) {
|
|
687
|
-
|
|
688
|
-
|
|
716
|
+
// No source was asked, so nothing learned this term is missing —
|
|
717
|
+
// the same posture a stop takes, for the same reason.
|
|
718
|
+
markTerm(ledger, entry.term, askedAnySource ? "missed" : "pending", nowVal);
|
|
719
|
+
if (askedAnySource) missed.push(entry.term);
|
|
689
720
|
continue;
|
|
690
721
|
}
|
|
691
722
|
const res = await ingestResearchArticle(ctx, entry.term, hit.provider, hit.article);
|
|
@@ -712,6 +743,7 @@ export async function enrichTopTerms(ctx, { limit } = {}) {
|
|
|
712
743
|
|
|
713
744
|
return {
|
|
714
745
|
enriched, missed, aborted,
|
|
746
|
+
skippedSources: [...skippedSources].sort(),
|
|
715
747
|
facts: factsTotal + reprocessResult.facts,
|
|
716
748
|
derived: derivedTotal + reprocessResult.derived,
|
|
717
749
|
};
|
|
@@ -838,11 +870,13 @@ function renderPollResult(result) {
|
|
|
838
870
|
function renderEnrichResult(result) {
|
|
839
871
|
const enrichedText = result.enriched.length ? ` (${result.enriched.join(", ")})` : "";
|
|
840
872
|
const missedText = result.missed.length ? ` (${result.missed.join(", ")})` : "";
|
|
873
|
+
const skipped = result.skippedSources || [];
|
|
841
874
|
const text = `enriched ${pluralize(result.enriched.length, "term")}${enrichedText}; `
|
|
842
875
|
+ `${pluralize(result.missed.length, "miss")}${missedText}; `
|
|
843
876
|
+ `${pluralize(result.facts, "fact")} stored, ${result.derived} derived.`
|
|
844
|
-
+ (result.aborted ? STOPPED_SUFFIX : "")
|
|
845
|
-
|
|
877
|
+
+ (result.aborted ? STOPPED_SUFFIX : "")
|
|
878
|
+
+ (skipped.length ? ` ${sourceSkipStatusLine(skipped)}` : "");
|
|
879
|
+
return { text, miss: !result.enriched.length && !result.missed.length && !result.aborted && !skipped.length };
|
|
846
880
|
}
|
|
847
881
|
|
|
848
882
|
async function handleAddSource(ctx, url) {
|
|
@@ -91,24 +91,27 @@ const ALREADY_PEER_LABELED = /^teach:peer:/;
|
|
|
91
91
|
* same tag again, so the union stops growing once every peer has seen it. */
|
|
92
92
|
/** `observedAtBySegment` maps a STORED (pre-relabel) tag to the observedAt its
|
|
93
93
|
* own record carries, when it has one — the dated-teach frame's own
|
|
94
|
-
* `mgx:observedAt`, threaded onto the wire fact each tag becomes.
|
|
95
|
-
* `
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
|
|
94
|
+
* `mgx:observedAt`, threaded onto the wire fact each tag becomes.
|
|
95
|
+
* `extractionBySegment` does the same for that record's own extraction
|
|
96
|
+
* findings, so a peer replicating the tag reads back the same findings the
|
|
97
|
+
* original assertion recorded. Returns `{ tag, observedAt, extraction }`
|
|
98
|
+
* triples, deduped by the RELABELED tag (the first value seen for a given
|
|
99
|
+
* output tag wins, matching the prior de-dup by tag string alone). */
|
|
100
|
+
function wireProvenanceTags(provenance, identity, fallbackTimestamp, observedAtBySegment, extractionBySegment) {
|
|
99
101
|
const stored = String(provenance || "").split(" | ").filter(Boolean);
|
|
100
|
-
if (!stored.length) return [{ tag: "", observedAt: undefined }];
|
|
102
|
+
if (!stored.length) return [{ tag: "", observedAt: undefined, extraction: undefined }];
|
|
101
103
|
const byTag = new Map();
|
|
102
104
|
for (const segment of stored) {
|
|
103
105
|
const observedAt = observedAtBySegment?.get(segment);
|
|
106
|
+
const extraction = extractionBySegment?.get(segment);
|
|
104
107
|
const tag = ALREADY_PEER_LABELED.test(segment) ? segment : (() => {
|
|
105
108
|
const assertedAt = latestProvenanceTimestamp(segment);
|
|
106
109
|
const timestamp = assertedAt === null ? fallbackTimestamp : new Date(assertedAt).toISOString();
|
|
107
110
|
return relabelForBroadcast(segment, identity.displayName, timestamp, identity.nodeId);
|
|
108
111
|
})();
|
|
109
|
-
if (!byTag.has(tag)) byTag.set(tag, observedAt);
|
|
112
|
+
if (!byTag.has(tag)) byTag.set(tag, { observedAt, extraction });
|
|
110
113
|
}
|
|
111
|
-
return [...byTag].map(([tag,
|
|
114
|
+
return [...byTag].map(([tag, meta]) => ({ tag, ...meta }));
|
|
112
115
|
}
|
|
113
116
|
|
|
114
117
|
/** This store's own node id, minted on first use and never regenerated: it
|
|
@@ -137,28 +140,34 @@ const isFactShaped = (f) => !!f
|
|
|
137
140
|
* every hop and never settle. Sending each tag on its own row keeps the merge
|
|
138
141
|
* idempotent, and a repeated triple inside one batch unions correctly.
|
|
139
142
|
*
|
|
140
|
-
* `mgx:observedAt`
|
|
141
|
-
* row.assertions is one live head, and its own
|
|
142
|
-
* tags) is the join key back to which outgoing
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
* way the local store
|
|
146
|
-
* effectiveObservedAt chain)
|
|
143
|
+
* `mgx:observedAt` and `mgx:extractionFinding` are both record content the
|
|
144
|
+
* same way the tag is: each of row.assertions is one live head, and its own
|
|
145
|
+
* `provenance` (that head's own tags) is the join key back to which outgoing
|
|
146
|
+
* wire fact carries its observedAt and its extraction findings. A dated
|
|
147
|
+
* taught fact's broadcast carries the date, so a peer that receives it can
|
|
148
|
+
* resolve it against a fresher OR staler claim the same way the local store
|
|
149
|
+
* already does (memory/resolution.mjs's effectiveObservedAt chain), and a
|
|
150
|
+
* finding-bearing assertion's broadcast carries its findings, so a peer
|
|
151
|
+
* renders the same caveat the origin did rather than reading a clean
|
|
152
|
+
* reading that never happened. Sent per assertion, never unioned at the wire
|
|
153
|
+
* layer — the row's own union is a read-time fold over exactly these
|
|
154
|
+
* per-assertion values, so unioning again here would double up on merge. */
|
|
147
155
|
const toWireFacts = (row, identity, fallbackTimestamp) => {
|
|
148
156
|
const observedAtBySegment = new Map();
|
|
157
|
+
const extractionBySegment = new Map();
|
|
149
158
|
for (const a of row.assertions || []) {
|
|
150
|
-
|
|
151
|
-
for (const segment of
|
|
152
|
-
|
|
153
|
-
}
|
|
159
|
+
const segments = String(a.provenance || "").split(" | ").filter(Boolean);
|
|
160
|
+
if (a.observedAt) for (const segment of segments) observedAtBySegment.set(segment, a.observedAt);
|
|
161
|
+
if (a.extraction?.length) for (const segment of segments) extractionBySegment.set(segment, a.extraction);
|
|
154
162
|
}
|
|
155
|
-
return wireProvenanceTags(row.provenance, identity, fallbackTimestamp, observedAtBySegment)
|
|
156
|
-
.map(({ tag, observedAt }) => ({
|
|
163
|
+
return wireProvenanceTags(row.provenance, identity, fallbackTimestamp, observedAtBySegment, extractionBySegment)
|
|
164
|
+
.map(({ tag, observedAt, extraction }) => ({
|
|
157
165
|
subject: row.subject,
|
|
158
166
|
predicate: row.predicate,
|
|
159
167
|
object: row.object,
|
|
160
168
|
provenance: tag,
|
|
161
169
|
...(observedAt ? { observedAt } : {}),
|
|
170
|
+
...(extraction?.length ? { extraction } : {}),
|
|
162
171
|
}));
|
|
163
172
|
};
|
|
164
173
|
|
|
@@ -462,6 +471,11 @@ export function createP2pRoom({
|
|
|
462
471
|
// this is the passthrough that lets a dated taught fact's wire fact
|
|
463
472
|
// reach it at all.
|
|
464
473
|
...(typeof f.observedAt === "string" && f.observedAt ? { observedAt: f.observedAt } : {}),
|
|
474
|
+
// Same passthrough for the extraction findings the origin recorded on
|
|
475
|
+
// this same assertion — appendFacts dedupes and sorts them the same way
|
|
476
|
+
// a local write does, so a merged record reads back exactly as its
|
|
477
|
+
// origin stored it.
|
|
478
|
+
...(Array.isArray(f.extraction) && f.extraction.length ? { extraction: f.extraction } : {}),
|
|
465
479
|
}))) : { ids: [] };
|
|
466
480
|
await sortFactIndividualsById();
|
|
467
481
|
await refreshRows();
|
|
@@ -16,7 +16,10 @@ import {
|
|
|
16
16
|
buildRetrievalPlan, expandedTerms, ancestryTerms,
|
|
17
17
|
} from "../domain/retrieval-plan.mjs";
|
|
18
18
|
import { loadLexicon } from "../domain/grammar/lexicon.mjs";
|
|
19
|
-
import {
|
|
19
|
+
import { isSystemicFailure } from "../adapters/memory/systemic-failure.mjs";
|
|
20
|
+
import { SUPPLEMENTED_MODE, SEED_SESSION_MODE } from "../domain/retrieval-modes.mjs";
|
|
21
|
+
|
|
22
|
+
export { isSystemicFailure, SUPPLEMENTED_MODE, SEED_SESSION_MODE };
|
|
20
23
|
|
|
21
24
|
/** The retrieval budgets, set from what scripts/corpus-bands/calibrate-retrieval.mjs
|
|
22
25
|
* measured over the committed WordNet and ConceptNet corpora. Changing one is
|
|
@@ -64,38 +67,6 @@ export const RETRIEVAL_BUDGETS = Object.freeze({
|
|
|
64
67
|
backoffBaseMs: 25,
|
|
65
68
|
});
|
|
66
69
|
|
|
67
|
-
/** Retrieval ran and the answer stands on the corpus supplement as well as the
|
|
68
|
-
* seed and the session. */
|
|
69
|
-
export const SUPPLEMENTED_MODE = "supplemented";
|
|
70
|
-
|
|
71
|
-
/** No corpus read happened, because no bands are configured or the breaker is
|
|
72
|
-
* open. The
|
|
73
|
-
* answer stands on the bundled seed and the session alone. */
|
|
74
|
-
export const SEED_SESSION_MODE = "seed-session";
|
|
75
|
-
|
|
76
|
-
const THROTTLE_ERROR_NAMES = new Set([
|
|
77
|
-
"ProvisionedThroughputExceededException",
|
|
78
|
-
"RequestLimitExceeded",
|
|
79
|
-
"ThrottlingException",
|
|
80
|
-
"TooManyRequestsException",
|
|
81
|
-
"InternalServerError",
|
|
82
|
-
"ServiceUnavailable",
|
|
83
|
-
"TimeoutError",
|
|
84
|
-
"AbortError",
|
|
85
|
-
]);
|
|
86
|
-
|
|
87
|
-
/** Does this failure mean the store itself is in trouble? Only these count
|
|
88
|
-
* toward a breaker: throttles, 5xx and timeouts. An empty result is an answer,
|
|
89
|
-
* and a rejected input is a bug in the caller, so neither is systemic. */
|
|
90
|
-
export function isSystemicFailure(error) {
|
|
91
|
-
if (!error) return false;
|
|
92
|
-
if (error.code === BACKEND_UNAVAILABLE_CODE) return true;
|
|
93
|
-
if (error.retryable === true || error.$retryable?.throttling === true) return true;
|
|
94
|
-
if (THROTTLE_ERROR_NAMES.has(error.name)) return true;
|
|
95
|
-
const status = error.status ?? error.$metadata?.httpStatusCode;
|
|
96
|
-
return status === 429 || (typeof status === "number" && status >= 500);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
70
|
/** Is fuzzy variant expansion on for this turn? Most specific setting wins:
|
|
100
71
|
* the request, then the environment, then the config file, then the default,
|
|
101
72
|
* which is on. */
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// http-row-backend.mjs — the §3.1 row-backend contract over the row
|
|
2
|
+
// service's HTTP surface (server/row-service/handler.mjs's endpoint table).
|
|
3
|
+
// This is the client half of the seam the DynamoDB backend fills on the
|
|
4
|
+
// storage side. A page or a Node caller constructs one per session and gets
|
|
5
|
+
// the same contract every other backend gives. Only the network can fail.
|
|
6
|
+
//
|
|
7
|
+
// The module is fetch-only and imports nothing node-specific, so it runs
|
|
8
|
+
// unmodified in a browser bundle and in a node test. `fetchImpl` lets a test
|
|
9
|
+
// or an older runtime hand in its own implementation.
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
ROW_BACKEND_KIND, ROW_BACKEND_CONTRACT_VERSION,
|
|
13
|
+
BackendRejected, BackendUnavailable,
|
|
14
|
+
} from "../../adapters/memory/row-backend.mjs";
|
|
15
|
+
|
|
16
|
+
const SESSION_HEADER = "x-tmct-session";
|
|
17
|
+
|
|
18
|
+
function trimTrailingSlash(value) {
|
|
19
|
+
return value.endsWith("/") ? value.slice(0, -1) : value;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Reads whatever text the response carries, for the error's own message
|
|
23
|
+
* only. The class decision uses the status code alone (the service's own
|
|
24
|
+
* §3.8 mapping), so a consumer never has to parse a body to know whether a
|
|
25
|
+
* failure is worth retrying. */
|
|
26
|
+
async function responseFailureMessage(response, fallback) {
|
|
27
|
+
try {
|
|
28
|
+
const text = await response.text();
|
|
29
|
+
if (!text) return fallback;
|
|
30
|
+
const parsed = JSON.parse(text);
|
|
31
|
+
return parsed?.error?.message || fallback;
|
|
32
|
+
} catch {
|
|
33
|
+
return fallback;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function throwForStatus(response, fallbackMessage) {
|
|
38
|
+
const status = response.status;
|
|
39
|
+
const message = await responseFailureMessage(response, fallbackMessage);
|
|
40
|
+
if (status === 400 || status === 413) throw new BackendRejected(message, { status });
|
|
41
|
+
// 429 (mutation rate), 507 (table cap), and any 5xx (503 is the handler's
|
|
42
|
+
// own mapping for a backend-level BackendUnavailable; 500 is an
|
|
43
|
+
// unexpected handler fault) all mean the store refused or failed to
|
|
44
|
+
// serve. They share one retryable bucket, decided by status, never by
|
|
45
|
+
// matching on message text.
|
|
46
|
+
throw new BackendUnavailable(message, { status });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function runFetch(fetchImpl, url, init, networkFailureMessage) {
|
|
50
|
+
try {
|
|
51
|
+
return await fetchImpl(url, init);
|
|
52
|
+
} catch (error) {
|
|
53
|
+
throw new BackendUnavailable(networkFailureMessage, { cause: error });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** One retry, on a 5xx only, for the one call the spec singles out.
|
|
58
|
+
* `deleteAll`'s purge is query-then-mark and idempotent, so a retried
|
|
59
|
+
* DELETE just re-marks whatever the first attempt already reached; it
|
|
60
|
+
* never double-applies. Every other mutation gets one attempt only:
|
|
61
|
+
* retrying a PUT or a keyed DELETE past a 5xx is a caller decision, not
|
|
62
|
+
* this backend's. */
|
|
63
|
+
async function fetchWithOneRetryOn5xx(fetchImpl, url, init, networkFailureMessage) {
|
|
64
|
+
const first = await runFetch(fetchImpl, url, init, networkFailureMessage);
|
|
65
|
+
if (first.status < 500) return first;
|
|
66
|
+
return runFetch(fetchImpl, url, init, networkFailureMessage);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** `createHttpRowBackend({ apiBase, sessionKey, fetchImpl })`: a §3.1 row
|
|
70
|
+
* backend over the row service at `apiBase` (same-origin, no trailing
|
|
71
|
+
* slash needed), scoped to `sessionKey` (a v4 UUID the caller minted).
|
|
72
|
+
* `fetchImpl` defaults to the ambient `fetch`, so a page never has to pass
|
|
73
|
+
* one. A test points it at a running `local.mjs` double instead. */
|
|
74
|
+
export function createHttpRowBackend({ apiBase, sessionKey, fetchImpl = fetch } = {}) {
|
|
75
|
+
if (typeof apiBase !== "string" || !apiBase) throw new TypeError("createHttpRowBackend needs an apiBase URL");
|
|
76
|
+
if (typeof sessionKey !== "string" || !sessionKey) throw new TypeError("createHttpRowBackend needs a sessionKey");
|
|
77
|
+
if (typeof fetchImpl !== "function") throw new TypeError("createHttpRowBackend needs a fetchImpl(url, init) function, or an ambient fetch");
|
|
78
|
+
|
|
79
|
+
const base = trimTrailingSlash(apiBase);
|
|
80
|
+
let closed = false;
|
|
81
|
+
|
|
82
|
+
const assertOpen = () => {
|
|
83
|
+
if (closed) throw new BackendUnavailable("this row backend was closed and can no longer be used");
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const jsonHeaders = { "content-type": "application/json" };
|
|
87
|
+
const sessionReadHeaders = { [SESSION_HEADER]: sessionKey };
|
|
88
|
+
|
|
89
|
+
async function getJson(path, { headers = {} } = {}) {
|
|
90
|
+
const response = await runFetch(fetchImpl, `${base}${path}`, { headers }, "could not reach the row service");
|
|
91
|
+
if (response.status === 404) return { notFound: true };
|
|
92
|
+
if (!response.ok) await throwForStatus(response, `GET ${path} failed`);
|
|
93
|
+
return { value: await response.json() };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function mutate(path, { method, body }, { retryOn5xx = false } = {}) {
|
|
97
|
+
const init = { method, headers: jsonHeaders, body: JSON.stringify(body) };
|
|
98
|
+
const response = retryOn5xx
|
|
99
|
+
? await fetchWithOneRetryOn5xx(fetchImpl, `${base}${path}`, init, "could not reach the row service")
|
|
100
|
+
: await runFetch(fetchImpl, `${base}${path}`, init, "could not reach the row service");
|
|
101
|
+
if (!response.ok) await throwForStatus(response, `${method} ${path} failed`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
kind: ROW_BACKEND_KIND,
|
|
106
|
+
contractVersion: ROW_BACKEND_CONTRACT_VERSION,
|
|
107
|
+
|
|
108
|
+
async readRows() {
|
|
109
|
+
assertOpen();
|
|
110
|
+
const result = await getJson("/api/rows", { headers: sessionReadHeaders });
|
|
111
|
+
return result.notFound ? [] : (result.value.rows || []);
|
|
112
|
+
},
|
|
113
|
+
|
|
114
|
+
async readRowsByTerm(term) {
|
|
115
|
+
assertOpen();
|
|
116
|
+
const result = await getJson(`/api/rows?term=${encodeURIComponent(term)}`, { headers: sessionReadHeaders });
|
|
117
|
+
return result.notFound ? [] : (result.value.rows || []);
|
|
118
|
+
},
|
|
119
|
+
|
|
120
|
+
async putRows(rows) {
|
|
121
|
+
assertOpen();
|
|
122
|
+
await mutate(`/api/sessions/${sessionKey}/rows`, { method: "PUT", body: { puts: rows } });
|
|
123
|
+
},
|
|
124
|
+
|
|
125
|
+
async deleteRows(rowKeys) {
|
|
126
|
+
assertOpen();
|
|
127
|
+
await mutate(`/api/sessions/${sessionKey}/rows`, { method: "DELETE", body: { rowKeys } });
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
async deleteAll() {
|
|
131
|
+
assertOpen();
|
|
132
|
+
await mutate(`/api/sessions/${sessionKey}/rows`, { method: "DELETE", body: { all: true } }, { retryOn5xx: true });
|
|
133
|
+
},
|
|
134
|
+
|
|
135
|
+
async readMeta(key) {
|
|
136
|
+
assertOpen();
|
|
137
|
+
const result = await getJson(`/api/meta/${encodeURIComponent(key)}`, { headers: sessionReadHeaders });
|
|
138
|
+
return result.notFound ? null : result.value.value;
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
async putMeta(key, value) {
|
|
142
|
+
assertOpen();
|
|
143
|
+
await mutate(`/api/sessions/${sessionKey}/meta/${encodeURIComponent(key)}`, { method: "PUT", body: { value } });
|
|
144
|
+
},
|
|
145
|
+
|
|
146
|
+
async close() {
|
|
147
|
+
closed = true;
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
}
|