@nordhavnhq/beacon 0.4.0 → 0.5.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/LICENSE +21 -0
- package/README.md +3 -329
- package/dist/cache-q8uLEGYg.d.cts +165 -0
- package/dist/cache-q8uLEGYg.d.ts +165 -0
- package/dist/file-store.cjs +148 -0
- package/dist/file-store.cjs.map +1 -0
- package/dist/file-store.d.cts +47 -0
- package/dist/file-store.d.ts +47 -0
- package/dist/file-store.js +146 -0
- package/dist/file-store.js.map +1 -0
- package/dist/index.cjs +621 -107
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +240 -130
- package/dist/index.d.ts +240 -130
- package/dist/index.js +621 -107
- package/dist/index.js.map +1 -1
- package/package.json +42 -19
package/dist/index.js
CHANGED
|
@@ -2,6 +2,7 @@ import { chartTypeInfo, CHART_TYPES, PALETTE_KEYS, CHART_AXES } from './chunk-UN
|
|
|
2
2
|
export { AGGREGATIONS, BUCKET_MODES, CHART_AXES, CHART_SORTS, CHART_TYPES, CHART_TYPE_INFO, DATE_BUCKET_VALUES, PALETTE_KEYS, chartTypeInfo, isBarChart, isPartChart } from './chunk-UNIWH5QN.js';
|
|
3
3
|
|
|
4
4
|
// src/cache.ts
|
|
5
|
+
var EXPIRED = 1;
|
|
5
6
|
var MemoryCacheStore = class {
|
|
6
7
|
constructor(maxEntries = 500) {
|
|
7
8
|
this.maxEntries = maxEntries;
|
|
@@ -33,23 +34,31 @@ var ContentCache = class {
|
|
|
33
34
|
constructor(opts = {}) {
|
|
34
35
|
this.enabled = opts.enabled ?? true;
|
|
35
36
|
this.ttl = opts.ttl ?? 6048e5;
|
|
37
|
+
this.retryDelay = typeof opts.revalidate === "number" && opts.revalidate > 0 ? opts.revalidate : 6e4;
|
|
36
38
|
this.store = opts.store ?? new MemoryCacheStore(opts.maxEntries ?? 500);
|
|
37
39
|
}
|
|
38
40
|
/**
|
|
39
41
|
* The live entry for `key`, or `undefined` on miss / TTL expiry. Returns the
|
|
40
42
|
* whole entry (value + etag + validated stamp) so the client can decide
|
|
41
43
|
* whether to serve it, revalidate it, or fall back to it on error.
|
|
44
|
+
*
|
|
45
|
+
* An expired entry is left in the store (the refetch overwrites it, or
|
|
46
|
+
* `maxEntries` evicts it) so `stale` can still fall back to it.
|
|
42
47
|
*/
|
|
43
48
|
peek(key, now) {
|
|
44
|
-
|
|
45
|
-
const entry = this.store.get(key);
|
|
49
|
+
const entry = this.stale(key);
|
|
46
50
|
if (!entry) return void 0;
|
|
47
|
-
if (entry.expiresAt !== 0 && entry.expiresAt <= now)
|
|
48
|
-
this.store.delete(key);
|
|
49
|
-
return void 0;
|
|
50
|
-
}
|
|
51
|
+
if (entry.expiresAt !== 0 && entry.expiresAt <= now) return void 0;
|
|
51
52
|
return entry;
|
|
52
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* The entry for `key` whether or not its TTL has run out: the last good value
|
|
56
|
+
* to serve when a refetch fails transiently.
|
|
57
|
+
*/
|
|
58
|
+
stale(key) {
|
|
59
|
+
if (!this.enabled) return void 0;
|
|
60
|
+
return this.store.get(key);
|
|
61
|
+
}
|
|
53
62
|
/** Store a freshly fetched value with its validator and the stamp it is current against. */
|
|
54
63
|
set(key, value, opts, now) {
|
|
55
64
|
if (!this.enabled) return;
|
|
@@ -69,8 +78,43 @@ var ContentCache = class {
|
|
|
69
78
|
if (!entry) return;
|
|
70
79
|
entry.validatedVersion = version;
|
|
71
80
|
entry.expiresAt = this.ttl === 0 ? 0 : now + this.ttl;
|
|
81
|
+
delete entry.retryAt;
|
|
82
|
+
this.store.set(key, entry);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Record that refetching `key` from `from` just failed transiently, so reads
|
|
86
|
+
* serve it as-is for a while instead of each waiting on an unreachable studio.
|
|
87
|
+
* Returns the entry to serve: `from`, or the newer one a concurrent read stored
|
|
88
|
+
* in the meantime (left unpaused, since its own fetch succeeded).
|
|
89
|
+
*/
|
|
90
|
+
backoff(key, from, now) {
|
|
91
|
+
const entry = this.store.get(key);
|
|
92
|
+
if (!entry) return from;
|
|
93
|
+
if (entry.etag !== from.etag || entry.expiresAt !== from.expiresAt) return entry;
|
|
94
|
+
entry.retryAt = now + this.retryDelay;
|
|
95
|
+
this.store.set(key, entry);
|
|
96
|
+
return entry;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Mark `key` as due for a refetch while keeping its value to fall back on:
|
|
100
|
+
* the next read asks the studio again whatever the stamp says, and still
|
|
101
|
+
* serves this value if the studio does not answer. For when the stored value
|
|
102
|
+
* may be outdated but there is no telling - dropping it would throw away the
|
|
103
|
+
* only thing left to show during an outage. No-op for a key that is not held.
|
|
104
|
+
*/
|
|
105
|
+
expire(key) {
|
|
106
|
+
const entry = this.store.get(key);
|
|
107
|
+
if (!entry) return;
|
|
108
|
+
entry.expiresAt = EXPIRED;
|
|
109
|
+
delete entry.retryAt;
|
|
72
110
|
this.store.set(key, entry);
|
|
73
111
|
}
|
|
112
|
+
/** `expire` for every key that starts with `prefix`. */
|
|
113
|
+
expirePrefix(prefix) {
|
|
114
|
+
for (const key of [...this.store.keys()]) {
|
|
115
|
+
if (key.startsWith(prefix)) this.expire(key);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
74
118
|
/** Drop one exact key. */
|
|
75
119
|
delete(key) {
|
|
76
120
|
this.store.delete(key);
|
|
@@ -107,15 +151,22 @@ var HavenError = class _HavenError extends Error {
|
|
|
107
151
|
};
|
|
108
152
|
|
|
109
153
|
// src/version.ts
|
|
154
|
+
var UNSUPPORTED_PAUSE_MS = 15 * 6e4;
|
|
110
155
|
var VersionTracker = class {
|
|
111
|
-
constructor(probe, interval) {
|
|
156
|
+
constructor(probe, interval, isUnsupported = (err) => err?.status === 404) {
|
|
112
157
|
this.probe = probe;
|
|
113
158
|
this.interval = interval;
|
|
159
|
+
this.isUnsupported = isUnsupported;
|
|
114
160
|
this.lastChecked = 0;
|
|
115
161
|
this.version = null;
|
|
116
162
|
this.inFlight = null;
|
|
117
|
-
/**
|
|
118
|
-
|
|
163
|
+
/**
|
|
164
|
+
* Epoch ms before which we do not ask again, after the server turned out
|
|
165
|
+
* to have no version route. A pause and not a final verdict: an old server
|
|
166
|
+
* costs one request per pause, and one that gains the route is picked up
|
|
167
|
+
* without a restart.
|
|
168
|
+
*/
|
|
169
|
+
this.pausedUntil = 0;
|
|
119
170
|
}
|
|
120
171
|
/** The most recent stamp seen, or `null` before the first successful probe. */
|
|
121
172
|
current() {
|
|
@@ -125,24 +176,31 @@ var VersionTracker = class {
|
|
|
125
176
|
* Refresh the stamp if we are due. Resolves once the answer is in, so the
|
|
126
177
|
* read that triggered it sees an up-to-date stamp. A failed probe leaves the
|
|
127
178
|
* last known stamp in place (serve-from-cache rather than thrash).
|
|
179
|
+
*
|
|
180
|
+
* A failed probe counts towards the interval like any other, also when no
|
|
181
|
+
* stamp has ever come in. Otherwise a process that starts while the studio
|
|
182
|
+
* is down (with a persisted cache to serve from) would probe on every read,
|
|
183
|
+
* and against a hanging studio make each of them wait out the probe.
|
|
128
184
|
*/
|
|
129
185
|
async refresh(now) {
|
|
130
|
-
if (this.interval <= 0 || this.
|
|
186
|
+
if (this.interval <= 0 || now < this.pausedUntil) return;
|
|
131
187
|
if (this.inFlight) return this.inFlight;
|
|
132
|
-
if (
|
|
188
|
+
if (now - this.lastChecked < this.interval) return;
|
|
133
189
|
this.lastChecked = now;
|
|
134
|
-
this.inFlight = this.run();
|
|
190
|
+
this.inFlight = this.run(now);
|
|
135
191
|
try {
|
|
136
192
|
await this.inFlight;
|
|
137
193
|
} finally {
|
|
138
194
|
this.inFlight = null;
|
|
139
195
|
}
|
|
140
196
|
}
|
|
141
|
-
async run() {
|
|
197
|
+
async run(now) {
|
|
142
198
|
try {
|
|
143
199
|
this.version = await this.probe();
|
|
144
200
|
} catch (err) {
|
|
145
|
-
if (err
|
|
201
|
+
if (this.isUnsupported(err)) {
|
|
202
|
+
this.pausedUntil = now + Math.max(this.interval, UNSUPPORTED_PAUSE_MS);
|
|
203
|
+
}
|
|
146
204
|
}
|
|
147
205
|
}
|
|
148
206
|
};
|
|
@@ -150,26 +208,87 @@ var VersionTracker = class {
|
|
|
150
208
|
// src/client.ts
|
|
151
209
|
var PREVIEW_PARAM = "sl-preview";
|
|
152
210
|
var DEFAULT_BASE_URL = "https://beacon.nordhavn.ai";
|
|
153
|
-
var
|
|
211
|
+
var DEFAULT_TIMEOUT = 1e4;
|
|
212
|
+
var VERSION_TIMEOUT = 3e3;
|
|
213
|
+
var DEFAULT_WAIT_FOR_FRESH = 1e3;
|
|
214
|
+
var MAX_TIMER = 2147483647;
|
|
215
|
+
var STORED_LIMIT = 5e3;
|
|
216
|
+
var LOCALES_RETRY_MS = 6e4;
|
|
217
|
+
var DEFAULT_GATEWAY_RETRY = 200;
|
|
218
|
+
var MAX_GATEWAY_RETRY = 6e4;
|
|
219
|
+
var HavenClient = class {
|
|
154
220
|
constructor(options) {
|
|
221
|
+
/**
|
|
222
|
+
* The refresh under way per cache key, so concurrent reads of one key share
|
|
223
|
+
* one request, with the ticket it left on (see `state.ticket`).
|
|
224
|
+
*/
|
|
225
|
+
this.inflight = /* @__PURE__ */ new Map();
|
|
226
|
+
/**
|
|
227
|
+
* Per cache key, the ticket of the request whose answer the cache holds.
|
|
228
|
+
* Emptied on every invalidation, capped by `STORED_LIMIT`. See `storable`.
|
|
229
|
+
*/
|
|
230
|
+
this.storedBy = /* @__PURE__ */ new Map();
|
|
231
|
+
/**
|
|
232
|
+
* Everything that changes while the client runs and is not a collection of
|
|
233
|
+
* its own. One object, so that a preview view - which shares this client's
|
|
234
|
+
* fields through its prototype - changes the same values and never a copy.
|
|
235
|
+
*/
|
|
236
|
+
this.state = {
|
|
237
|
+
/**
|
|
238
|
+
* Numbers the requests in the order they leave. Answers come back in any
|
|
239
|
+
* order, and the cache must never go back in time: a request takes a
|
|
240
|
+
* ticket when it leaves, and `storable` compares it on the way back.
|
|
241
|
+
*/
|
|
242
|
+
ticket: 0,
|
|
243
|
+
/** The last ticket handed out when the cache was last invalidated. */
|
|
244
|
+
invalidatedAt: 0,
|
|
245
|
+
/** Set by an absorbed failure, cleared by the next answer: one warning per outage. */
|
|
246
|
+
unreachable: false,
|
|
247
|
+
/**
|
|
248
|
+
* The project's locales as last read. Kept here and not only in the cache,
|
|
249
|
+
* where the entry can be evicted: without the list a requested locale
|
|
250
|
+
* cannot be mapped onto the key its content is cached under, and that
|
|
251
|
+
* content would be out of reach for as long as the studio is away.
|
|
252
|
+
*/
|
|
253
|
+
locales: void 0,
|
|
254
|
+
/** Epoch ms before which the locales are not asked for again, after that failed. */
|
|
255
|
+
localesRetryAt: 0
|
|
256
|
+
};
|
|
155
257
|
if (!options.apiKey) throw new Error("HavenClient: `apiKey` is required");
|
|
156
258
|
this.apiKey = options.apiKey;
|
|
157
259
|
this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
158
260
|
const resolvedFetch = options.fetch ?? globalThis.fetch;
|
|
159
261
|
if (!resolvedFetch) {
|
|
160
|
-
throw new Error("HavenClient: no `fetch` available; pass one via options.fetch
|
|
262
|
+
throw new Error("HavenClient: no `fetch` available; pass one via options.fetch");
|
|
161
263
|
}
|
|
162
264
|
this.fetchImpl = resolvedFetch.bind(globalThis);
|
|
163
265
|
this.headers = options.headers ?? {};
|
|
164
266
|
this.locale = options.locale || void 0;
|
|
165
267
|
this.readDefault = options.preview !== true;
|
|
268
|
+
this.timeout = normalizeTimeout(options.timeout);
|
|
269
|
+
this.onError = options.onError;
|
|
166
270
|
const cacheOpt = options.cache;
|
|
167
271
|
const cacheOptions = cacheOpt === false ? { enabled: false } : cacheOpt === true || cacheOpt === void 0 ? {} : cacheOpt;
|
|
168
272
|
this.cache = new ContentCache(cacheOptions);
|
|
273
|
+
this.waitForFresh = normalizeWait(cacheOptions.waitForFresh);
|
|
274
|
+
this.gatewayRetry = normalizeGatewayRetry(options.gatewayRetry);
|
|
169
275
|
const revalidate = cacheOptions.enabled === false || cacheOptions.revalidate === false ? 0 : cacheOptions.revalidate ?? 6e4;
|
|
276
|
+
const probeTimeout = this.timeout === 0 ? VERSION_TIMEOUT : Math.min(this.timeout, VERSION_TIMEOUT);
|
|
170
277
|
this.versionTracker = new VersionTracker(
|
|
171
|
-
async () =>
|
|
172
|
-
|
|
278
|
+
async () => {
|
|
279
|
+
try {
|
|
280
|
+
const res = await this.request("GET", "/version", void 0, probeTimeout);
|
|
281
|
+
if (typeof res?.version !== "string") throw unexpectedBody(`${this.baseUrl}/api/content/version`);
|
|
282
|
+
this.state.unreachable = false;
|
|
283
|
+
return res.version;
|
|
284
|
+
} catch (err) {
|
|
285
|
+
if (isMissingRoute(err)) this.state.unreachable = false;
|
|
286
|
+
else this.report({ during: "stamp-check", error: err });
|
|
287
|
+
throw err;
|
|
288
|
+
}
|
|
289
|
+
},
|
|
290
|
+
revalidate,
|
|
291
|
+
isMissingRoute
|
|
173
292
|
);
|
|
174
293
|
}
|
|
175
294
|
// ── Preview scoping ─────────────────────────────────────────────────────────
|
|
@@ -197,17 +316,9 @@ var HavenClient = class _HavenClient {
|
|
|
197
316
|
forRequest(input) {
|
|
198
317
|
if (!this.readDefault) return this;
|
|
199
318
|
if (!isPreviewRequest(input)) return this;
|
|
200
|
-
const
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
fetch: this.fetchImpl,
|
|
204
|
-
headers: this.headers,
|
|
205
|
-
locale: this.locale,
|
|
206
|
-
preview: true
|
|
207
|
-
});
|
|
208
|
-
clone.cache = this.cache;
|
|
209
|
-
clone.versionTracker = this.versionTracker;
|
|
210
|
-
return clone;
|
|
319
|
+
const view = Object.create(this);
|
|
320
|
+
view.readDefault = false;
|
|
321
|
+
return view;
|
|
211
322
|
}
|
|
212
323
|
/** Whether this client bypasses the cache (i.e. came from a preview request). */
|
|
213
324
|
get isPreview() {
|
|
@@ -216,7 +327,7 @@ var HavenClient = class _HavenClient {
|
|
|
216
327
|
// ── Introspection ─────────────────────────────────────────────────────────
|
|
217
328
|
/** The full content shape this key can reach: nodes, datasets, field schemas. */
|
|
218
329
|
async schema(opts) {
|
|
219
|
-
return this.cachedGet("schema", "/schema", opts);
|
|
330
|
+
return this.cachedGet("schema", "/schema", opts, has("nodes", Array.isArray));
|
|
220
331
|
}
|
|
221
332
|
/** Shorthand for `schema()` then `.nodes`. */
|
|
222
333
|
async nodes(opts) {
|
|
@@ -227,43 +338,111 @@ var HavenClient = class _HavenClient {
|
|
|
227
338
|
* a locale `code` as the client `locale` option or a per-call `opts.locale`.
|
|
228
339
|
*/
|
|
229
340
|
async locales(opts) {
|
|
230
|
-
const res = await this.cachedGet("locales", "/locales", opts);
|
|
341
|
+
const res = await this.cachedGet("locales", "/locales", opts, has("locales", Array.isArray));
|
|
231
342
|
return res.locales;
|
|
232
343
|
}
|
|
233
|
-
/**
|
|
344
|
+
/**
|
|
345
|
+
* Resolve the locale for a read: per-call override, else the client default.
|
|
346
|
+
* Only a value overrides: `{ locale: undefined }` (or `null`) is what a site
|
|
347
|
+
* passes when the visitor sent no language, and must leave the client locale standing.
|
|
348
|
+
* `''` is the one way to ask for the project default.
|
|
349
|
+
*/
|
|
234
350
|
resolveLocale(opts) {
|
|
235
|
-
const l = opts
|
|
351
|
+
const l = opts?.locale != null ? opts.locale : this.locale;
|
|
236
352
|
return l || void 0;
|
|
237
353
|
}
|
|
354
|
+
/**
|
|
355
|
+
* The locale a read is requested and cached under: the requested one mapped
|
|
356
|
+
* onto a locale the project is configured with (see `matchLocale`).
|
|
357
|
+
*
|
|
358
|
+
* Sites pass on whatever language the visitor's browser asks for, and the
|
|
359
|
+
* studio answers all of `nl`, `nl-NL` and `nl-BE` with the same content. Keyed
|
|
360
|
+
* by the raw value, each spelling would be its own cache entry and its own
|
|
361
|
+
* request - and a stream of made-up ones would push every real entry out of
|
|
362
|
+
* the cache, the last good values for an outage among them. Mapped first,
|
|
363
|
+
* the cache holds one entry per configured locale, whatever is asked for.
|
|
364
|
+
*
|
|
365
|
+
* Without the list of locales (caching off, an older studio without the
|
|
366
|
+
* route, studio unreachable and never read) the requested value goes to the
|
|
367
|
+
* studio as it is, and the studio resolves it.
|
|
368
|
+
*/
|
|
369
|
+
async readLocale(opts) {
|
|
370
|
+
const requested = this.resolveLocale(opts)?.trim() || void 0;
|
|
371
|
+
if (requested === void 0 || !this.cache.enabled) return requested;
|
|
372
|
+
const bypass = !(opts?.cache ?? this.readDefault);
|
|
373
|
+
const configured = await this.configuredLocales(!bypass);
|
|
374
|
+
return configured ? matchLocale(requested, configured) : requested;
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* The project's locales, or `undefined` when they have never been read and
|
|
378
|
+
* cannot be now. An empty list is an answer like any other: the project has
|
|
379
|
+
* no locales, the studio serves the same content whatever language is asked
|
|
380
|
+
* for, and `matchLocale` then maps every request onto the default.
|
|
381
|
+
*
|
|
382
|
+
* Once the list is known this does not wait for anything: the read maps from
|
|
383
|
+
* the list as it stands, and the list is brought up to date on the side. A
|
|
384
|
+
* read therefore spends its `waitForFresh` on its content alone, and keeps
|
|
385
|
+
* finding that content under the same key while the studio is away. Only
|
|
386
|
+
* the very first localized read waits here, as it has nothing to map from.
|
|
387
|
+
*
|
|
388
|
+
* The exception is `waitForFresh: false`. That setting promises that a read
|
|
389
|
+
* waits for the studio and leaves nothing running when it returns - what a
|
|
390
|
+
* host needs that freezes the process once the response is out. So there
|
|
391
|
+
* the list is brought up to date first, like the content after it.
|
|
392
|
+
*/
|
|
393
|
+
async configuredLocales(retry) {
|
|
394
|
+
const state = this.state;
|
|
395
|
+
if (Date.now() >= state.localesRetryAt) {
|
|
396
|
+
const lookup = this.cachedGet(
|
|
397
|
+
"locales",
|
|
398
|
+
"/locales",
|
|
399
|
+
{ cache: true },
|
|
400
|
+
has("locales", Array.isArray),
|
|
401
|
+
retry
|
|
402
|
+
).then(
|
|
403
|
+
(res) => {
|
|
404
|
+
state.locales = res.locales;
|
|
405
|
+
},
|
|
406
|
+
() => {
|
|
407
|
+
state.localesRetryAt = Date.now() + LOCALES_RETRY_MS;
|
|
408
|
+
}
|
|
409
|
+
);
|
|
410
|
+
if (state.locales === void 0 || this.waitForFresh === Infinity) await lookup;
|
|
411
|
+
}
|
|
412
|
+
return state.locales;
|
|
413
|
+
}
|
|
238
414
|
// ── Records ───────────────────────────────────────────────────────────────
|
|
239
415
|
/** List every record in a dataset (references inflated). Requires read scope. */
|
|
240
416
|
async listRecords(nodeSlug, datasetSlug, opts) {
|
|
241
|
-
const locale = this.
|
|
417
|
+
const locale = await this.readLocale(opts);
|
|
242
418
|
const res = await this.cachedGet(
|
|
243
419
|
recordsKey(nodeSlug, datasetSlug, locale),
|
|
244
420
|
datasetPath(nodeSlug, datasetSlug) + localeQuery(locale),
|
|
245
|
-
opts
|
|
421
|
+
opts,
|
|
422
|
+
has("records", Array.isArray)
|
|
246
423
|
);
|
|
247
424
|
return res.records;
|
|
248
425
|
}
|
|
249
426
|
/** Read one record by uid. Requires read scope. Throws 404 if it does not exist. */
|
|
250
427
|
async getRecord(nodeSlug, datasetSlug, recordUid, opts) {
|
|
251
|
-
const locale = this.
|
|
428
|
+
const locale = await this.readLocale(opts);
|
|
252
429
|
const res = await this.cachedGet(
|
|
253
430
|
recordKey(nodeSlug, datasetSlug, recordUid, locale),
|
|
254
431
|
`${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}${localeQuery(locale)}`,
|
|
255
|
-
opts
|
|
432
|
+
opts,
|
|
433
|
+
has("record", isObject)
|
|
256
434
|
);
|
|
257
435
|
return res.record;
|
|
258
436
|
}
|
|
259
437
|
/** Create a record. Requires write scope. Invalidates cached reads of the dataset. */
|
|
260
438
|
async createRecord(nodeSlug, datasetSlug, data) {
|
|
261
|
-
const res = await this.
|
|
439
|
+
const res = await this.write(
|
|
262
440
|
"POST",
|
|
263
441
|
datasetPath(nodeSlug, datasetSlug),
|
|
264
|
-
{ data }
|
|
442
|
+
{ data },
|
|
443
|
+
nodeSlug,
|
|
444
|
+
datasetSlug
|
|
265
445
|
);
|
|
266
|
-
this.invalidateDataset(nodeSlug, datasetSlug);
|
|
267
446
|
return res.record;
|
|
268
447
|
}
|
|
269
448
|
/**
|
|
@@ -272,22 +451,45 @@ var HavenClient = class _HavenClient {
|
|
|
272
451
|
* reads of the dataset and of this record.
|
|
273
452
|
*/
|
|
274
453
|
async updateRecord(nodeSlug, datasetSlug, recordUid, data) {
|
|
275
|
-
const res = await this.
|
|
454
|
+
const res = await this.write(
|
|
276
455
|
"PATCH",
|
|
277
456
|
`${datasetPath(nodeSlug, datasetSlug)}/${encodeURIComponent(recordUid)}`,
|
|
278
|
-
{ data }
|
|
457
|
+
{ data },
|
|
458
|
+
nodeSlug,
|
|
459
|
+
datasetSlug
|
|
279
460
|
);
|
|
280
|
-
this.invalidateDataset(nodeSlug, datasetSlug);
|
|
281
|
-
this.cache.delete(recordKey(nodeSlug, datasetSlug, recordUid));
|
|
282
461
|
return res.record;
|
|
283
462
|
}
|
|
463
|
+
/**
|
|
464
|
+
* Sends a write and settles the cached reads of its dataset with the outcome.
|
|
465
|
+
*
|
|
466
|
+
* Stored: they are dropped. Refused (an answered 4xx): they are still right
|
|
467
|
+
* and stay. Anything else - a timeout, a dropped connection, a 5xx - leaves
|
|
468
|
+
* open whether the studio carried the write out, so they are marked for a
|
|
469
|
+
* recheck: the next read asks the studio again, and keeps the cached value to
|
|
470
|
+
* fall back on if the studio is in fact down.
|
|
471
|
+
*/
|
|
472
|
+
async write(method, path, body, nodeSlug, datasetSlug) {
|
|
473
|
+
let res;
|
|
474
|
+
try {
|
|
475
|
+
res = await this.request(method, path, body);
|
|
476
|
+
} catch (err) {
|
|
477
|
+
if (writeMayHaveLanded(err)) this.invalidateDataset(nodeSlug, datasetSlug, "recheck");
|
|
478
|
+
throw err;
|
|
479
|
+
}
|
|
480
|
+
this.invalidateDataset(nodeSlug, datasetSlug);
|
|
481
|
+
return res;
|
|
482
|
+
}
|
|
284
483
|
// -- Queries --
|
|
285
484
|
/** Run a saved query (`queries.<slug>`) and return its result. Requires read scope. */
|
|
286
485
|
async query(querySlug, opts) {
|
|
287
486
|
return this.cachedGet(
|
|
288
487
|
`query:${querySlug}`,
|
|
289
488
|
`/queries/${encodeURIComponent(querySlug)}`,
|
|
290
|
-
opts
|
|
489
|
+
opts,
|
|
490
|
+
// Recognised by `shape`, never by `value`: that may be anything, and a
|
|
491
|
+
// query without a result can come back with no `value` at all.
|
|
492
|
+
has("shape", (shape) => typeof shape === "string")
|
|
291
493
|
);
|
|
292
494
|
}
|
|
293
495
|
// ── Fluent dataset handle ───────────────────────────────────────────────────
|
|
@@ -302,31 +504,114 @@ var HavenClient = class _HavenClient {
|
|
|
302
504
|
/**
|
|
303
505
|
* Clear cached reads. With no argument, clears everything. Pass a scope to
|
|
304
506
|
* clear just part of it: a node slug, or `{ node, dataset }` for one dataset.
|
|
507
|
+
* A scoped clear also drops every saved query result, as any of them may
|
|
508
|
+
* aggregate the content that was cleared.
|
|
305
509
|
*/
|
|
306
510
|
clearCache(scope) {
|
|
307
511
|
if (scope === void 0) {
|
|
308
512
|
this.cache.clear();
|
|
513
|
+
this.invalidated();
|
|
309
514
|
return;
|
|
310
515
|
}
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
516
|
+
const node = typeof scope === "string" ? scope : scope.node;
|
|
517
|
+
const dataset = typeof scope === "string" ? void 0 : scope.dataset;
|
|
518
|
+
if (dataset) {
|
|
519
|
+
this.invalidateDataset(node, dataset);
|
|
314
520
|
return;
|
|
315
521
|
}
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
this.cache.deletePrefix(`records:${scope.node}/`);
|
|
320
|
-
this.cache.deletePrefix(`record:${scope.node}/`);
|
|
321
|
-
}
|
|
522
|
+
this.dropPrefix(`records:${node}/`);
|
|
523
|
+
this.dropPrefix(`record:${node}/`);
|
|
524
|
+
this.dropPrefix("query:");
|
|
322
525
|
}
|
|
323
|
-
/**
|
|
324
|
-
*
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
this.
|
|
526
|
+
/**
|
|
527
|
+
* Invalidate cached record reads for a dataset (every locale), plus all query
|
|
528
|
+
* results (which may aggregate it). `drop` removes them; `recheck` keeps each
|
|
529
|
+
* value as a fallback but makes the next read ask the studio again.
|
|
530
|
+
*/
|
|
531
|
+
invalidateDataset(nodeSlug, datasetSlug, how = "drop") {
|
|
532
|
+
const one = how === "drop" ? (key) => this.drop(key) : (key) => this.recheck(key);
|
|
533
|
+
const all = how === "drop" ? (prefix) => this.dropPrefix(prefix) : (prefix) => this.recheckPrefix(prefix);
|
|
534
|
+
one(recordsKey(nodeSlug, datasetSlug));
|
|
535
|
+
all(`${recordsKey(nodeSlug, datasetSlug)}::`);
|
|
536
|
+
all(`${recordKey(nodeSlug, datasetSlug, "")}`);
|
|
537
|
+
all("query:");
|
|
538
|
+
}
|
|
539
|
+
/** Drop one key from the cache. */
|
|
540
|
+
drop(key) {
|
|
541
|
+
this.cache.delete(key);
|
|
542
|
+
this.invalidated();
|
|
543
|
+
}
|
|
544
|
+
/** `drop` for every key that starts with `prefix`. */
|
|
545
|
+
dropPrefix(prefix) {
|
|
546
|
+
this.cache.deletePrefix(prefix);
|
|
547
|
+
this.invalidated();
|
|
548
|
+
}
|
|
549
|
+
/** Like `drop`, but the value stays as a fallback (see `ContentCache.expire`). */
|
|
550
|
+
recheck(key) {
|
|
551
|
+
this.cache.expire(key);
|
|
552
|
+
this.invalidated();
|
|
553
|
+
}
|
|
554
|
+
/** `recheck` for every key that starts with `prefix`. */
|
|
555
|
+
recheckPrefix(prefix) {
|
|
556
|
+
this.cache.expirePrefix(prefix);
|
|
557
|
+
this.invalidated();
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Called by everything that invalidates cached reads. Every request that is
|
|
561
|
+
* under way at this moment left before it, so its answer may show the
|
|
562
|
+
* content as it was: none of them may store what they come back with
|
|
563
|
+
* (`storable`), and no later read may join one of them (hence the cleared
|
|
564
|
+
* `inflight`). They still answer the reads that were already waiting on them.
|
|
565
|
+
*
|
|
566
|
+
* Deliberately not narrowed to the keys that were invalidated. The price is
|
|
567
|
+
* that an unrelated answer now and then is served without being stored, and
|
|
568
|
+
* asked for once more; what it buys is one rule without exceptions.
|
|
569
|
+
*/
|
|
570
|
+
invalidated() {
|
|
571
|
+
this.state.invalidatedAt = this.state.ticket;
|
|
572
|
+
this.storedBy.clear();
|
|
573
|
+
this.inflight.clear();
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Whether the answer to the request that left on `ticket` may change what
|
|
577
|
+
* the cache holds for `key`. The single gate in front of every cache write
|
|
578
|
+
* that follows a request - cached read or bypass, a new value, a `304`, a
|
|
579
|
+
* deletion or a retry pause alike. It keeps the cache from going back in time:
|
|
580
|
+
*
|
|
581
|
+
* - not when the cache was invalidated after the request left: the answer
|
|
582
|
+
* may show the content from before (a write, `clearCache`);
|
|
583
|
+
* - not when the cache already holds the answer to a request that left
|
|
584
|
+
* later: that one is newer, whichever of the two came back first.
|
|
585
|
+
*/
|
|
586
|
+
storable(key, ticket) {
|
|
587
|
+
return ticket > this.state.invalidatedAt && ticket >= (this.storedBy.get(key) ?? 0);
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* Settles the cache with the studio's own definitive "no" for `key` (deleted,
|
|
591
|
+
* forbidden), in answer to the request that left on `ticket`: the entry goes.
|
|
592
|
+
* The one place this happens, for a cached read and a bypass alike.
|
|
593
|
+
*
|
|
594
|
+
* The deletion is noted like any other answer. Without that, a request that
|
|
595
|
+
* left earlier and comes back later would pass the gate and put the deleted
|
|
596
|
+
* content straight back.
|
|
597
|
+
*/
|
|
598
|
+
gone(key, ticket) {
|
|
599
|
+
if (!this.storable(key, ticket)) return;
|
|
600
|
+
this.cache.delete(key);
|
|
601
|
+
this.stored(key, ticket);
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* Notes that the cache now reflects, for `key`, the answer to the request
|
|
605
|
+
* that left on `ticket` - a value, a `304`, or the studio's own "this does
|
|
606
|
+
* not exist", after which the cache holds nothing for it. A refresh of that
|
|
607
|
+
* key that left earlier and is still under way is retired: a read arriving
|
|
608
|
+
* now must not join it for an older answer than the cache already reflects.
|
|
609
|
+
*/
|
|
610
|
+
stored(key, ticket) {
|
|
611
|
+
if (this.storedBy.size >= STORED_LIMIT) this.invalidated();
|
|
612
|
+
this.storedBy.set(key, ticket);
|
|
613
|
+
const running = this.inflight.get(key);
|
|
614
|
+
if (running && running.ticket < ticket) this.inflight.delete(key);
|
|
330
615
|
}
|
|
331
616
|
// ── Transport ───────────────────────────────────────────────────────────────
|
|
332
617
|
/**
|
|
@@ -335,76 +620,204 @@ var HavenClient = class _HavenClient {
|
|
|
335
620
|
* Steady state (project stamp unchanged since we last confirmed this entry):
|
|
336
621
|
* served straight from cache, zero network. After a content change the stamp
|
|
337
622
|
* moves, so the entry is revalidated once with `If-None-Match` - a `304` keeps
|
|
338
|
-
* the cached value, a `200` replaces it - and then it is fast again.
|
|
339
|
-
*
|
|
340
|
-
*
|
|
623
|
+
* the cached value, a `200` replaces it - and then it is fast again.
|
|
624
|
+
*
|
|
625
|
+
* Five rules hold for every read, whatever the studio does. Each is enforced
|
|
626
|
+
* in exactly one place, named here, so that it cannot hold for one kind of
|
|
627
|
+
* read and not for another:
|
|
628
|
+
*
|
|
629
|
+
* 1. A failure that is not the studio's own definitive answer never costs a
|
|
630
|
+
* cached value: it is served instead, and stays cached (`refresh`).
|
|
631
|
+
* 2. Only what is recognisably this endpoint's answer is ever stored
|
|
632
|
+
* (`conditionalGet`).
|
|
633
|
+
* 3. The cache never goes back in time: an answer is not stored when the
|
|
634
|
+
* cache was invalidated, or filled with a newer answer, after its request
|
|
635
|
+
* left (`storable`, in front of every write to the cache).
|
|
636
|
+
* 4. A read that already holds a value waits on the studio for `waitForFresh`
|
|
637
|
+
* at most, stamp check and refresh together (here); the refresh then
|
|
638
|
+
* finishes on the side.
|
|
639
|
+
* 5. One request per key at a time (`refresh`).
|
|
341
640
|
*/
|
|
342
|
-
async cachedGet(cacheKey, path, opts) {
|
|
641
|
+
async cachedGet(cacheKey, path, opts, isExpected, retry = true) {
|
|
343
642
|
const useCache = opts?.cache ?? this.readDefault;
|
|
344
643
|
if (!useCache) {
|
|
345
|
-
const
|
|
346
|
-
|
|
347
|
-
|
|
644
|
+
const version2 = this.versionTracker.current() ?? void 0;
|
|
645
|
+
const ticket = ++this.state.ticket;
|
|
646
|
+
let res;
|
|
647
|
+
try {
|
|
648
|
+
res = await this.conditionalGet(path, void 0, isExpected);
|
|
649
|
+
} catch (err) {
|
|
650
|
+
if (isDefinitive(err)) this.gone(cacheKey, ticket);
|
|
651
|
+
throw err;
|
|
652
|
+
}
|
|
653
|
+
if (this.storable(cacheKey, ticket)) {
|
|
654
|
+
this.cache.set(cacheKey, res.value, { etag: res.etag, version: version2 }, Date.now());
|
|
655
|
+
this.stored(cacheKey, ticket);
|
|
656
|
+
}
|
|
657
|
+
return res.value;
|
|
348
658
|
}
|
|
349
|
-
|
|
659
|
+
const started = Date.now();
|
|
660
|
+
const budget = this.cache.stale(cacheKey) ? this.waitForFresh : Infinity;
|
|
661
|
+
await within(this.versionTracker.refresh(started), budget);
|
|
350
662
|
const version = this.versionTracker.current() ?? void 0;
|
|
351
663
|
const entry = this.cache.peek(cacheKey, Date.now());
|
|
352
664
|
if (entry) {
|
|
353
665
|
if (version === void 0 || entry.validatedVersion === version) {
|
|
354
666
|
return entry.value;
|
|
355
667
|
}
|
|
668
|
+
}
|
|
669
|
+
const last = entry ?? this.cache.stale(cacheKey);
|
|
670
|
+
if (last?.retryAt !== void 0 && Date.now() < last.retryAt) {
|
|
671
|
+
return last.value;
|
|
672
|
+
}
|
|
673
|
+
const refresh = this.refresh(cacheKey, path, last, version, isExpected, retry);
|
|
674
|
+
if (!last) return refresh;
|
|
675
|
+
const outcome = await within(refresh, budget - (Date.now() - started));
|
|
676
|
+
return outcome.settled ? outcome.value : last.value;
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Fetches `cacheKey` from the studio and settles the cache with the answer.
|
|
680
|
+
* One per key at a time: reads that arrive while it runs get the same promise,
|
|
681
|
+
* so a slow studio sees one request for a key and not one per visitor.
|
|
682
|
+
*
|
|
683
|
+
* Resolves with the value to serve: the fresh one, or a cached one when the
|
|
684
|
+
* studio failed transiently. Rejects on a definitive answer, or when there is
|
|
685
|
+
* nothing cached to serve in its place.
|
|
686
|
+
*/
|
|
687
|
+
refresh(cacheKey, path, last, version, isExpected, retry) {
|
|
688
|
+
const running = this.inflight.get(cacheKey);
|
|
689
|
+
if (running) return running.job;
|
|
690
|
+
let ticket = ++this.state.ticket;
|
|
691
|
+
const registered = () => this.inflight.get(cacheKey)?.job === job;
|
|
692
|
+
const register = () => {
|
|
693
|
+
this.inflight.set(cacheKey, { job, ticket });
|
|
694
|
+
};
|
|
695
|
+
const job = (async () => {
|
|
356
696
|
try {
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
this.
|
|
360
|
-
|
|
697
|
+
let res;
|
|
698
|
+
try {
|
|
699
|
+
res = await this.conditionalGet(path, last?.etag, isExpected);
|
|
700
|
+
} catch (err) {
|
|
701
|
+
const pause = this.gatewayRetry;
|
|
702
|
+
if (!retry || pause === void 0 || last || this.cache.stale(cacheKey) || !isGatewayHiccup(err)) throw err;
|
|
703
|
+
await sleep(pause + Math.random() * pause);
|
|
704
|
+
const meanwhile = this.cache.stale(cacheKey);
|
|
705
|
+
if (meanwhile) return meanwhile.value;
|
|
706
|
+
const slot = this.inflight.get(cacheKey);
|
|
707
|
+
if (slot && !registered()) return slot.job;
|
|
708
|
+
ticket = ++this.state.ticket;
|
|
709
|
+
if (slot) slot.ticket = ticket;
|
|
710
|
+
else register();
|
|
711
|
+
version = this.versionTracker.current() ?? void 0;
|
|
712
|
+
res = await this.conditionalGet(path, void 0, isExpected);
|
|
361
713
|
}
|
|
362
|
-
|
|
363
|
-
|
|
714
|
+
if (res.notModified && last) {
|
|
715
|
+
if (this.storable(cacheKey, ticket)) {
|
|
716
|
+
this.cache.confirm(cacheKey, version, Date.now());
|
|
717
|
+
this.stored(cacheKey, ticket);
|
|
718
|
+
}
|
|
719
|
+
return last.value;
|
|
720
|
+
}
|
|
721
|
+
if (this.storable(cacheKey, ticket)) {
|
|
722
|
+
this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now());
|
|
723
|
+
this.stored(cacheKey, ticket);
|
|
724
|
+
}
|
|
725
|
+
return res.value;
|
|
364
726
|
} catch (err) {
|
|
365
|
-
if (err
|
|
366
|
-
this.
|
|
727
|
+
if (isDefinitive(err)) {
|
|
728
|
+
this.gone(cacheKey, ticket);
|
|
367
729
|
throw err;
|
|
368
730
|
}
|
|
369
|
-
|
|
731
|
+
const held = this.cache.stale(cacheKey) ?? last;
|
|
732
|
+
if (!held) throw err;
|
|
733
|
+
this.report({ during: "read", key: cacheKey, error: err });
|
|
734
|
+
return (this.storable(cacheKey, ticket) ? this.cache.backoff(cacheKey, held, Date.now()) : held).value;
|
|
735
|
+
} finally {
|
|
736
|
+
if (registered()) this.inflight.delete(cacheKey);
|
|
737
|
+
}
|
|
738
|
+
})();
|
|
739
|
+
this.inflight.set(cacheKey, { job, ticket });
|
|
740
|
+
return job;
|
|
741
|
+
}
|
|
742
|
+
/**
|
|
743
|
+
* Hands an absorbed failure to `onError`, or without one warns once per
|
|
744
|
+
* outage. Never throws and never leaves a rejection behind: a broken hook
|
|
745
|
+
* must not turn a served read into an error, and an `async` hook whose own
|
|
746
|
+
* work fails (an alert that cannot be delivered, during the very outage it
|
|
747
|
+
* reports) must not become the unhandled rejection that stops the process.
|
|
748
|
+
*/
|
|
749
|
+
report(failure) {
|
|
750
|
+
const first = !this.state.unreachable;
|
|
751
|
+
this.state.unreachable = true;
|
|
752
|
+
try {
|
|
753
|
+
if (this.onError) {
|
|
754
|
+
const outcome = this.onError(failure);
|
|
755
|
+
if (isThenable(outcome)) outcome.then(void 0, () => {
|
|
756
|
+
});
|
|
757
|
+
} else if (first) {
|
|
758
|
+
const reason = failure.error instanceof Error ? failure.error.message : String(failure.error);
|
|
759
|
+
const what = failure.during === "read" ? `could not refresh "${failure.key}"` : "stamp check failed";
|
|
760
|
+
console.warn(`[@nordhavnhq/beacon] ${what} (${reason}); cached content keeps being served.`);
|
|
370
761
|
}
|
|
762
|
+
} catch {
|
|
371
763
|
}
|
|
372
|
-
const res = await this.conditionalGet(path);
|
|
373
|
-
this.cache.set(cacheKey, res.value, { etag: res.etag, version }, Date.now());
|
|
374
|
-
return res.value;
|
|
375
764
|
}
|
|
376
765
|
/**
|
|
377
766
|
* A GET that understands conditional requests: sends `If-None-Match` when an
|
|
378
767
|
* etag is supplied, and reports a `304` as `notModified` rather than a value.
|
|
768
|
+
*
|
|
769
|
+
* The one place that decides what counts as an answer, for every read:
|
|
770
|
+
*
|
|
771
|
+
* - A `2xx` whose body fails `isExpected` is rejected, not returned. A
|
|
772
|
+
* maintenance page or a captive portal can answer `200` with JSON of its
|
|
773
|
+
* own; storing that would replace the last good value with nothing, at the
|
|
774
|
+
* very moment the studio is away.
|
|
775
|
+
* - A `304` is only an answer to a request that sent an etag. Unasked for,
|
|
776
|
+
* it says "keep what you have" to a caller that has nothing, and there is
|
|
777
|
+
* no value to return or store.
|
|
379
778
|
*/
|
|
380
|
-
async conditionalGet(path, ifNoneMatch) {
|
|
381
|
-
const
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
779
|
+
async conditionalGet(path, ifNoneMatch, isExpected) {
|
|
780
|
+
const url = `${this.baseUrl}/api/content${path}`;
|
|
781
|
+
return withTimeout(url, this.timeout, async (signal) => {
|
|
782
|
+
const res = await this.fetchImpl(url, {
|
|
783
|
+
method: "GET",
|
|
784
|
+
headers: {
|
|
785
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
786
|
+
...ifNoneMatch ? { "If-None-Match": ifNoneMatch } : {},
|
|
787
|
+
...this.headers
|
|
788
|
+
},
|
|
789
|
+
signal
|
|
790
|
+
});
|
|
791
|
+
if (res.status === 304) {
|
|
792
|
+
if (!ifNoneMatch) throw unexpectedBody(url);
|
|
793
|
+
this.state.unreachable = false;
|
|
794
|
+
return { notModified: true, etag: res.headers.get("etag") ?? ifNoneMatch };
|
|
387
795
|
}
|
|
796
|
+
if (!res.ok) throw await this.toError(res);
|
|
797
|
+
const etag = res.headers.get("etag") ?? void 0;
|
|
798
|
+
const value = res.status === 204 ? void 0 : await res.json();
|
|
799
|
+
if (!isExpected(value)) throw unexpectedBody(url);
|
|
800
|
+
this.state.unreachable = false;
|
|
801
|
+
return { notModified: false, value, etag };
|
|
388
802
|
});
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
const
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
}
|
|
403
|
-
|
|
803
|
+
}
|
|
804
|
+
async request(method, path, body, timeout = this.timeout) {
|
|
805
|
+
const url = `${this.baseUrl}/api/content${path}`;
|
|
806
|
+
return withTimeout(url, timeout, async (signal) => {
|
|
807
|
+
const res = await this.fetchImpl(url, {
|
|
808
|
+
method,
|
|
809
|
+
headers: {
|
|
810
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
811
|
+
...body !== void 0 ? { "Content-Type": "application/json" } : {},
|
|
812
|
+
...this.headers
|
|
813
|
+
},
|
|
814
|
+
body: body !== void 0 ? JSON.stringify(body) : void 0,
|
|
815
|
+
signal
|
|
816
|
+
});
|
|
817
|
+
if (!res.ok) throw await this.toError(res);
|
|
818
|
+
if (res.status === 204) return void 0;
|
|
819
|
+
return await res.json();
|
|
404
820
|
});
|
|
405
|
-
if (!res.ok) throw await this.toError(res);
|
|
406
|
-
if (res.status === 204) return void 0;
|
|
407
|
-
return res.json();
|
|
408
821
|
}
|
|
409
822
|
/** Parse a non-2xx response into a `HavenError`, preferring its message. */
|
|
410
823
|
async toError(res) {
|
|
@@ -417,7 +830,9 @@ var HavenClient = class _HavenClient {
|
|
|
417
830
|
else if (typeof m?.statusMessage === "string") message = m.statusMessage;
|
|
418
831
|
} catch {
|
|
419
832
|
}
|
|
420
|
-
|
|
833
|
+
const err = new HavenError(message, res.status, parsed);
|
|
834
|
+
if (res.headers.has("retry-after")) askedToWait.add(err);
|
|
835
|
+
return err;
|
|
421
836
|
}
|
|
422
837
|
};
|
|
423
838
|
var DatasetHandle = class {
|
|
@@ -456,9 +871,108 @@ function isPreviewRequest(input) {
|
|
|
456
871
|
}
|
|
457
872
|
return Object.prototype.hasOwnProperty.call(input, PREVIEW_PARAM);
|
|
458
873
|
}
|
|
874
|
+
async function withTimeout(url, ms, run) {
|
|
875
|
+
if (ms <= 0) return run(void 0);
|
|
876
|
+
const controller = new AbortController();
|
|
877
|
+
let timer;
|
|
878
|
+
const expired = new Promise((_, reject) => {
|
|
879
|
+
timer = setTimeout(() => {
|
|
880
|
+
const err = new Error(`The studio did not answer within ${ms}ms: ${url}`);
|
|
881
|
+
err.name = "TimeoutError";
|
|
882
|
+
controller.abort(err);
|
|
883
|
+
reject(err);
|
|
884
|
+
}, ms);
|
|
885
|
+
});
|
|
886
|
+
try {
|
|
887
|
+
return await Promise.race([run(controller.signal), expired]);
|
|
888
|
+
} finally {
|
|
889
|
+
clearTimeout(timer);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
function normalizeTimeout(value) {
|
|
893
|
+
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_TIMEOUT;
|
|
894
|
+
return value > MAX_TIMER ? 0 : value;
|
|
895
|
+
}
|
|
896
|
+
function normalizeGatewayRetry(value) {
|
|
897
|
+
if (value === false) return void 0;
|
|
898
|
+
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_GATEWAY_RETRY;
|
|
899
|
+
return Math.min(value, MAX_GATEWAY_RETRY);
|
|
900
|
+
}
|
|
901
|
+
function normalizeWait(value) {
|
|
902
|
+
if (value === false) return Infinity;
|
|
903
|
+
if (typeof value !== "number" || Number.isNaN(value) || value < 0) return DEFAULT_WAIT_FOR_FRESH;
|
|
904
|
+
return value > MAX_TIMER ? Infinity : value;
|
|
905
|
+
}
|
|
906
|
+
async function within(promise, ms) {
|
|
907
|
+
if (ms > MAX_TIMER) return { settled: true, value: await promise };
|
|
908
|
+
if (ms <= 0) {
|
|
909
|
+
promise.catch(() => {
|
|
910
|
+
});
|
|
911
|
+
return { settled: false };
|
|
912
|
+
}
|
|
913
|
+
let timer;
|
|
914
|
+
const late = new Promise((resolve) => {
|
|
915
|
+
timer = setTimeout(() => resolve({ settled: false }), ms);
|
|
916
|
+
});
|
|
917
|
+
try {
|
|
918
|
+
return await Promise.race([promise.then((value) => ({ settled: true, value })), late]);
|
|
919
|
+
} finally {
|
|
920
|
+
clearTimeout(timer);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
function isThenable(value) {
|
|
924
|
+
return typeof value?.then === "function";
|
|
925
|
+
}
|
|
926
|
+
function isObject(value) {
|
|
927
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
928
|
+
}
|
|
929
|
+
function has(field, check) {
|
|
930
|
+
return (body) => isObject(body) && field in body && check(body[field]);
|
|
931
|
+
}
|
|
932
|
+
function unexpectedBody(url) {
|
|
933
|
+
const err = new Error(`The studio answered with an unexpected response: ${url}`);
|
|
934
|
+
err.name = "UnexpectedResponseError";
|
|
935
|
+
return err;
|
|
936
|
+
}
|
|
937
|
+
function isTransientStatus(status) {
|
|
938
|
+
return status >= 500 || status === 408 || status === 429;
|
|
939
|
+
}
|
|
940
|
+
var askedToWait = /* @__PURE__ */ new WeakSet();
|
|
941
|
+
function isGatewayHiccup(err) {
|
|
942
|
+
return err instanceof HavenError && (err.status === 502 || err.status === 503) && !askedToWait.has(err);
|
|
943
|
+
}
|
|
944
|
+
function sleep(ms) {
|
|
945
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
946
|
+
}
|
|
947
|
+
function isDefinitive(err) {
|
|
948
|
+
return err instanceof HavenError && !isTransientStatus(err.status) && isStudioAnswer(err);
|
|
949
|
+
}
|
|
950
|
+
function isStudioAnswer(err) {
|
|
951
|
+
const body = err.body;
|
|
952
|
+
if (typeof body !== "object" || body === null) return false;
|
|
953
|
+
return body.statusCode === err.status || body.status === err.status;
|
|
954
|
+
}
|
|
955
|
+
function isMissingRoute(err) {
|
|
956
|
+
return err instanceof HavenError && err.status === 404 && isStudioAnswer(err);
|
|
957
|
+
}
|
|
958
|
+
function writeMayHaveLanded(err) {
|
|
959
|
+
return !(err instanceof HavenError && err.status >= 400 && err.status < 500);
|
|
960
|
+
}
|
|
459
961
|
function datasetPath(nodeSlug, datasetSlug) {
|
|
460
962
|
return `/nodes/${encodeURIComponent(nodeSlug)}/datasets/${encodeURIComponent(datasetSlug)}/records`;
|
|
461
963
|
}
|
|
964
|
+
function matchLocale(requested, locales) {
|
|
965
|
+
const canonical = (code) => code.trim().toLowerCase().replace(/_/g, "-");
|
|
966
|
+
const known = locales.filter((locale) => typeof locale?.code === "string" && locale.code !== "");
|
|
967
|
+
const wanted = canonical(requested);
|
|
968
|
+
const exact = known.find((locale) => canonical(locale.code) === wanted);
|
|
969
|
+
if (exact) return exact.code;
|
|
970
|
+
const language = wanted.split("-")[0];
|
|
971
|
+
const related = known.filter((locale) => canonical(locale.code).split("-")[0] === language);
|
|
972
|
+
const close = related.find((locale) => locale.isDefault) ?? related[0];
|
|
973
|
+
if (close) return close.code;
|
|
974
|
+
return known.find((locale) => locale.isFallback)?.code;
|
|
975
|
+
}
|
|
462
976
|
function localeQuery(locale) {
|
|
463
977
|
return locale ? `?locale=${encodeURIComponent(locale)}` : "";
|
|
464
978
|
}
|