@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/LICENSE +21 -0
- package/README.md +2 -2
- package/package.json +41 -4
- package/src/access-ask.ts +97 -0
- package/src/actions.ts +216 -0
- package/src/cockpit/actions.ts +68 -0
- package/src/cockpit/answer-form.tsx +103 -0
- package/src/cockpit/answers.ts +71 -0
- package/src/cockpit/history.tsx +149 -0
- package/src/cockpit/index.tsx +28 -0
- package/src/cockpit/page.tsx +115 -0
- package/src/entity.ts +58 -0
- package/src/index.ts +619 -0
- package/src/question.ts +50 -0
- package/src/records-entry.ts +47 -0
- package/src/records.ts +111 -0
- package/src/resolver.ts +74 -0
- package/src/state.ts +398 -0
- package/test/ask.test.ts +265 -0
- package/test/cockpit-actions.test.ts +36 -0
- package/test/cockpit-answers.test.ts +77 -0
- package/test/deadline.test.ts +40 -0
- package/test/ending.test.ts +223 -0
- package/test/entity.test.ts +18 -0
- package/test/ledger.test.ts +64 -0
- package/tsconfig.json +15 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The records entry of the requests module: what another plugin may import from it. The records,
|
|
3
|
+
* the action references and names, the question declaration and the pure helpers that read the
|
|
4
|
+
* state of a request; no factory and nothing that runs. The actions import the records, so this
|
|
5
|
+
* file sits above both and neither imports it.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export {
|
|
9
|
+
Deadline,
|
|
10
|
+
QuestionName,
|
|
11
|
+
REQUEST_TYPES,
|
|
12
|
+
RequestAnswered,
|
|
13
|
+
RequestCancelledRecord,
|
|
14
|
+
RequestCreated,
|
|
15
|
+
RequestExpiredRecord,
|
|
16
|
+
RequestId,
|
|
17
|
+
expiryId,
|
|
18
|
+
} from "./records.ts";
|
|
19
|
+
export {
|
|
20
|
+
AskAnswered,
|
|
21
|
+
AskInput,
|
|
22
|
+
AskOpen,
|
|
23
|
+
AskOutput,
|
|
24
|
+
answeredBy,
|
|
25
|
+
REQUEST_ANSWER,
|
|
26
|
+
REQUEST_ASK,
|
|
27
|
+
REQUEST_CANCEL,
|
|
28
|
+
REQUEST_FIND,
|
|
29
|
+
REQUEST_GET,
|
|
30
|
+
REQUEST_LIST,
|
|
31
|
+
REQUEST_OPEN,
|
|
32
|
+
REQUEST_RESOLVE,
|
|
33
|
+
RequestEntity,
|
|
34
|
+
RequestStatus,
|
|
35
|
+
requestAnswer,
|
|
36
|
+
requestAsk,
|
|
37
|
+
requestCancel,
|
|
38
|
+
requestFind,
|
|
39
|
+
requestGet,
|
|
40
|
+
requestList,
|
|
41
|
+
requestOpen,
|
|
42
|
+
requestResolve,
|
|
43
|
+
} from "./actions.ts";
|
|
44
|
+
export { question } from "./question.ts";
|
|
45
|
+
export type { DeclaredQuestion } from "./question.ts";
|
|
46
|
+
export { RequestCancelled, RequestExpired, fold, operatorAnswered } from "./state.ts";
|
|
47
|
+
export type { AnswerVerdict, RequestState } from "./state.ts";
|
package/src/records.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The records of the requests module: a request was created, and
|
|
3
|
+
* then it was answered, cancelled or expired. An open request is one with none of the three, so
|
|
4
|
+
* nothing is written for "still open".
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
|
|
9
|
+
import { AnswerSchema, QuestionSchema, idSchema, record, recordId, Address } from "@niwa-labs/core";
|
|
10
|
+
import type { Id, RecordId, Timestamp } from "@niwa-labs/core";
|
|
11
|
+
|
|
12
|
+
/** The id of a request, `req-3fa9c2`: niwa issues it, and the answer is bound to it. */
|
|
13
|
+
export const RequestId = idSchema("request");
|
|
14
|
+
export type RequestId = Id<"request">;
|
|
15
|
+
|
|
16
|
+
/** The name of a question: a key in the journal, not a sentence. */
|
|
17
|
+
export const QuestionName = z
|
|
18
|
+
.string()
|
|
19
|
+
.regex(/^\S+$/, "a question name is not empty and has no whitespace")
|
|
20
|
+
.brand<"QuestionName">();
|
|
21
|
+
export type QuestionName = z.infer<typeof QuestionName>;
|
|
22
|
+
|
|
23
|
+
/** The moment a request stops waiting, in milliseconds since the epoch. */
|
|
24
|
+
export const Deadline = z.custom<Timestamp>(
|
|
25
|
+
(value) => typeof value === "number" && Number.isInteger(value) && value >= 0,
|
|
26
|
+
{ message: "a deadline is a moment in milliseconds since the epoch" },
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* A request was created. The question is written whole, so a request is drawn and answered without
|
|
31
|
+
* the code that asked it; its name is the key resolvers and decisions know it by.
|
|
32
|
+
*/
|
|
33
|
+
export const RequestCreated = record(
|
|
34
|
+
"request.created",
|
|
35
|
+
z.object({
|
|
36
|
+
id: RequestId,
|
|
37
|
+
/** The one who may answer it. */
|
|
38
|
+
to: Address,
|
|
39
|
+
answerPolicy: z.literal("owner-only").optional(),
|
|
40
|
+
question: QuestionName,
|
|
41
|
+
/** What was asked: the question, whole. */
|
|
42
|
+
input: QuestionSchema,
|
|
43
|
+
/** Who asked, when the caller is bound to an address. */
|
|
44
|
+
from: Address.optional(),
|
|
45
|
+
/** When the request stops waiting. A request without one waits for ever. */
|
|
46
|
+
deadline: Deadline.optional(),
|
|
47
|
+
}),
|
|
48
|
+
{ providerOnly: "requests" },
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
/** A request was answered, by the address the caller is bound to. */
|
|
52
|
+
export const RequestAnswered = record(
|
|
53
|
+
"request.answered",
|
|
54
|
+
z.object({
|
|
55
|
+
id: RequestId,
|
|
56
|
+
answer: AnswerSchema,
|
|
57
|
+
by: Address.optional(),
|
|
58
|
+
/**
|
|
59
|
+
* How a resolver found the answer, when a resolver gave it.
|
|
60
|
+
*
|
|
61
|
+
* It is kept apart from the answer: the answer is what the asker parses against the schema
|
|
62
|
+
* of its question, and the way it was found is about the resolver, not about the answer.
|
|
63
|
+
*/
|
|
64
|
+
how: z.string().min(1).optional(),
|
|
65
|
+
/** The area the answer was found for. */
|
|
66
|
+
area: z.string().min(1).optional(),
|
|
67
|
+
/** What the answer came from: the id of a decision, or of a record. */
|
|
68
|
+
source: z.string().min(1).optional(),
|
|
69
|
+
}),
|
|
70
|
+
{ providerOnly: "requests" },
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
/** A request was cancelled: nobody chose to be answered any more. */
|
|
74
|
+
export const RequestCancelledRecord = record(
|
|
75
|
+
"request.cancelled",
|
|
76
|
+
z.object({
|
|
77
|
+
id: RequestId,
|
|
78
|
+
reason: z.string().optional(),
|
|
79
|
+
by: Address.optional(),
|
|
80
|
+
}),
|
|
81
|
+
{ providerOnly: "requests" },
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
/** A request expired: the time ran out, nobody chose anything. */
|
|
85
|
+
export const RequestExpiredRecord = record(
|
|
86
|
+
"request.expired",
|
|
87
|
+
z.object({
|
|
88
|
+
id: RequestId,
|
|
89
|
+
reason: z.string().optional(),
|
|
90
|
+
}),
|
|
91
|
+
{ providerOnly: "requests" },
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The id of the expiry of one request: `expired:${request}`.
|
|
96
|
+
*
|
|
97
|
+
* It is a function of the request alone, so the expiry written twice — a timer that ticked
|
|
98
|
+
* twice, a host that started again after the deadline — is the same record and not a second
|
|
99
|
+
* fact.
|
|
100
|
+
*/
|
|
101
|
+
export function expiryId(request: RequestId): RecordId {
|
|
102
|
+
return recordId(`expired:${request}`);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The record types this module declares. */
|
|
106
|
+
export const REQUEST_TYPES = [
|
|
107
|
+
RequestCreated,
|
|
108
|
+
RequestAnswered,
|
|
109
|
+
RequestCancelledRecord,
|
|
110
|
+
RequestExpiredRecord,
|
|
111
|
+
] as const;
|
package/src/resolver.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolvers: a plugin may answer a request before it reaches its addressee. A request for the
|
|
3
|
+
* owner reaches the resolvers first; if one already knows the answer the owner never sees the
|
|
4
|
+
* question.
|
|
5
|
+
*
|
|
6
|
+
* A resolver runs after the request is in the journal, so one that dies leaves the request
|
|
7
|
+
* open and the addressee still gets it. Its answer is written as a record by the module.
|
|
8
|
+
* A resolver may run again when its work is replayed after a crash, so it should not have
|
|
9
|
+
* effects of its own.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { Answer, Question, Address } from "@niwa-labs/core";
|
|
13
|
+
|
|
14
|
+
import type { DeclaredQuestion } from "./question.ts";
|
|
15
|
+
import type { QuestionName } from "./records.ts";
|
|
16
|
+
|
|
17
|
+
/** A request as a resolver sees it. The id stays with the module. */
|
|
18
|
+
export interface ResolverRequest {
|
|
19
|
+
readonly question: QuestionName;
|
|
20
|
+
readonly input: Question;
|
|
21
|
+
readonly to: Address;
|
|
22
|
+
readonly from?: Address;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* How a resolver's answer came, and what it rests on.
|
|
27
|
+
*
|
|
28
|
+
* It is told apart from the answer itself: the answer is what the asker reads against its
|
|
29
|
+
* question, and the way it was found is about the resolver, not about the answer.
|
|
30
|
+
*/
|
|
31
|
+
export interface ResolverInfo {
|
|
32
|
+
/** How the answer was found: "recalled", and the like. */
|
|
33
|
+
readonly how?: string;
|
|
34
|
+
/** The area the answer was found for. */
|
|
35
|
+
readonly area?: string;
|
|
36
|
+
/** What the answer came from: the id of a decision, or of a record. */
|
|
37
|
+
readonly source?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** An answer, or "no": the request goes on to its addressee. */
|
|
41
|
+
export type ResolverResult =
|
|
42
|
+
| { readonly answered: true; readonly answer: Answer; readonly info?: ResolverInfo }
|
|
43
|
+
| { readonly answered: false };
|
|
44
|
+
|
|
45
|
+
/** The code that may answer a question. */
|
|
46
|
+
export type Resolver = (request: ResolverRequest) => Promise<ResolverResult> | ResolverResult;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The resolvers of one host, by question name or "*" for every question. The resolver of the
|
|
50
|
+
* question has the first word; "*" is asked last.
|
|
51
|
+
*/
|
|
52
|
+
export class ResolverRegistry {
|
|
53
|
+
private readonly exact = new Map<string, Resolver>();
|
|
54
|
+
private fallback: Resolver | undefined;
|
|
55
|
+
|
|
56
|
+
/** One resolver per question: two would make the answer depend on the order of registering. */
|
|
57
|
+
register(question: DeclaredQuestion | "*", resolver: Resolver): void {
|
|
58
|
+
if (question === "*") {
|
|
59
|
+
if (this.fallback !== undefined) throw new Error("a resolver for every question is already registered");
|
|
60
|
+
this.fallback = resolver;
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (this.exact.has(question.question)) {
|
|
64
|
+
throw new Error(`a resolver for the question "${question.question}" is already registered`);
|
|
65
|
+
}
|
|
66
|
+
this.exact.set(question.question, resolver);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The resolvers to try, in order. */
|
|
70
|
+
resolversFor(question: QuestionName): Resolver[] {
|
|
71
|
+
const exact = this.exact.get(question);
|
|
72
|
+
return [...(exact === undefined ? [] : [exact]), ...(this.fallback === undefined ? [] : [this.fallback])];
|
|
73
|
+
}
|
|
74
|
+
}
|
package/src/state.ts
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The state of a request, folded from the journal, and the rules about who may do what to it.
|
|
3
|
+
* The records are the truth; what is held in memory is a reading of them. The first end of a request stands; a
|
|
4
|
+
* later answer, cancel or expiry of the same request is passed over.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
|
|
9
|
+
import { CORE_TYPES, CatchableError, IdIndex, UnknownId, answerMismatch, providerWrote, seq, stableJson } from "@niwa-labs/core";
|
|
10
|
+
import type { CallerBinding } from "@niwa-labs/plugin";
|
|
11
|
+
import type { Answer, IssuedId, JournalReader, RecordId, RecordTypeName, Seq, StoredRecord, Address } from "@niwa-labs/core";
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
RequestAnswered,
|
|
15
|
+
RequestCancelledRecord,
|
|
16
|
+
RequestCreated,
|
|
17
|
+
RequestExpiredRecord,
|
|
18
|
+
} from "./records.ts";
|
|
19
|
+
import { RequestId } from "./records.ts";
|
|
20
|
+
import { heldAnswerCheckOf } from "./question.ts";
|
|
21
|
+
|
|
22
|
+
/** What is read from a record: its type and its data. */
|
|
23
|
+
export type Fact = Pick<StoredRecord, "type" | "data"> & Partial<Pick<StoredRecord, "actor">>;
|
|
24
|
+
|
|
25
|
+
/** A request as it was created. */
|
|
26
|
+
export type Created = z.infer<typeof RequestCreated.schema>;
|
|
27
|
+
|
|
28
|
+
/** What a request is now. An end says who ended it, when the caller was bound to an address. */
|
|
29
|
+
export type RequestState =
|
|
30
|
+
| { readonly status: "open"; readonly created: Created }
|
|
31
|
+
| { readonly status: "answered"; readonly created: Created; readonly answer: Answer; readonly by?: Address }
|
|
32
|
+
| { readonly status: "cancelled"; readonly created: Created; readonly by?: Address }
|
|
33
|
+
| { readonly status: "expired"; readonly created: Created };
|
|
34
|
+
|
|
35
|
+
/** A refusal: a command that breaks a rule. */
|
|
36
|
+
export class RequestRefusal extends Error {
|
|
37
|
+
override name = "RequestRefusal";
|
|
38
|
+
readonly code: string;
|
|
39
|
+
|
|
40
|
+
constructor(code: string, message: string) {
|
|
41
|
+
super(message);
|
|
42
|
+
this.code = code;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The request was cancelled: nobody chose to answer it any more.
|
|
48
|
+
*
|
|
49
|
+
* The one waiting catches it and decides what happens next; the wait ends, and the request is
|
|
50
|
+
* not open any more.
|
|
51
|
+
*/
|
|
52
|
+
export class RequestCancelled extends CatchableError {
|
|
53
|
+
override name = "RequestCancelled";
|
|
54
|
+
override readonly code = "RequestCancelled";
|
|
55
|
+
/** The request that was cancelled. */
|
|
56
|
+
readonly request: RequestId;
|
|
57
|
+
|
|
58
|
+
constructor(request: RequestId, message = `the request "${request}" was cancelled`) {
|
|
59
|
+
super(message);
|
|
60
|
+
this.request = request;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The request expired: the time ran out and nobody answered.
|
|
66
|
+
*
|
|
67
|
+
* The one waiting catches it and decides what happens next; the wait ends, and the request is
|
|
68
|
+
* not open any more.
|
|
69
|
+
*/
|
|
70
|
+
export class RequestExpired extends CatchableError {
|
|
71
|
+
override name = "RequestExpired";
|
|
72
|
+
override readonly code = "RequestExpired";
|
|
73
|
+
/** The request that expired. */
|
|
74
|
+
readonly request: RequestId;
|
|
75
|
+
|
|
76
|
+
constructor(request: RequestId, message = `the request "${request}" expired`) {
|
|
77
|
+
super(message);
|
|
78
|
+
this.request = request;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The state of every request, in the order the facts happened. */
|
|
83
|
+
export function fold(facts: readonly Fact[], bind?: CallerBinding): Map<RequestId, RequestState> {
|
|
84
|
+
const states = new Map<RequestId, RequestState>();
|
|
85
|
+
for (const fact of facts) applyFact(states, fact, bind);
|
|
86
|
+
return states;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Whether the authenticated writer can speak for the owner. */
|
|
90
|
+
export function operatorAnswered(fact: Fact, bind?: CallerBinding): boolean {
|
|
91
|
+
const who = fact.actor;
|
|
92
|
+
if (who === undefined || !providerWrote({ actor: who }, "requests") || who.kind === "host") return false;
|
|
93
|
+
if (who.kind === "client") return who.principal?.kind === "owner";
|
|
94
|
+
// A handler is installed host code. Its binding certifies the owner on a running host;
|
|
95
|
+
// offline readers have its host-stamped actor and the binding recorded by the action.
|
|
96
|
+
return bind === undefined ? RequestAnswered.schema.safeParse(fact.data).data?.by?.kind === "owner" : bind(who)?.kind === "owner";
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Apply a birth or the first accepted end of an open request. */
|
|
100
|
+
function applyFact(states: Map<RequestId, RequestState>, fact: Fact, bind?: CallerBinding): Created | undefined {
|
|
101
|
+
if (!fact.actor || !providerWrote({ actor: fact.actor }, "requests")) return undefined;
|
|
102
|
+
if (fact.type === RequestCreated.name) {
|
|
103
|
+
const created = RequestCreated.schema.safeParse(fact.data);
|
|
104
|
+
if (!created.success || states.has(created.data.id)) return undefined;
|
|
105
|
+
states.set(created.data.id, { status: "open", created: created.data });
|
|
106
|
+
return created.data;
|
|
107
|
+
}
|
|
108
|
+
const end = endOf(fact);
|
|
109
|
+
if (end === undefined) return undefined;
|
|
110
|
+
const state = states.get(end.id);
|
|
111
|
+
if (state === undefined || state.status !== "open") return undefined;
|
|
112
|
+
if (state.created.answerPolicy === "owner-only" && fact.type === RequestAnswered.name && !operatorAnswered(fact, bind)) return undefined;
|
|
113
|
+
states.set(end.id, end.close(state.created));
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The requests and the paused invocations as of the last record read, kept between calls.
|
|
119
|
+
*
|
|
120
|
+
* The journal is the truth; this is a reading of it that goes on from where it stopped, so an
|
|
121
|
+
* answer does not fold the whole history again. A journal that is not the one it read starts it
|
|
122
|
+
* over.
|
|
123
|
+
*/
|
|
124
|
+
export class RequestLedger {
|
|
125
|
+
private readonly states = new Map<RequestId, RequestState>();
|
|
126
|
+
private readonly latest = new Map<string, z.infer<typeof InvocationState>>();
|
|
127
|
+
/** Each request id with the journal record it was born in: what a replayed ask is found by. */
|
|
128
|
+
private readonly issued = new Map<RequestId, IssuedId>();
|
|
129
|
+
private cursor: Seq = seq(0);
|
|
130
|
+
private source: JournalReader | undefined;
|
|
131
|
+
/** The ids of the requests: issues a new one, and resolves what a person typed. */
|
|
132
|
+
readonly ids: IdIndex<"request">;
|
|
133
|
+
|
|
134
|
+
constructor(
|
|
135
|
+
private readonly types: RecordTypeName[],
|
|
136
|
+
private readonly reader: () => JournalReader | undefined,
|
|
137
|
+
private readonly bind?: CallerBinding,
|
|
138
|
+
) {
|
|
139
|
+
this.ids = new IdIndex("request", () => {
|
|
140
|
+
this.catchUp();
|
|
141
|
+
return [...this.issued.values()];
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** A record of the journal by its id, when the host is serving and holds it. */
|
|
146
|
+
recordOf(id: RecordId): StoredRecord | undefined {
|
|
147
|
+
return this.reader()?.get(id);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The state of every request, up to the last record of the journal. */
|
|
151
|
+
requests(): ReadonlyMap<RequestId, RequestState> {
|
|
152
|
+
this.catchUp();
|
|
153
|
+
return this.states;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The request a command names: an id, a unique prefix or suffix of one, or the run whose one
|
|
158
|
+
* open ask it is. A whole id of an existing request names that one before any short form is tried. A text that names no request but is an id is said as an id, so a request the
|
|
159
|
+
* caller may not act on is refused for that and not for being unknown.
|
|
160
|
+
*/
|
|
161
|
+
named(input: { id?: string | undefined; run?: string | undefined }, sees: (request: Created) => boolean = () => true): RequestId {
|
|
162
|
+
if (input.id !== undefined) {
|
|
163
|
+
// The whole id of a request names it, open or ended: a longer id that starts with the same text
|
|
164
|
+
// is another request. Whether the caller may act on it is for the command to decide.
|
|
165
|
+
const whole = RequestId.safeParse(input.id);
|
|
166
|
+
if (whole.success && this.requests().has(whole.data)) return whole.data;
|
|
167
|
+
}
|
|
168
|
+
// Only the requests the caller may act on are candidates: a short text never names, or lists in a refusal, another's.
|
|
169
|
+
const states = [...this.requests().values()].filter((state) => sees(state.created));
|
|
170
|
+
if (input.id !== undefined) {
|
|
171
|
+
// What is open is looked at first: a text that names one open request is that one, though it also ends an old one.
|
|
172
|
+
const open = new Set(states.filter((state) => state.status === "open").map((state) => state.created.id));
|
|
173
|
+
const seen = new Set(states.map((state) => state.created.id));
|
|
174
|
+
const named = this.ids.resolve(input.id, (id) => open.has(RequestId.parse(id))) ?? this.ids.resolve(input.id, (id) => seen.has(RequestId.parse(id)));
|
|
175
|
+
if (named !== undefined) return named;
|
|
176
|
+
const exact = RequestId.safeParse(input.id);
|
|
177
|
+
if (exact.success) return exact.data;
|
|
178
|
+
throw new RequestRefusal("unknown", `the request "${input.id}" does not exist`);
|
|
179
|
+
}
|
|
180
|
+
const run = input.run ?? "";
|
|
181
|
+
const asks = states.filter((state) => state.status === "open" && state.created.from?.kind === "client" && state.created.from.id.startsWith(`run:${run}`)).map((state) => state.created.id);
|
|
182
|
+
const [only, ...more] = asks;
|
|
183
|
+
if (only === undefined) throw new RequestRefusal("no-open-ask", `the run "${run}" has no open ask`);
|
|
184
|
+
if (more.length > 0) throw new RequestRefusal("several-asks", `the run "${run}" has ${String(asks.length)} open asks: ${asks.join(", ")}: name one`);
|
|
185
|
+
return only;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** The request a text names: an id, a unique prefix or suffix of one. A text that names none is `UnknownId`. */
|
|
189
|
+
get(text: string): RequestState {
|
|
190
|
+
const state = this.requests().get(this.ids.require(text));
|
|
191
|
+
if (state === undefined) throw new UnknownId(text, "request");
|
|
192
|
+
return state;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The invocations whose latest state is "paused", up to the last record of the journal. */
|
|
196
|
+
paused(): Paused[] {
|
|
197
|
+
this.catchUp();
|
|
198
|
+
return pausedIn(this.latest.values());
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private catchUp(): void {
|
|
202
|
+
const journal = this.reader();
|
|
203
|
+
if (journal === undefined) return;
|
|
204
|
+
if (journal !== this.source) {
|
|
205
|
+
this.source = journal;
|
|
206
|
+
this.states.clear();
|
|
207
|
+
this.issued.clear();
|
|
208
|
+
this.latest.clear();
|
|
209
|
+
this.cursor = seq(0);
|
|
210
|
+
}
|
|
211
|
+
for (const record of journal.since(this.cursor, [...this.types, CORE_TYPES.invocationState])) {
|
|
212
|
+
this.cursor = record.seq;
|
|
213
|
+
if (record.type === CORE_TYPES.invocationState) {
|
|
214
|
+
const data = InvocationState.safeParse(record.data);
|
|
215
|
+
if (data.success) this.latest.set(data.data.invocation, data.data);
|
|
216
|
+
} else {
|
|
217
|
+
const created = applyFact(this.states, record, this.bind);
|
|
218
|
+
if (created !== undefined) this.issued.set(created.id, { id: created.id, seed: record.id });
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** The request a fact ends, and the state it leaves the request in. */
|
|
225
|
+
function endOf(
|
|
226
|
+
fact: Fact,
|
|
227
|
+
): { id: RequestId; close: (created: Created) => RequestState } | undefined {
|
|
228
|
+
if (fact.type === RequestAnswered.name) {
|
|
229
|
+
const data = RequestAnswered.schema.safeParse(fact.data);
|
|
230
|
+
if (!data.success) return undefined;
|
|
231
|
+
const { id, answer, by } = data.data;
|
|
232
|
+
return { id, close: (created) => ({ status: "answered", created, answer, ...(by === undefined ? {} : { by }) }) };
|
|
233
|
+
}
|
|
234
|
+
if (fact.type === RequestCancelledRecord.name) {
|
|
235
|
+
const data = RequestCancelledRecord.schema.safeParse(fact.data);
|
|
236
|
+
if (!data.success) return undefined;
|
|
237
|
+
const { id, by } = data.data;
|
|
238
|
+
return { id, close: (created) => ({ status: "cancelled", created, ...(by === undefined ? {} : { by }) }) };
|
|
239
|
+
}
|
|
240
|
+
if (fact.type === RequestExpiredRecord.name) {
|
|
241
|
+
const data = RequestExpiredRecord.schema.safeParse(fact.data);
|
|
242
|
+
if (!data.success) return undefined;
|
|
243
|
+
return { id: data.data.id, close: (created) => ({ status: "expired", created }) };
|
|
244
|
+
}
|
|
245
|
+
return undefined;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* The request of this question that a record caused: what a handler woken by the record asked. How a
|
|
250
|
+
* handler finds its own request again: a caller does not choose the id of one.
|
|
251
|
+
*/
|
|
252
|
+
export function requestOfCause(journal: JournalReader, cause: RecordId, question: string): RequestId | undefined {
|
|
253
|
+
for (const stored of journal.find({ type: RequestCreated.name })) {
|
|
254
|
+
if (stored.cause !== cause) continue;
|
|
255
|
+
const created = RequestCreated.schema.safeParse(stored.data);
|
|
256
|
+
if (created.success && created.data.question === question) return created.data.id;
|
|
257
|
+
}
|
|
258
|
+
return undefined;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Are two addresses the same one? They are when they say the same thing, kind included. */
|
|
262
|
+
export function sameAddress(one: Address, other: Address): boolean {
|
|
263
|
+
return stableJson(one) === stableJson(other);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* What an answer does to the state of a request.
|
|
268
|
+
*
|
|
269
|
+
* - "write": the answer is written and the request is answered by it.
|
|
270
|
+
* - "repeat": the same address gave the same answer to a request that is already answered by
|
|
271
|
+
* it; nothing is written and the answer stands.
|
|
272
|
+
* - "late": the request was cancelled or expired before the answer came; nothing is written and
|
|
273
|
+
* the answerer is told why, not refused.
|
|
274
|
+
*/
|
|
275
|
+
export type AnswerVerdict =
|
|
276
|
+
| { readonly kind: "write" }
|
|
277
|
+
| { readonly kind: "repeat" }
|
|
278
|
+
| { readonly kind: "late"; readonly reason: "cancelled" | "expired" };
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* What an answer does. Only the addressee answers an open request, once; the same address
|
|
282
|
+
* giving the same answer again changes nothing ("repeat"), and anything else is refused.
|
|
283
|
+
*
|
|
284
|
+
* An answer to a request that was cancelled or expired does nothing ("late"): the request is
|
|
285
|
+
* over, and the answerer is told so instead of being refused.
|
|
286
|
+
*
|
|
287
|
+
* The answer is checked against the schema of the question when it comes. An answer that does
|
|
288
|
+
* not pass it is refused, and nothing is written: the request stays open, and a right answer
|
|
289
|
+
* may still come.
|
|
290
|
+
*/
|
|
291
|
+
export function decideAnswer(
|
|
292
|
+
id: RequestId,
|
|
293
|
+
state: RequestState | undefined,
|
|
294
|
+
by: Address | undefined,
|
|
295
|
+
answer: Answer,
|
|
296
|
+
): AnswerVerdict {
|
|
297
|
+
if (by === undefined) {
|
|
298
|
+
throw new RequestRefusal("unbound", "the caller is not bound to an address, so it cannot answer");
|
|
299
|
+
}
|
|
300
|
+
if (
|
|
301
|
+
state?.status === "answered" &&
|
|
302
|
+
state.by !== undefined &&
|
|
303
|
+
sameAddress(by, state.by) &&
|
|
304
|
+
stableJson(answer) === stableJson(state.answer)
|
|
305
|
+
) {
|
|
306
|
+
return { kind: "repeat" };
|
|
307
|
+
}
|
|
308
|
+
if (state?.status === "cancelled") return { kind: "late", reason: "cancelled" };
|
|
309
|
+
if (state?.status === "expired") return { kind: "late", reason: "expired" };
|
|
310
|
+
const open = requireOpen(id, state);
|
|
311
|
+
if (!sameAddress(by, open.to)) {
|
|
312
|
+
throw new RequestRefusal("not-addressee", `only the addressee of the request "${id}" may answer it`);
|
|
313
|
+
}
|
|
314
|
+
checkAnswer(open, answer);
|
|
315
|
+
return { kind: "write" };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* The answer must fit the question of the request it answers: its kind says which answers there
|
|
320
|
+
* are, and its options and its schema say which of them. An answer that cancels is no answer:
|
|
321
|
+
* cancelling is what `request.cancel` is for.
|
|
322
|
+
*
|
|
323
|
+
* While the ask waits in this process, the zod schema of the value of its form is held and checks
|
|
324
|
+
* the value whole, refinements included, which JSON Schema cannot say.
|
|
325
|
+
*/
|
|
326
|
+
export function checkAnswer(request: Pick<Created, "id" | "question" | "input">, answer: Answer): void {
|
|
327
|
+
const mismatch = answerMismatch(request.input, answer);
|
|
328
|
+
if (mismatch !== undefined) {
|
|
329
|
+
throw new RequestRefusal("bad-answer", `the answer to "${request.question}" is not valid: ${mismatch}`);
|
|
330
|
+
}
|
|
331
|
+
const held = heldAnswerCheckOf(request.id);
|
|
332
|
+
if (held === undefined || !("form" in answer)) return;
|
|
333
|
+
const checked = held.safeParse(answer.form);
|
|
334
|
+
if (!checked.success) {
|
|
335
|
+
throw new RequestRefusal("bad-answer", `the answer to "${request.question}" is not valid: ${checked.error.message}`);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* What a cancel does. Only the asker or the addressee cancels an open request; the same
|
|
341
|
+
* address cancelling again changes nothing ("repeat").
|
|
342
|
+
*/
|
|
343
|
+
export function decideCancel(
|
|
344
|
+
id: RequestId,
|
|
345
|
+
state: RequestState | undefined,
|
|
346
|
+
by: Address | undefined,
|
|
347
|
+
): "write" | "repeat" {
|
|
348
|
+
if (by === undefined) {
|
|
349
|
+
throw new RequestRefusal("unbound", "the caller is not bound to an address, so it cannot cancel");
|
|
350
|
+
}
|
|
351
|
+
if (state?.status === "cancelled" && state.by !== undefined && sameAddress(by, state.by)) {
|
|
352
|
+
return "repeat";
|
|
353
|
+
}
|
|
354
|
+
const open = requireOpen(id, state);
|
|
355
|
+
const parties = [open.to, ...(open.from === undefined ? [] : [open.from])];
|
|
356
|
+
if (!parties.some((party) => sameAddress(by, party))) {
|
|
357
|
+
throw new RequestRefusal("not-party", `only the asker or the addressee of the request "${id}" may cancel it`);
|
|
358
|
+
}
|
|
359
|
+
return "write";
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** The request, when it is open. */
|
|
363
|
+
function requireOpen(id: RequestId, state: RequestState | undefined): Created {
|
|
364
|
+
if (state === undefined) throw new RequestRefusal("unknown", `the request "${id}" does not exist`);
|
|
365
|
+
if (state.status !== "open") {
|
|
366
|
+
throw new RequestRefusal(state.status, `the request "${id}" is already ${state.status}`);
|
|
367
|
+
}
|
|
368
|
+
return state.created;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** The data of a state change of an invocation, as far as the list of open work needs it. */
|
|
372
|
+
const InvocationState = z.object({
|
|
373
|
+
invocation: z.string().min(1),
|
|
374
|
+
state: z.string(),
|
|
375
|
+
key: z.string().optional(),
|
|
376
|
+
reason: z.string().optional(),
|
|
377
|
+
choices: z.array(z.string()).optional(),
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
/** An invocation that is paused: it waits for a decision between typed choices. */
|
|
381
|
+
export interface Paused {
|
|
382
|
+
readonly invocation: string;
|
|
383
|
+
readonly choices: readonly string[];
|
|
384
|
+
readonly key?: string;
|
|
385
|
+
readonly reason?: string;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** The invocations among these whose state is "paused". */
|
|
389
|
+
function pausedIn(latest: Iterable<z.infer<typeof InvocationState>>): Paused[] {
|
|
390
|
+
return [...latest]
|
|
391
|
+
.filter((data) => data.state === "paused")
|
|
392
|
+
.map((data) => ({
|
|
393
|
+
invocation: data.invocation,
|
|
394
|
+
choices: data.choices ?? [],
|
|
395
|
+
...(data.key === undefined ? {} : { key: data.key }),
|
|
396
|
+
...(data.reason === undefined ? {} : { reason: data.reason }),
|
|
397
|
+
}));
|
|
398
|
+
}
|