@operad-io/engine 0.3.1 → 0.4.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/package.json +1 -1
- package/src/http/server.ts +16 -1
- package/src/loop/code-watch.ts +6 -1
- package/src/plugin/context.ts +1 -0
- package/src/plugin/harness.ts +14 -0
- package/src/plugin/home-flows.ts +124 -0
- package/src/plugin/in-flight.ts +50 -0
- package/src/plugin/load.ts +10 -0
- package/src/plugin/registry.ts +60 -2
- package/src/plugin/sqlite-store.ts +7 -0
- package/src/plugin/store.ts +4 -0
- package/src/plugin/types.ts +11 -0
- package/src/plugin/validate.ts +9 -0
- package/src/views/presentation.ts +30 -3
package/package.json
CHANGED
package/src/http/server.ts
CHANGED
|
@@ -31,6 +31,8 @@ import {
|
|
|
31
31
|
type HttpToken,
|
|
32
32
|
} from "./token.ts";
|
|
33
33
|
import { isRecord } from "../util.ts";
|
|
34
|
+
import { StoreClosedError } from "../log/errors.ts";
|
|
35
|
+
import { InFlight } from "../plugin/in-flight.ts";
|
|
34
36
|
|
|
35
37
|
/** How long an idle event stream waits before a keep-alive comment. */
|
|
36
38
|
export const DEFAULT_KEEP_ALIVE_MS = 15_000;
|
|
@@ -1089,6 +1091,11 @@ function createHandler(
|
|
|
1089
1091
|
);
|
|
1090
1092
|
}
|
|
1091
1093
|
if (error instanceof ViewError) return viewErrorResponse(error);
|
|
1094
|
+
// A request that outlives its store is over because the server is
|
|
1095
|
+
// going away: answer it, and do not log it as a failure.
|
|
1096
|
+
if (error instanceof StoreClosedError) {
|
|
1097
|
+
return errorResponse(503, "unavailable", "the server is stopping");
|
|
1098
|
+
}
|
|
1092
1099
|
onLog(`http: ${messageOf(error)}`);
|
|
1093
1100
|
return errorResponse(500, "internal", "the request failed");
|
|
1094
1101
|
}
|
|
@@ -1122,7 +1129,14 @@ export async function startHttpServer(
|
|
|
1122
1129
|
void uploads.sweep().catch(() => undefined);
|
|
1123
1130
|
}, options.uploadSweepMs ?? DEFAULT_UPLOAD_SWEEP_MS);
|
|
1124
1131
|
(uploadSweep as { unref?: () => void }).unref?.();
|
|
1125
|
-
const
|
|
1132
|
+
const handle = createHandler(options, uploads, hub, streams, onLog);
|
|
1133
|
+
// Requests in flight are waited for (bounded) by `stop`, so the store they
|
|
1134
|
+
// read is not closed under them.
|
|
1135
|
+
const requests = new InFlight();
|
|
1136
|
+
const handler = async (request: Request): Promise<Response> =>
|
|
1137
|
+
requests.draining
|
|
1138
|
+
? errorResponse(503, "unavailable", "the server is stopping")
|
|
1139
|
+
: await requests.track(() => handle(request));
|
|
1126
1140
|
const servers: { readonly address: string; readonly server: ReturnType<typeof Bun.serve> }[] = [];
|
|
1127
1141
|
const listener = options.listener ?? Bun.serve;
|
|
1128
1142
|
const stopTimeoutMs = options.stopTimeoutMs ?? DEFAULT_STOP_TIMEOUT_MS;
|
|
@@ -1208,6 +1222,7 @@ export async function startHttpServer(
|
|
|
1208
1222
|
hub.stop();
|
|
1209
1223
|
streams.closeAll();
|
|
1210
1224
|
const unreleased = await stopAll();
|
|
1225
|
+
await requests.drain(stopTimeoutMs);
|
|
1211
1226
|
if (unreleased.length > 0) throw new HttpStopError(unreleased);
|
|
1212
1227
|
},
|
|
1213
1228
|
};
|
package/src/loop/code-watch.ts
CHANGED
|
@@ -242,7 +242,12 @@ export function codeRoots(options: {
|
|
|
242
242
|
readonly extra?: readonly CodeRoot[] | undefined;
|
|
243
243
|
readonly plugins: readonly { readonly name: string; readonly module: string }[];
|
|
244
244
|
}): CodeRoot[] {
|
|
245
|
-
|
|
245
|
+
// The person's own flows are code every process loads.
|
|
246
|
+
const roots: CodeRoot[] = [
|
|
247
|
+
ENGINE_CODE_ROOT,
|
|
248
|
+
...(options.extra ?? []),
|
|
249
|
+
{ label: "home flows", path: join(options.home, "flows") },
|
|
250
|
+
];
|
|
246
251
|
const seen = new Set(roots.map((root) => root.path));
|
|
247
252
|
const add = (label: string, path: string): void => {
|
|
248
253
|
if (seen.has(path)) return;
|
package/src/plugin/context.ts
CHANGED
|
@@ -213,6 +213,7 @@ export async function openHome(options: OpenHomeOptions): Promise<OpenedHome> {
|
|
|
213
213
|
clock,
|
|
214
214
|
kernelVerbs: options.kernelVerbs ?? KERNEL_VERBS,
|
|
215
215
|
onLog: report,
|
|
216
|
+
onHomeFlowProblem: onLog,
|
|
216
217
|
onAnswer: answer,
|
|
217
218
|
onEvent: event,
|
|
218
219
|
onCancelRun: cancel,
|
package/src/plugin/harness.ts
CHANGED
|
@@ -45,6 +45,17 @@ export interface AgentTimings {
|
|
|
45
45
|
readonly totalMs: number;
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
/** What a compaction of a harness session did. */
|
|
49
|
+
export interface AgentCompaction {
|
|
50
|
+
readonly reason: "threshold" | "manual";
|
|
51
|
+
/** The context before it, in tokens. */
|
|
52
|
+
readonly before: number;
|
|
53
|
+
/** The estimated context after it, when the harness could tell. */
|
|
54
|
+
readonly after?: number | undefined;
|
|
55
|
+
/** Whether a silent memory turn ran before it. */
|
|
56
|
+
readonly flushed: boolean;
|
|
57
|
+
}
|
|
58
|
+
|
|
48
59
|
/** What every harness `agent` step records as its facts. */
|
|
49
60
|
export interface AgentResultData {
|
|
50
61
|
readonly exitCode: number | null;
|
|
@@ -70,6 +81,9 @@ export interface AgentResultData {
|
|
|
70
81
|
readonly window?: number | undefined;
|
|
71
82
|
}
|
|
72
83
|
| undefined;
|
|
84
|
+
/** True when the run compacted the harness session; `compaction` says how. */
|
|
85
|
+
readonly compacted?: true | undefined;
|
|
86
|
+
readonly compaction?: AgentCompaction | undefined;
|
|
73
87
|
/** Set on `failed`: which limit or condition ended the run. */
|
|
74
88
|
readonly reason?: string | undefined;
|
|
75
89
|
readonly message?: string | undefined;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flows a person keeps in the operad home: each `<home>/flows/<name>.flow.ts`
|
|
3
|
+
* whose default export is a `defineFlow` value is one flow named
|
|
4
|
+
* `home:<name>`. It is loaded and validated like a plugin's flow, against the
|
|
5
|
+
* steps of every loaded plugin. A file that does not load is refused with its
|
|
6
|
+
* reason and the others still load.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { lstatSync, mkdirSync, readdirSync, realpathSync, rmSync, symlinkSync } from "node:fs";
|
|
10
|
+
import { basename, join } from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { loadFlow } from "../flow/load.ts";
|
|
13
|
+
import type { FlowDefinition, StepTypeRegistry } from "../flow/types.ts";
|
|
14
|
+
import { messageOf } from "./errors.ts";
|
|
15
|
+
|
|
16
|
+
/** The prefix every flow of the home carries. */
|
|
17
|
+
export const HOME_FLOW_PREFIX = "home:";
|
|
18
|
+
|
|
19
|
+
/** What the owner of a home flow is called in `flows()`. */
|
|
20
|
+
export const HOME_FLOW_OWNER = "home";
|
|
21
|
+
|
|
22
|
+
const SUFFIX = ".flow.ts";
|
|
23
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
24
|
+
|
|
25
|
+
/** One flow file that loaded. */
|
|
26
|
+
export interface HomeFlow {
|
|
27
|
+
readonly file: string;
|
|
28
|
+
readonly flow: FlowDefinition;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** One flow file that was refused, with the reason. The message names the file. */
|
|
32
|
+
export interface HomeFlowRefusal {
|
|
33
|
+
readonly file: string;
|
|
34
|
+
readonly message: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface HomeFlows {
|
|
38
|
+
readonly flows: readonly HomeFlow[];
|
|
39
|
+
readonly refused: readonly HomeFlowRefusal[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The package directory of the running engine. */
|
|
43
|
+
const ENGINE_DIRECTORY = realpathSync(fileURLToPath(new URL("../../", import.meta.url)));
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Makes `import { defineFlow } from "@operad-io/engine"` work in a flow file of
|
|
47
|
+
* the home. The home is outside any package, so plain resolution from the file
|
|
48
|
+
* finds nothing (or, with auto-install, a copy of another version). The home
|
|
49
|
+
* gets `node_modules/@operad-io/engine`, a link to the engine the running
|
|
50
|
+
* operad is made of, so a file imports the same code operad runs, from a
|
|
51
|
+
* global install or from a source checkout alike. A link that points elsewhere
|
|
52
|
+
* (the install moved or was upgraded) is renewed; a real directory the person
|
|
53
|
+
* put there is left alone. A process that starts at the same time and wins the
|
|
54
|
+
* race to write the link leaves the same link, so the loser has nothing to do.
|
|
55
|
+
*/
|
|
56
|
+
export function linkEngineIntoHome(home: string): void {
|
|
57
|
+
const scope = join(home, "node_modules", "@operad-io");
|
|
58
|
+
const link = join(scope, "engine");
|
|
59
|
+
try {
|
|
60
|
+
if (!lstatSync(link).isSymbolicLink() || realpathSync(link) === ENGINE_DIRECTORY) return;
|
|
61
|
+
} catch {
|
|
62
|
+
// Absent or dangling: written below.
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
mkdirSync(scope, { recursive: true });
|
|
66
|
+
rmSync(link, { force: true });
|
|
67
|
+
symlinkSync(ENGINE_DIRECTORY, link, "dir");
|
|
68
|
+
} catch {
|
|
69
|
+
// A home that cannot be written: the import then fails, and the refusal names the file.
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The directory of the home's flows. */
|
|
74
|
+
export function homeFlowsDirectory(home: string): string {
|
|
75
|
+
return join(home, "flows");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Reads every flow file of the home. A missing directory holds no flows. */
|
|
79
|
+
export async function loadHomeFlows(
|
|
80
|
+
home: string,
|
|
81
|
+
registry: StepTypeRegistry,
|
|
82
|
+
taken: (name: string) => boolean = () => false,
|
|
83
|
+
): Promise<HomeFlows> {
|
|
84
|
+
const directory = homeFlowsDirectory(home);
|
|
85
|
+
let names: string[];
|
|
86
|
+
try {
|
|
87
|
+
names = readdirSync(directory)
|
|
88
|
+
.filter((name) => name.endsWith(SUFFIX))
|
|
89
|
+
.sort();
|
|
90
|
+
} catch {
|
|
91
|
+
return { flows: [], refused: [] };
|
|
92
|
+
}
|
|
93
|
+
linkEngineIntoHome(home);
|
|
94
|
+
const flows: HomeFlow[] = [];
|
|
95
|
+
const refused: HomeFlowRefusal[] = [];
|
|
96
|
+
for (const entry of names) {
|
|
97
|
+
const path = join(directory, entry);
|
|
98
|
+
const file = basename(path);
|
|
99
|
+
const short = entry.slice(0, -SUFFIX.length);
|
|
100
|
+
const name = `${HOME_FLOW_PREFIX}${short}`;
|
|
101
|
+
if (!NAME.test(short)) {
|
|
102
|
+
refused.push({
|
|
103
|
+
file,
|
|
104
|
+
message: `home flow file "${path}": the name "${short}" may use letters, digits, ".", "_" and "-" and must start with a letter or digit`,
|
|
105
|
+
});
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (taken(name)) {
|
|
109
|
+
refused.push({ file, message: `home flow file "${path}": flow "${name}" is already declared` });
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
const loaded = await loadFlow(path, registry);
|
|
114
|
+
flows.push({ file, flow: { ...loaded, name } });
|
|
115
|
+
} catch (error) {
|
|
116
|
+
const message = messageOf(error);
|
|
117
|
+
refused.push({
|
|
118
|
+
file,
|
|
119
|
+
message: message.includes(path) ? message : `home flow file "${path}": ${message}`,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return { flows, refused };
|
|
124
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Work that reads a store and must be over before the store is closed. After
|
|
3
|
+
* `drain` no new work starts, and work still running at the end of the wait is
|
|
4
|
+
* dropped quietly by its caller (`draining` tells it so).
|
|
5
|
+
*
|
|
6
|
+
* Nothing pending is lost or wrong in the window: a drained registry belongs
|
|
7
|
+
* to a context that is ending, its answers are read again from the next
|
|
8
|
+
* context's registry, and work that was in flight when the wait began either
|
|
9
|
+
* finishes with the right items or is dropped whole, never half-read: a late
|
|
10
|
+
* failure keeps only the items already complete.
|
|
11
|
+
*/
|
|
12
|
+
export class InFlight {
|
|
13
|
+
private readonly running = new Set<Promise<unknown>>();
|
|
14
|
+
private stopped = false;
|
|
15
|
+
|
|
16
|
+
/** True once `drain` was called: nothing new starts and a late failure is not news. */
|
|
17
|
+
get draining(): boolean {
|
|
18
|
+
return this.stopped;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Runs `work` counted as in flight. */
|
|
22
|
+
async track<T>(work: () => Promise<T>): Promise<T> {
|
|
23
|
+
const promise = work();
|
|
24
|
+
const settled = promise.then(
|
|
25
|
+
() => undefined,
|
|
26
|
+
() => undefined,
|
|
27
|
+
);
|
|
28
|
+
this.running.add(settled);
|
|
29
|
+
void settled.then(() => this.running.delete(settled));
|
|
30
|
+
return await promise;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Stops new work and waits for the work in flight, at most `timeoutMs`. */
|
|
34
|
+
async drain(timeoutMs: number): Promise<void> {
|
|
35
|
+
this.stopped = true;
|
|
36
|
+
if (this.running.size === 0) return;
|
|
37
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
38
|
+
const timeout = new Promise<void>((resolve) => {
|
|
39
|
+
timer = setTimeout(resolve, timeoutMs);
|
|
40
|
+
});
|
|
41
|
+
try {
|
|
42
|
+
await Promise.race([Promise.all([...this.running]), timeout]);
|
|
43
|
+
} finally {
|
|
44
|
+
clearTimeout(timer);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** How long a reload or a stop waits for work that reads the old store. */
|
|
50
|
+
export const DRAIN_TIMEOUT_MS = 5000;
|
package/src/plugin/load.ts
CHANGED
|
@@ -17,6 +17,12 @@ export interface LoadPluginRegistryOptions extends PluginRegistryOptions {
|
|
|
17
17
|
readonly configPath?: string | undefined;
|
|
18
18
|
/** Defaults to `<home>/keys.json`. */
|
|
19
19
|
readonly keysPath?: string | undefined;
|
|
20
|
+
/**
|
|
21
|
+
* Where the reason a flow file of the home was refused goes. Defaults to
|
|
22
|
+
* `onLog`. A caller that counts load problems passes another: a refused flow
|
|
23
|
+
* file is not a reason to keep older code.
|
|
24
|
+
*/
|
|
25
|
+
readonly onHomeFlowProblem?: ((message: string) => void) | undefined;
|
|
20
26
|
/**
|
|
21
27
|
* Plugins whose package the distribution installs into the home when a person
|
|
22
28
|
* enables them. A missing one is reported with the command that installs it.
|
|
@@ -274,6 +280,10 @@ export async function loadPluginRegistry(
|
|
|
274
280
|
off: offNames(config.entries, options.optional ?? {}),
|
|
275
281
|
disabledGuide: options.disabledGuide ?? offGuideReader(config.entries, options.optional ?? {}, home),
|
|
276
282
|
});
|
|
283
|
+
// The person's own flows load once every plugin's steps are known; a file
|
|
284
|
+
// that does not load is reported and the rest still load.
|
|
285
|
+
const onFlowProblem = options.onHomeFlowProblem ?? onLog;
|
|
286
|
+
for (const refusal of await registry.loadHomeFlows()) onFlowProblem(refusal.message);
|
|
277
287
|
// A harness reads its model list in the background; the load asks for none,
|
|
278
288
|
// so a client that asks just after it gets the list the home already keeps.
|
|
279
289
|
return registry;
|
package/src/plugin/registry.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import type { ClientApi } from "../views/presentation.ts";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
+
import { DRAIN_TIMEOUT_MS, InFlight } from "./in-flight.ts";
|
|
3
4
|
import type { FlowDefinition, StepType } from "../flow/types.ts";
|
|
4
5
|
import { loadFlow as loadFlowFile } from "../flow/load.ts";
|
|
5
6
|
import { FlowError, validateFlow } from "../flow/validate.ts";
|
|
6
7
|
import type { JsonValue } from "../log/types.ts";
|
|
7
8
|
import { validateActionArgs } from "./action-schema.ts";
|
|
8
9
|
import { readDeclaredFlows, writeDeclaredFlow } from "./declared-flows.ts";
|
|
10
|
+
import { HOME_FLOW_OWNER, loadHomeFlows } from "./home-flows.ts";
|
|
11
|
+
import type { HomeFlowRefusal } from "./home-flows.ts";
|
|
9
12
|
import { readFile } from "node:fs/promises";
|
|
10
13
|
import { AccessError, AskTimeoutError, messageOf, PluginError, StepNotLoadedError } from "./errors.ts";
|
|
11
14
|
import { defaultOperadHome } from "./home.ts";
|
|
@@ -256,6 +259,7 @@ export class PluginRegistry {
|
|
|
256
259
|
private readonly cwd: string;
|
|
257
260
|
/** Runs whose missing object was already logged, so a poll does not repeat it. */
|
|
258
261
|
private readonly reportedMissing = new Set<string>();
|
|
262
|
+
private readonly inFlight = new InFlight();
|
|
259
263
|
private readonly kernelVerbs: ReadonlySet<string>;
|
|
260
264
|
private shortCommands: ReadonlyMap<
|
|
261
265
|
string,
|
|
@@ -298,6 +302,9 @@ export class PluginRegistry {
|
|
|
298
302
|
string,
|
|
299
303
|
{ readonly plugin: string; readonly flow: FlowDefinition }
|
|
300
304
|
>();
|
|
305
|
+
/** The flows of `<home>/flows`, by name, and the files refused. */
|
|
306
|
+
private homeFlowMap: ReadonlyMap<string, FlowDefinition> = new Map();
|
|
307
|
+
private homeFlowRefusals: readonly HomeFlowRefusal[] = [];
|
|
301
308
|
private readonly refusalList: PluginRefusal[] = [];
|
|
302
309
|
private readonly settingsByPlugin: ReadonlyMap<
|
|
303
310
|
string,
|
|
@@ -730,6 +737,11 @@ export class PluginRegistry {
|
|
|
730
737
|
})),
|
|
731
738
|
);
|
|
732
739
|
const names = new Set(staticFlows.map((item) => item.flow.name));
|
|
740
|
+
const fromHome = [...this.homeFlowMap.values()].map((flow) => ({
|
|
741
|
+
plugin: HOME_FLOW_OWNER,
|
|
742
|
+
flow,
|
|
743
|
+
source: undefined,
|
|
744
|
+
}));
|
|
733
745
|
const generated = [...this.declaredFlows.values()]
|
|
734
746
|
.filter((item) => !names.has(item.flow.name))
|
|
735
747
|
.map((item) => ({
|
|
@@ -737,7 +749,29 @@ export class PluginRegistry {
|
|
|
737
749
|
flow: item.flow,
|
|
738
750
|
source: this.sourceByPlugin.get(item.plugin),
|
|
739
751
|
}));
|
|
740
|
-
return [...staticFlows, ...generated];
|
|
752
|
+
return [...staticFlows, ...generated, ...fromHome];
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/**
|
|
756
|
+
* Reads the flow files of `<home>/flows`, replacing what an earlier read
|
|
757
|
+
* found. A file that does not load is refused with its reason and the other
|
|
758
|
+
* files still load; the refusals are returned and kept for `homeFlowProblems`.
|
|
759
|
+
*/
|
|
760
|
+
async loadHomeFlows(): Promise<readonly HomeFlowRefusal[]> {
|
|
761
|
+
this.homeFlowMap = new Map();
|
|
762
|
+
const found = await loadHomeFlows(
|
|
763
|
+
this.home,
|
|
764
|
+
this.stepTypes(),
|
|
765
|
+
(name) => this.flow(name) !== undefined,
|
|
766
|
+
);
|
|
767
|
+
this.homeFlowMap = new Map(found.flows.map((item) => [item.flow.name, item.flow]));
|
|
768
|
+
this.homeFlowRefusals = found.refused;
|
|
769
|
+
return found.refused;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/** The flow files of the home the last read refused. */
|
|
773
|
+
homeFlowProblems(): readonly HomeFlowRefusal[] {
|
|
774
|
+
return this.homeFlowRefusals;
|
|
741
775
|
}
|
|
742
776
|
|
|
743
777
|
/**
|
|
@@ -792,7 +826,8 @@ export class PluginRegistry {
|
|
|
792
826
|
const flow = plugin.flows.find((item) => item.name === name);
|
|
793
827
|
if (flow !== undefined) return { plugin: plugin.name, flow };
|
|
794
828
|
}
|
|
795
|
-
|
|
829
|
+
const home = this.homeFlowMap.get(name);
|
|
830
|
+
return home === undefined ? undefined : { plugin: HOME_FLOW_OWNER, flow: home };
|
|
796
831
|
}
|
|
797
832
|
|
|
798
833
|
/** The result names a step type declares, or undefined when it is unknown. */
|
|
@@ -1738,6 +1773,26 @@ export class PluginRegistry {
|
|
|
1738
1773
|
* logged and shows nothing, so one plugin cannot hide the others.
|
|
1739
1774
|
*/
|
|
1740
1775
|
async standing(runs?: RunLookup): Promise<readonly StandingEntry[]> {
|
|
1776
|
+
// Once the registry is drained its store is about to close: no new work
|
|
1777
|
+
// starts, and an item missing until the next tick is not a wrong one.
|
|
1778
|
+
if (this.inFlight.draining) return [];
|
|
1779
|
+
return await this.inFlight.track(() => this.standingNow(runs));
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
/**
|
|
1783
|
+
* Stops starting standing work and waits, a bounded time, for the work that
|
|
1784
|
+
* runs. Called before the store of this registry is closed.
|
|
1785
|
+
*/
|
|
1786
|
+
async drain(timeoutMs: number = DRAIN_TIMEOUT_MS): Promise<void> {
|
|
1787
|
+
await this.inFlight.drain(timeoutMs);
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
/** True once `drain` was called. */
|
|
1791
|
+
get draining(): boolean {
|
|
1792
|
+
return this.inFlight.draining;
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
private async standingNow(runs?: RunLookup): Promise<readonly StandingEntry[]> {
|
|
1741
1796
|
const items: StandingEntry[] = [];
|
|
1742
1797
|
for (const plugin of this.plugins) {
|
|
1743
1798
|
if (plugin.standing === undefined) continue;
|
|
@@ -1779,6 +1834,9 @@ export class PluginRegistry {
|
|
|
1779
1834
|
});
|
|
1780
1835
|
}
|
|
1781
1836
|
} catch (error) {
|
|
1837
|
+
// Work that ends after the drain belongs to a store that is closing:
|
|
1838
|
+
// stop quietly and keep what earlier plugins already gave.
|
|
1839
|
+
if (this.inFlight.draining) return items;
|
|
1782
1840
|
this.log(`plugin "${plugin.name}": standing failed: ${messageOf(error)}`);
|
|
1783
1841
|
}
|
|
1784
1842
|
}
|
|
@@ -369,6 +369,13 @@ export class SqlitePluginStore implements PluginStore {
|
|
|
369
369
|
return row === null ? undefined : this.objectOf(row);
|
|
370
370
|
}
|
|
371
371
|
|
|
372
|
+
remove(type: string, id: string): void {
|
|
373
|
+
writeImmediate(this.db, () => {
|
|
374
|
+
this.db.query("DELETE FROM objects WHERE type = ? AND id = ?").run(type, id);
|
|
375
|
+
});
|
|
376
|
+
this.listed.get(type)?.delete(id);
|
|
377
|
+
}
|
|
378
|
+
|
|
372
379
|
list(type: string, options: ListOptions = {}): ListPage {
|
|
373
380
|
this.assertWhere(type, options);
|
|
374
381
|
const fingerprint = whereFingerprint(options.where ?? {});
|
package/src/plugin/store.ts
CHANGED
|
@@ -104,6 +104,10 @@ export class MemoryPluginStore implements PluginStore {
|
|
|
104
104
|
return this.objects.get(type)?.get(id);
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
+
remove(type: string, id: string): void {
|
|
108
|
+
this.objects.get(type)?.delete(id);
|
|
109
|
+
}
|
|
110
|
+
|
|
107
111
|
list(type: string, options: ListOptions = {}): ListPage {
|
|
108
112
|
this.assertWhere(type, options);
|
|
109
113
|
const fingerprint = whereFingerprint(options.where ?? {});
|
package/src/plugin/types.ts
CHANGED
|
@@ -499,6 +499,12 @@ export interface ObjectStore {
|
|
|
499
499
|
|
|
500
500
|
get(type: string, id: string): MaybePromise<StoredObject | undefined>;
|
|
501
501
|
|
|
502
|
+
/**
|
|
503
|
+
* Removes the object and its index entries. The facts it wrote stay in the
|
|
504
|
+
* history. Removing an object that is not there does nothing.
|
|
505
|
+
*/
|
|
506
|
+
remove(type: string, id: string): MaybePromise<void>;
|
|
507
|
+
|
|
502
508
|
/** One page of objects of `type`, ordered by id and filtered by `where`. */
|
|
503
509
|
list(type: string, options?: ListOptions): MaybePromise<ListPage>;
|
|
504
510
|
}
|
|
@@ -1064,6 +1070,11 @@ export interface ObjectTypeDefinition {
|
|
|
1064
1070
|
readonly index?: readonly string[] | undefined;
|
|
1065
1071
|
/** Ordered row filters for lists; see {@link ObjectFilterDefinition}. */
|
|
1066
1072
|
readonly filters?: readonly ObjectFilterDefinition[] | undefined;
|
|
1073
|
+
/**
|
|
1074
|
+
* Row states no list shows, not even the kernel's `all`. An object in one of
|
|
1075
|
+
* them is still read by its id.
|
|
1076
|
+
*/
|
|
1077
|
+
readonly unlistedStates?: readonly string[] | undefined;
|
|
1067
1078
|
}
|
|
1068
1079
|
|
|
1069
1080
|
/** The value types an action argument may have. */
|
package/src/plugin/validate.ts
CHANGED
|
@@ -438,8 +438,17 @@ function normalizeObjects(
|
|
|
438
438
|
|
|
439
439
|
const filters = normalizeFilters(entry.filters, `${at}[${index}]: filters`);
|
|
440
440
|
|
|
441
|
+
const unlisted = entry.unlistedStates;
|
|
442
|
+
if (
|
|
443
|
+
unlisted !== undefined &&
|
|
444
|
+
(!Array.isArray(unlisted) || unlisted.some((state) => typeof state !== "string" || state.length === 0))
|
|
445
|
+
) {
|
|
446
|
+
throw new PluginError(`${at}[${index}]: unlistedStates: must be an array of state names`);
|
|
447
|
+
}
|
|
448
|
+
|
|
441
449
|
objects.push({
|
|
442
450
|
name,
|
|
451
|
+
...(unlisted === undefined ? {} : { unlistedStates: unlisted as readonly string[] }),
|
|
443
452
|
...(entry.answeredAutomatically === undefined
|
|
444
453
|
? {}
|
|
445
454
|
: {
|
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
} from "../platform/index.ts";
|
|
15
15
|
import { runTimes } from "./running.ts";
|
|
16
16
|
import type { PluginRegistry, ActionInfo } from "../plugin/registry.ts";
|
|
17
|
+
import { DRAIN_TIMEOUT_MS, InFlight } from "../plugin/in-flight.ts";
|
|
17
18
|
import { rankOf, sortByRank, splitActionName } from "../plugin/registry.ts";
|
|
18
19
|
import { messageOf } from "../plugin/errors.ts";
|
|
19
20
|
import { createPluginLogger } from "../plugin/logger.ts";
|
|
@@ -715,6 +716,7 @@ export class Views {
|
|
|
715
716
|
/** The section of the last tail an object pushed, so an empty tail can clear it. */
|
|
716
717
|
private readonly liveSections = new Map<string, string>();
|
|
717
718
|
private closed = false;
|
|
719
|
+
private readonly resolving = new InFlight();
|
|
718
720
|
/** How the newest ended run of an object ended, keyed by its run and last fact. */
|
|
719
721
|
private readonly lastRunEnds = new Map<
|
|
720
722
|
string,
|
|
@@ -849,6 +851,14 @@ export class Views {
|
|
|
849
851
|
return this.store.get(type, id);
|
|
850
852
|
}
|
|
851
853
|
|
|
854
|
+
/**
|
|
855
|
+
* Stops starting work on the store and waits, a bounded time, for the
|
|
856
|
+
* resolves and standing work in flight. Call it before the store closes.
|
|
857
|
+
*/
|
|
858
|
+
async drain(timeoutMs: number = DRAIN_TIMEOUT_MS): Promise<void> {
|
|
859
|
+
await Promise.all([this.resolving.drain(timeoutMs), this.registry.drain(timeoutMs)]);
|
|
860
|
+
}
|
|
861
|
+
|
|
852
862
|
/** Closes the change listeners this view opened. */
|
|
853
863
|
close(): void {
|
|
854
864
|
this.closed = true;
|
|
@@ -867,6 +877,11 @@ export class Views {
|
|
|
867
877
|
this.lastRunEnds.clear();
|
|
868
878
|
}
|
|
869
879
|
|
|
880
|
+
/** True when a row of this type in this state is in no list. */
|
|
881
|
+
private unlisted(type: string, state: string): boolean {
|
|
882
|
+
return this.registry.objectType(type)?.unlistedStates?.includes(state) === true;
|
|
883
|
+
}
|
|
884
|
+
|
|
870
885
|
/** The filter a list of this type uses when the caller names none. */
|
|
871
886
|
defaultFilterOf(type: string): string | undefined {
|
|
872
887
|
return typeFilters(this.registry.objectType(type))?.default;
|
|
@@ -1019,6 +1034,7 @@ export class Views {
|
|
|
1019
1034
|
const inLevel =
|
|
1020
1035
|
accepted === undefined ? rowParent === undefined : rowParent !== undefined && accepted.has(rowParent);
|
|
1021
1036
|
if (!inLevel) continue;
|
|
1037
|
+
if (this.unlisted(name, row.state)) continue;
|
|
1022
1038
|
if (chosen === undefined || filterShows(chosen, row.state)) {
|
|
1023
1039
|
shown.push({ t, id: object.id, row });
|
|
1024
1040
|
} else {
|
|
@@ -1159,6 +1175,7 @@ export class Views {
|
|
|
1159
1175
|
}
|
|
1160
1176
|
for (const object of page.objects) {
|
|
1161
1177
|
const row = this.listRow(owner.plugin, type, object, flags, withScope);
|
|
1178
|
+
if (this.unlisted(type, row.state)) continue;
|
|
1162
1179
|
if (filterShows(chosen, row.state)) shown.push({ id: object.id, row });
|
|
1163
1180
|
else {
|
|
1164
1181
|
hidden += 1;
|
|
@@ -1235,9 +1252,9 @@ export class Views {
|
|
|
1235
1252
|
}
|
|
1236
1253
|
const flags = await this.allRunFlags();
|
|
1237
1254
|
const withScope = await this.scopeShown(owner.plugin, type, owner.views);
|
|
1238
|
-
const rows = page.objects
|
|
1239
|
-
this.listRow(owner.plugin, type, object, flags, withScope)
|
|
1240
|
-
|
|
1255
|
+
const rows = page.objects
|
|
1256
|
+
.map((object) => this.listRow(owner.plugin, type, object, flags, withScope))
|
|
1257
|
+
.filter((row) => !this.unlisted(type, row.state));
|
|
1241
1258
|
return { rows, ...(page.next === undefined ? {} : { next: page.next }) };
|
|
1242
1259
|
}
|
|
1243
1260
|
|
|
@@ -2359,6 +2376,15 @@ export class Views {
|
|
|
2359
2376
|
private async resolveWithPlugins(
|
|
2360
2377
|
id: string,
|
|
2361
2378
|
onlyType?: string,
|
|
2379
|
+
): Promise<ResolvedObject | undefined> {
|
|
2380
|
+
// A resolve that starts after the drain finds nothing: the store closes.
|
|
2381
|
+
if (this.resolving.draining) return undefined;
|
|
2382
|
+
return await this.resolving.track(() => this.resolveNow(id, onlyType));
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2385
|
+
private async resolveNow(
|
|
2386
|
+
id: string,
|
|
2387
|
+
onlyType?: string,
|
|
2362
2388
|
): Promise<ResolvedObject | undefined> {
|
|
2363
2389
|
const matches: ResolvedObject[] = [];
|
|
2364
2390
|
for (const entry of this.registry.objectTypes()) {
|
|
@@ -2379,6 +2405,7 @@ export class Views {
|
|
|
2379
2405
|
} catch (error) {
|
|
2380
2406
|
// A plugin refuses with a ViewError when it knows why the id is wrong.
|
|
2381
2407
|
if (error instanceof ViewError) throw error;
|
|
2408
|
+
if (this.resolving.draining) return undefined;
|
|
2382
2409
|
this.onLog(
|
|
2383
2410
|
`plugin "${entry.plugin}": resolve failed for "${entry.type}:${id}": ${messageOf(error)}`,
|
|
2384
2411
|
);
|