@niwa-labs/requests 0.0.0-stage → 0.0.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/src/index.ts ADDED
@@ -0,0 +1,619 @@
1
+ /**
2
+ * The requests module: someone waits for a typed answer from someone.
3
+ *
4
+ * - **request.ask** creates the request and, as a step, waits for the answer in one call, so an
5
+ * answer cannot arrive between the two and be missed. The wait survives a restart. Called
6
+ * directly it cannot wait: it returns the id of the open request.
7
+ * - **request.answer** answers a request. The caller is bound to an address by the transport,
8
+ * never by the payload, and only the addressee may answer. The first answer stands.
9
+ * - **request.cancel** cancels an open request; only its asker or addressee may.
10
+ * - **request.open** lists what waits: open requests, and invocations paused for a decision.
11
+ * - **request.list** and **request.get** read any request, open or ended, by id or short form.
12
+ *
13
+ * The state of a request is folded from the journal (`state.ts`). A plugin may register a
14
+ * resolver to answer a request before it reaches its addressee (`resolver.ts`).
15
+ */
16
+
17
+ import { z } from "zod";
18
+
19
+ import { action, isSuspend, providerWrote, recordId, stableJson, Address } from "@niwa-labs/core";
20
+ import type { Action, Answer, Caller, OperationId, RecordId, RecordType, Timestamp } from "@niwa-labs/core";
21
+ import { COCKPIT_MODULE, plugin, bindingOf } from "@niwa-labs/plugin";
22
+ import { fileURLToPath } from "node:url";
23
+ import type { CallerBinding, Plugin } from "@niwa-labs/plugin";
24
+
25
+ import { PendingAsks, outcomeOf, requestOf } from "./access-ask.ts";
26
+ import { AskInput, AskOutput, OpenOutput, requestAnswer, requestAsk, requestCancel, requestFind, requestGet, requestList, requestOpen, requestResolve } from "./actions.ts";
27
+ import { entityOf, itemOf } from "./entity.ts";
28
+ import { holdAnswerCheck, releaseAnswerCheck } from "./question.ts";
29
+ import {
30
+ REQUEST_TYPES,
31
+ Deadline,
32
+ RequestAnswered,
33
+ RequestCancelledRecord,
34
+ RequestCreated,
35
+ RequestExpiredRecord,
36
+ RequestId,
37
+ expiryId,
38
+ } from "./records.ts";
39
+ import { ResolverRegistry } from "./resolver.ts";
40
+ import {
41
+ RequestCancelled,
42
+ RequestExpired,
43
+ RequestLedger,
44
+ RequestRefusal,
45
+ checkAnswer,
46
+ decideAnswer,
47
+ decideCancel,
48
+ operatorAnswered,
49
+ requestOfCause,
50
+ sameAddress,
51
+ } from "./state.ts";
52
+
53
+ export { ACCESS_ASK } from "./access-ask.ts";
54
+ export { question } from "./question.ts";
55
+ export type { DeclaredQuestion } from "./question.ts";
56
+ export {
57
+ Deadline,
58
+ QuestionName,
59
+ REQUEST_TYPES,
60
+ RequestAnswered,
61
+ RequestCancelledRecord,
62
+ RequestCreated,
63
+ RequestExpiredRecord,
64
+ RequestId,
65
+ expiryId,
66
+ } from "./records.ts";
67
+ export { ResolverRegistry } from "./resolver.ts";
68
+ export type { Resolver, ResolverInfo, ResolverRequest, ResolverResult } from "./resolver.ts";
69
+ export { RequestCancelled, RequestExpired, RequestLedger, RequestRefusal, fold } from "./state.ts";
70
+ export type { AnswerVerdict, RequestState } from "./state.ts";
71
+
72
+ /** How long the module waits before it tries again to expire a request it could not. */
73
+ const EXPIRY_RETRY_MS = 1000;
74
+
75
+ /** The longest delay a timer takes: a longer one fires at once. The timer is set again then. */
76
+ const MAX_TIMER_MS = 2 ** 31 - 1;
77
+
78
+ /** What the plugin is given. */
79
+ export interface RequestsOptions {
80
+ /**
81
+ * The binding says what address a caller speaks as: the same one the other modules that speak by
82
+ * address use. Default: a client speaks as itself, the owner as the owner, nobody else as anybody.
83
+ */
84
+ readonly bind?: CallerBinding;
85
+ /** The resolvers that may answer a request before it reaches its addressee. */
86
+ readonly resolvers?: ResolverRegistry;
87
+ /**
88
+ * How long the owner has to answer the question of an `ask` rule, in milliseconds of the host's
89
+ * clock. A call whose question is not answered in time is denied Ten minutes by default.
90
+ */
91
+ readonly askTimeoutMs?: number;
92
+ }
93
+
94
+ /** How long the owner has to answer a question of a grant when nothing says otherwise. */
95
+ const DEFAULT_ASK_TIMEOUT_MS = 10 * 60 * 1000;
96
+
97
+ /**
98
+ * The record a call writes first when it is not inside an invocation, or inside one: the operation
99
+ * and the ordinal of the write (the way the core places a record an action emits). The id of a
100
+ * request is issued from it, so a step made again is the same request.
101
+ */
102
+ function createdRecordOf(operation: OperationId): RecordId {
103
+ return recordId(`${operation}/emit/1`);
104
+ }
105
+
106
+ /**
107
+ * The action that asks a question and waits for the answer.
108
+ *
109
+ * The id of the request is issued from the record the ask writes, which follows the operation, so
110
+ * a step made again is the same request. The answer is looked for after the request was written,
111
+ * so one that arrives at once is not missed. A call outside an invocation has nothing to suspend:
112
+ * it returns the request as open.
113
+ *
114
+ * The wait ends with the first of three things: an answer, a cancellation or an expiry. The
115
+ * two latter end the wait with an error the caller catches — `RequestCancelled` or
116
+ * `RequestExpired` — so nobody waits for ever.
117
+ */
118
+ export function askWith(bind: CallerBinding, ledger: RequestLedger): Action<z.infer<typeof AskInput>, z.infer<typeof AskOutput>, z.input<typeof AskInput>> {
119
+ return action(requestAsk, {
120
+ // The request is written under the id of the operation, so the question is the same one
121
+ // however many times the call is made: it may be made again, and the wait finds the
122
+ // answer that arrived in the meantime.
123
+ recovery: "repeat",
124
+ effect: "record",
125
+ world: "niwa",
126
+ async run(input, ctx) {
127
+ if (input.answerPolicy === "owner-only" && input.to.kind !== "owner") throw new Error("An owner-only request must address the owner");
128
+ const id = ledger.ids.issue(createdRecordOf(ctx.operationId));
129
+ // A run asks as itself, whatever the host binds its other callers to: the owner sees who asks.
130
+ // A client is held to its binding; a handler or the host, in-process, may say who asks.
131
+ const from: Address | undefined =
132
+ ctx.caller.kind === "client" && ctx.caller.principal?.kind === "run"
133
+ ? { kind: "client", id: ctx.caller.id }
134
+ : (bind(ctx.caller) ?? (ctx.caller.kind === "client" ? undefined : input.from));
135
+ // While this process waits, the zod schema of the value of a form checks it whole: JSON
136
+ // Schema cannot say a refinement, and an answer that fails one must be refused, not written.
137
+ // Outside an invocation nothing waits, so there is nothing to hold it for.
138
+ const waits = ctx.invocation !== undefined;
139
+ if (waits && input.check !== undefined) holdAnswerCheck(id, input.check);
140
+ try {
141
+ const created = await ctx.emit(RequestCreated, {
142
+ id,
143
+ to: input.to,
144
+ ...(input.answerPolicy === undefined ? {} : { answerPolicy: input.answerPolicy }),
145
+ question: input.question,
146
+ input: input.input,
147
+ ...(from === undefined ? {} : { from }),
148
+ ...(input.deadline === undefined ? {} : { deadline: input.deadline }),
149
+ });
150
+ // A call outside an invocation cannot wait: it leaves the request open and says so, and
151
+ // the caller reads the answer later by the id.
152
+ if (!waits) return { id, status: "open" as const };
153
+ let after = created.seq;
154
+ for (;;) {
155
+ const ended = await ctx.waitAnyOf(
156
+ [
157
+ { type: RequestAnswered, filter: { id } },
158
+ { type: RequestCancelledRecord, filter: { id } },
159
+ { type: RequestExpiredRecord, filter: { id } },
160
+ ] as const,
161
+ { from: after },
162
+ );
163
+ const state = ledger.requests().get(id);
164
+ if (state?.status === "answered") {
165
+ releaseAnswerCheck(id);
166
+ return { id, answer: state.answer };
167
+ }
168
+ if (state?.status === "cancelled") throw new RequestCancelled(id);
169
+ if (state?.status === "expired") throw new RequestExpired(id);
170
+ // A historical row without provider provenance cannot end the wait.
171
+ after = ended.at;
172
+ }
173
+ } catch (error) {
174
+ // A wait that suspends the invocation throws, and the schema stays held for the run that
175
+ // resumes it; any other failure ends the ask, and with it the hold.
176
+ if (!isSuspend(error)) releaseAnswerCheck(id);
177
+ throw error;
178
+ }
179
+ },
180
+ });
181
+ }
182
+
183
+ /**
184
+ * Who gives the answer of a resolve: the address a client is bound to, which must be the addressee
185
+ * of the request or the owner. A configured owner surface can give the operator’s explicit answer.
186
+ */
187
+ function answerer(caller: Caller, bind: CallerBinding, to: Address, forwarded: boolean): Address | undefined {
188
+ if (caller.kind === "handler" && !forwarded) {
189
+ const surface = bind(caller);
190
+ return surface?.kind === "owner" ? surface : undefined;
191
+ }
192
+ if (caller.kind !== "client") return undefined;
193
+ const by = bind(caller);
194
+ if (by === undefined) {
195
+ throw new RequestRefusal("unbound", "the caller is not bound to an address, so it cannot answer");
196
+ }
197
+ if (by.kind !== "owner" && !sameAddress(by, to)) {
198
+ throw new RequestRefusal("not-addressee", "only the addressee of the request, or the owner, may answer it");
199
+ }
200
+ return by;
201
+ }
202
+
203
+ /**
204
+ * What the actions need of the host's time: its clock, and the write that ends a request whose
205
+ * deadline has passed. The clock is absent until the host serves.
206
+ */
207
+ export interface Expiry {
208
+ now(): Timestamp | undefined;
209
+ /** End the request as expired: the one record a request has for it, whoever writes it. */
210
+ expire(id: RequestId): Promise<void>;
211
+ }
212
+
213
+ /**
214
+ * The request an earlier try of this operation already ended with a record of this type, when there
215
+ * is one. The record of an action takes its id from the operation, so a try made again finds it,
216
+ * whatever it called the request by.
217
+ */
218
+ function writtenBefore<T extends { id: RequestId }>(ledger: RequestLedger, operation: OperationId, type: RecordType<T>): T | undefined {
219
+ const stored = ledger.recordOf(createdRecordOf(operation));
220
+ if (stored?.type !== type.name || !providerWrote(stored, "requests")) return undefined;
221
+ const data = type.schema.safeParse(stored.data);
222
+ return data.success ? data.data : undefined;
223
+ }
224
+
225
+ /** The actions that read and write the state of requests, from the facts and the binding. */
226
+ export function requestActions(ledger: RequestLedger, bind: CallerBinding, resolvers: ResolverRegistry, expiry: Expiry) {
227
+ /**
228
+ * Whether the request is open and its deadline has passed by the clock of the host. It is
229
+ * ended as expired then, before the timer gets to it, so no answer is taken between the two.
230
+ */
231
+ const expiredNow = async (id: RequestId): Promise<boolean> => {
232
+ const state = ledger.requests().get(id);
233
+ const now = expiry.now();
234
+ if (state?.status !== "open" || now === undefined) return false;
235
+ const { deadline } = state.created;
236
+ if (deadline === undefined || deadline > now) return false;
237
+ await expiry.expire(id);
238
+ return true;
239
+ };
240
+
241
+ /** How the request ended other than by an answer, when it did: an answer written after that does not stand. */
242
+ const endedBefore = (id: RequestId): "cancelled" | "expired" | undefined => {
243
+ const status = ledger.requests().get(id)?.status;
244
+ return status === "cancelled" || status === "expired" ? status : undefined;
245
+ };
246
+
247
+ /** Whether the answer written for the request is the one that stands: nothing ended it first. */
248
+ const stands = (id: RequestId, answer: Answer): boolean => {
249
+ const state = ledger.requests().get(id);
250
+ return state?.status === "answered" && stableJson(state.answer) === stableJson(answer);
251
+ };
252
+
253
+ const answer = action(requestAnswer, {
254
+ // The answer is written under the id of the operation, and the first answer stands:
255
+ // a call that was cut off may be made again, and the same answer stands.
256
+ recovery: "repeat",
257
+ effect: "record",
258
+ world: "niwa",
259
+ async run(input, ctx) {
260
+ // A try that was cut off after its answer was written finds it: the request is named by the
261
+ // record of this operation, not by what the call said, which may be a run with no open ask now.
262
+ const written = writtenBefore(ledger, ctx.operationId, RequestAnswered);
263
+ if (written !== undefined) {
264
+ const reason = endedBefore(written.id);
265
+ return reason === undefined ? { id: written.id, accepted: true } : { id: written.id, accepted: false, reason };
266
+ }
267
+ const by = bind(ctx.caller);
268
+ const id = ledger.named(input, (request) => by !== undefined && (by.kind === "owner" || sameAddress(by, request.to)));
269
+ const state = ledger.requests().get(id);
270
+ if (state?.created.answerPolicy === "owner-only" && (by?.kind !== "owner" ||
271
+ (ctx.caller.kind === "client" ? ctx.caller.principal?.kind !== "owner" : ctx.caller.kind !== "handler"))) {
272
+ throw new RequestRefusal("not-addressee", "Only the owner may answer this request");
273
+ }
274
+ const verdict = decideAnswer(id, state, by, input.answer);
275
+ if (verdict.kind === "late") {
276
+ // The request was over before the answer came: nothing is written, and the answerer is
277
+ // told why its answer does not stand instead of being refused.
278
+ return { id, accepted: false, reason: verdict.reason };
279
+ }
280
+ if (verdict.kind === "write") {
281
+ // An answer that comes after the deadline comes too late, whether or not the timer has run.
282
+ if (await expiredNow(id)) return { id, accepted: false, reason: "expired" };
283
+ await ctx.emit(RequestAnswered, { id, answer: input.answer, ...(by === undefined ? {} : { by }) });
284
+ // Something may have ended the request while this was written: the first end stands.
285
+ const reason = endedBefore(id);
286
+ if (reason !== undefined) return { id, accepted: false, reason };
287
+ }
288
+ return { id, accepted: true };
289
+ },
290
+ });
291
+
292
+ const cancel = action(requestCancel, {
293
+ // The cancellation is written under the id of the operation, and the same address
294
+ // cancelling again changes nothing: a call that was cut off may be made again.
295
+ recovery: "repeat",
296
+ effect: "record",
297
+ world: "niwa",
298
+ async run(input, ctx) {
299
+ const cancelled = writtenBefore(ledger, ctx.operationId, RequestCancelledRecord);
300
+ if (cancelled !== undefined) return { id: cancelled.id };
301
+ // A client is held to its binding; a handler or the host, in-process, may say who cancels.
302
+ const by = bind(ctx.caller) ?? (ctx.caller.kind === "client" ? undefined : input.by);
303
+ const id = ledger.named(input, (request) => by !== undefined && (by.kind === "owner" || [request.to, request.from].some((party) => party !== undefined && sameAddress(by, party))));
304
+ const verdict = decideCancel(id, ledger.requests().get(id), by);
305
+ if (verdict === "write") {
306
+ await ctx.emit(RequestCancelledRecord, {
307
+ id,
308
+ ...(input.reason === undefined ? {} : { reason: input.reason }),
309
+ ...(by === undefined ? {} : { by }),
310
+ });
311
+ }
312
+ return { id };
313
+ },
314
+ });
315
+
316
+ const open = action(requestOpen, {
317
+ // A read of what waits changes nothing: it may be made again.
318
+ recovery: "repeat",
319
+ effect: "read",
320
+ world: "niwa",
321
+ async run(input) {
322
+ const requests: z.infer<typeof OpenOutput>["requests"] = [];
323
+ for (const state of ledger.requests().values()) {
324
+ if (state.status !== "open") continue;
325
+ if (input.to !== undefined && !sameAddress(state.created.to, input.to)) continue;
326
+ requests.push(state.created);
327
+ }
328
+ for (const paused of ledger.paused()) requests.push({ kind: "paused", ...paused, choices: [...paused.choices] });
329
+ return { requests };
330
+ },
331
+ });
332
+
333
+ const list = action(requestList, {
334
+ // A read of what exists changes nothing: it may be made again.
335
+ recovery: "repeat",
336
+ effect: "read",
337
+ world: "niwa",
338
+ async run(input) {
339
+ const items = [...ledger.requests().values()]
340
+ .filter(
341
+ (state) =>
342
+ (input.status === undefined || state.status === input.status) &&
343
+ (input.to === undefined || sameAddress(state.created.to, input.to)) &&
344
+ (input.from === undefined || (state.created.from !== undefined && sameAddress(state.created.from, input.from))) &&
345
+ (input.question === undefined || state.created.question === input.question),
346
+ )
347
+ .map(itemOf);
348
+ return { items };
349
+ },
350
+ });
351
+
352
+ const get = action(requestGet, {
353
+ recovery: "repeat",
354
+ effect: "read",
355
+ world: "niwa",
356
+ async run(input) {
357
+ return entityOf(ledger.get(input.id));
358
+ },
359
+ });
360
+
361
+ const resolve = action(requestResolve, {
362
+ // The resolvers only read and answer, and the answer stands: a resolve that was cut
363
+ // off may be made again.
364
+ recovery: "repeat",
365
+ effect: "record",
366
+ world: "niwa",
367
+ async run(input, ctx) {
368
+ // A try that was cut off after its answer was written finds it, whoever gave the answer.
369
+ const written = writtenBefore(ledger, ctx.operationId, RequestAnswered);
370
+ if (written !== undefined) return { answered: stands(written.id, written.answer) };
371
+ // The id is the whole id of a request: a short form is not tried, so a request that does not
372
+ // exist is never taken for a longer one that starts the same.
373
+ const id = input.id;
374
+ const state = ledger.requests().get(id);
375
+ if (state?.created.answerPolicy === "owner-only") return { answered: false };
376
+ // A client that gives an answer is held to its binding as the one who answers is: the
377
+ // addressee, or the owner. `submit-answer` and answers forwarded by another module reach the request here.
378
+ const by = input.answer === undefined || state === undefined ? undefined : answerer(ctx.caller, bind, state.created.to, input.info !== undefined);
379
+ // The same answer to a request it already answered stands: a call made again says so.
380
+ if (
381
+ input.answer !== undefined &&
382
+ state?.status === "answered" &&
383
+ stableJson(input.answer) === stableJson(state.answer)
384
+ ) {
385
+ return { answered: true };
386
+ }
387
+ if (state?.status !== "open") return { answered: false };
388
+ if (await expiredNow(id)) return { answered: false };
389
+ const { question: name, input: asked, to, from } = state.created;
390
+ // An answer given with the resolve is the answer of the request: it is checked against
391
+ // the schema of the question, as the answer of the addressee is.
392
+ if (input.answer !== undefined) {
393
+ checkAnswer(state.created, input.answer);
394
+ const info = input.info;
395
+ await ctx.emit(RequestAnswered, {
396
+ id,
397
+ answer: input.answer,
398
+ ...(by === undefined ? {} : { by }),
399
+ ...(info?.how === undefined ? {} : { how: info.how }),
400
+ ...(info?.area === undefined ? {} : { area: info.area }),
401
+ ...(info?.source === undefined ? {} : { source: info.source }),
402
+ });
403
+ return { answered: stands(id, input.answer) };
404
+ }
405
+ for (const resolver of resolvers.resolversFor(name)) {
406
+ const result = await resolver({ question: name, input: asked, to, ...(from === undefined ? {} : { from }) });
407
+ if (!result.answered) continue;
408
+ // The request went on while the resolver worked: what ended it first stands.
409
+ const current = ledger.requests().get(id);
410
+ if (current?.status !== "open") return { answered: false };
411
+ if (await expiredNow(id)) return { answered: false };
412
+ // The answer of a resolver must fit the question as the answer of anyone does; one that
413
+ // does not is no answer, and the request stays open for the next resolver or its addressee.
414
+ try {
415
+ checkAnswer(current.created, result.answer);
416
+ } catch (error) {
417
+ if (!(error instanceof RequestRefusal)) throw error;
418
+ console.error(`niwa: a resolver of "${name}" gave an answer that does not fit the request "${id}": ${error.message}`);
419
+ continue;
420
+ }
421
+ // The answer is the answer of the request: the asker parses it against the schema of
422
+ // its question. How the resolver found it is told apart from it, so that the way it
423
+ // was found does not have to pass the schema of the answer.
424
+ const info = result.info;
425
+ await ctx.emit(RequestAnswered, {
426
+ id,
427
+ answer: result.answer,
428
+ ...(info?.how === undefined ? {} : { how: info.how }),
429
+ ...(info?.area === undefined ? {} : { area: info.area }),
430
+ ...(info?.source === undefined ? {} : { source: info.source }),
431
+ });
432
+ return { answered: stands(id, result.answer) };
433
+ }
434
+ return { answered: false };
435
+ },
436
+ });
437
+
438
+ return { answer, cancel, open, list, get, resolve };
439
+ }
440
+
441
+ /** The requests module. */
442
+ export function requests(opts: RequestsOptions = {}): Plugin {
443
+ const bind = opts.bind ?? bindingOf();
444
+ const resolvers = opts.resolvers ?? new ResolverRegistry();
445
+
446
+ return plugin("requests", (api) => {
447
+ // The page of this plugin in the cockpit: a client module, offered by the path of its source.
448
+ api.offer(COCKPIT_MODULE, { id: "requests", entry: fileURLToPath(new URL("./cockpit/index.tsx", import.meta.url)) });
449
+ api.declare(...REQUEST_TYPES);
450
+ const types = REQUEST_TYPES.map((type) => type.name);
451
+ const ledger = new RequestLedger(types, () => api.journal?.(), bind);
452
+ // The clock of the host, known once the service runs: an answer is held to the deadline by it.
453
+ let clock: (() => Timestamp) | undefined;
454
+ const expiry: Expiry = {
455
+ now: () => clock?.(),
456
+ // The id of the expiry is a function of the request, so the timer and an answer that finds the deadline passed write the same record.
457
+ expire: async (id) => {
458
+ await api.emit(RequestExpiredRecord, { id }, { id: expiryId(id) });
459
+ },
460
+ };
461
+ const written = requestActions(ledger, bind, resolvers, expiry);
462
+ api.summarize(() => ({ open: [...ledger.requests().values()].filter((state) => state.status === "open").length }));
463
+
464
+ api.action(askWith(bind, ledger));
465
+ api.action(written.answer);
466
+ api.action(written.cancel);
467
+ api.action(written.open);
468
+ api.action(written.list);
469
+ api.action(written.get);
470
+ api.action(written.resolve);
471
+ api.action(
472
+ action(requestFind, {
473
+ recovery: "repeat",
474
+ effect: "read",
475
+ world: "niwa",
476
+ async run(input) {
477
+ const journal = api.journal?.();
478
+ return { id: journal === undefined ? undefined : requestOfCause(journal, recordId(input.cause), input.question) };
479
+ },
480
+ }),
481
+ );
482
+
483
+ // A call that meets a rule that asks becomes a request to the owner, and waits here for its end.
484
+ const asks = new PendingAsks();
485
+ api.asker(async (asked, now) => {
486
+ // The record is named here, so the id is issued from it as the id of an ask of a call is.
487
+ const born = recordId(`ask:${crypto.randomUUID()}`);
488
+ const id = ledger.ids.issue(born);
489
+ const ended = asks.expect(id);
490
+ try {
491
+ await api.emit(RequestCreated, requestOf(id, asked, now, opts.askTimeoutMs ?? DEFAULT_ASK_TIMEOUT_MS), { id: born });
492
+ } catch {
493
+ asks.forget(id);
494
+ return "unanswered";
495
+ }
496
+ return ended;
497
+ });
498
+
499
+ // The requests whose time ran out end as expired: the one waiting is woken by it.
500
+ //
501
+ // One timer is set for the nearest deadline of the open requests. It is set again when the
502
+ // service starts and whenever a request is created or ends, so nothing polls. The id of the
503
+ // expiry is a function of the request alone, so a host that starts again after the deadline,
504
+ // or a timer that fires for a request that has just ended, writes the same record or none.
505
+ let rearm: (() => void) | undefined;
506
+ api.service((ctx) => {
507
+ let stopped = false;
508
+ let cancel: (() => void) | undefined;
509
+
510
+ const arm = (retry: boolean): void => {
511
+ cancel?.();
512
+ cancel = undefined;
513
+ if (stopped) return;
514
+ let nearest: number | undefined;
515
+ for (const state of ledger.requests().values()) {
516
+ const deadline = state.status === "open" ? state.created.deadline : undefined;
517
+ if (deadline !== undefined && (nearest === undefined || deadline < nearest)) nearest = deadline;
518
+ }
519
+ if (nearest === undefined) return;
520
+ const wait = retry ? EXPIRY_RETRY_MS : Math.min(Math.max(nearest - ctx.now(), 0), MAX_TIMER_MS);
521
+ // The clock of the host: a host whose clock is moved by hand expires what is due.
522
+ cancel = ctx.schedule(ctx.now() + wait, () => expire());
523
+ };
524
+
525
+ const expire = async (): Promise<void> => {
526
+ cancel = undefined;
527
+ const now = ctx.now();
528
+ let failed = false;
529
+ for (const state of ledger.requests().values()) {
530
+ if (state.status !== "open") continue;
531
+ const { deadline } = state.created;
532
+ if (deadline === undefined || deadline > now) continue;
533
+ if (stopped) return;
534
+ try {
535
+ await ctx.emit(RequestExpiredRecord, { id: state.created.id }, { id: expiryId(state.created.id) });
536
+ } catch (error) {
537
+ // The host is closing, or the write failed: the request stays open and is tried again.
538
+ if (stopped) return;
539
+ failed = true;
540
+ console.error(
541
+ `niwa: the request "${state.created.id}" could not be expired: ${
542
+ error instanceof Error ? error.message : String(error)
543
+ }`,
544
+ );
545
+ }
546
+ }
547
+ arm(failed);
548
+ };
549
+
550
+ rearm = () => arm(false);
551
+ clock = () => ctx.now();
552
+ // The requests that were already past their deadline when the host started end now.
553
+ arm(false);
554
+ return () => {
555
+ stopped = true;
556
+ rearm = undefined;
557
+ clock = undefined;
558
+ cancel?.();
559
+ cancel = undefined;
560
+ };
561
+ });
562
+
563
+ // A request that is created or ends changes the nearest deadline.
564
+ // The ones that end a question of a rule that asks let its call go on, or deny it.
565
+ // The decision of an access ask is the owner's only when the owner wrote the record: who did is
566
+ // the actor the host stamped on it, bound as any caller is, never the `by` the data claims.
567
+ api.on(RequestAnswered, (data, _step, written) => {
568
+ rearm?.();
569
+ const state = ledger.requests().get(data.id);
570
+ if (state?.status === "answered" && operatorAnswered(written, bind)) {
571
+ asks.end(data.id, outcomeOf(state.answer), bind(written.actor));
572
+ }
573
+ });
574
+ api.on(RequestCancelledRecord, (data, _step, record) => {
575
+ if (!providerWrote(record, "requests")) return;
576
+ rearm?.();
577
+ asks.end(data.id, "unanswered");
578
+ });
579
+ api.on(RequestExpiredRecord, (data, _step, record) => {
580
+ if (!providerWrote(record, "requests")) return;
581
+ rearm?.();
582
+ asks.end(data.id, "unanswered");
583
+ });
584
+
585
+ // A request reaches its resolvers as soon as it exists; a resolver that fails leaves it open.
586
+ // A resolver may take its time over one request: the others do not wait for it.
587
+ api.on(RequestCreated, { concurrency: Number.POSITIVE_INFINITY }, async (data, step, record) => {
588
+ if (!providerWrote(record, "requests")) return;
589
+ rearm?.();
590
+ if (data.answerPolicy === "owner-only" || resolvers.resolversFor(data.question).length === 0) return;
591
+ await step(written.resolve, { id: data.id });
592
+ });
593
+ });
594
+ }
595
+ export {
596
+ AskAnswered,
597
+ AskInput,
598
+ AskOpen,
599
+ AskOutput,
600
+ answeredBy,
601
+ REQUEST_ANSWER,
602
+ REQUEST_ASK,
603
+ REQUEST_CANCEL,
604
+ REQUEST_FIND,
605
+ REQUEST_GET,
606
+ REQUEST_LIST,
607
+ REQUEST_OPEN,
608
+ REQUEST_RESOLVE,
609
+ RequestEntity,
610
+ RequestStatus,
611
+ requestAnswer,
612
+ requestAsk,
613
+ requestCancel,
614
+ requestFind,
615
+ requestGet,
616
+ requestList,
617
+ requestOpen,
618
+ requestResolve,
619
+ } from "./actions.ts";
@@ -0,0 +1,50 @@
1
+ /**
2
+ * A question, declared: a name and the question itself. It is not
3
+ * a fact that happened: the same question is asked many times, each time with its own request.
4
+ * The format of the question is the one of the whole system (`QuestionSchema` in `@niwa-labs/core`).
5
+ */
6
+
7
+ import type { z } from "zod";
8
+
9
+ import { QuestionSchema } from "@niwa-labs/core";
10
+ import type { Question, QuestionInput } from "@niwa-labs/core";
11
+
12
+ import { QuestionName } from "./records.ts";
13
+ import type { RequestId } from "./records.ts";
14
+
15
+ /** A question with its name: what `request.ask` takes as `{ question, input }`. */
16
+ export interface DeclaredQuestion {
17
+ /** The name the journal, the resolvers and the decisions of the owner know the question by. */
18
+ readonly question: QuestionName;
19
+ /** The question, whole. */
20
+ readonly input: Question;
21
+ }
22
+
23
+ /** `question("release.branch", { kind: "choice", title, options })`: a question with a name. */
24
+ export function question(name: string, spec: QuestionInput): DeclaredQuestion {
25
+ return { question: QuestionName.parse(name), input: QuestionSchema.parse(spec) };
26
+ }
27
+
28
+ /**
29
+ * The checks of the asks this process waits on, by request.
30
+ *
31
+ * The question says what a form's value must look like in JSON Schema, which cannot say a
32
+ * refinement. While an ask waits here, the zod schema of its value is held and checks the value
33
+ * whole, so an answer that fails a refinement is refused when it is given and not written.
34
+ */
35
+ const held = new Map<RequestId, z.ZodType<unknown>>();
36
+
37
+ /** Hold the zod schema of the value of a form while its ask waits. */
38
+ export function holdAnswerCheck(request: RequestId, schema: z.ZodType<unknown>): void {
39
+ held.set(request, schema);
40
+ }
41
+
42
+ /** The ask stopped waiting: its check is not held any more. */
43
+ export function releaseAnswerCheck(request: RequestId): void {
44
+ held.delete(request);
45
+ }
46
+
47
+ /** The schema of the value of the form of a request whose ask waits in this process. */
48
+ export function heldAnswerCheckOf(request: RequestId): z.ZodType<unknown> | undefined {
49
+ return held.get(request);
50
+ }