@coda-console/plugin-check 0.8.20 → 0.8.22

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.
Files changed (38) hide show
  1. package/README.md +3 -3
  2. package/check/agent.mjs +2 -1
  3. package/check/coda/adapters/call-limit.mjs +56 -0
  4. package/check/coda/adapters/clock.mjs +48 -0
  5. package/check/coda/adapters/plugin-command.mjs +171 -0
  6. package/check/coda/adapters/plugin-modules.mjs +505 -0
  7. package/check/coda/adapters/plugin-stream-services.mjs +53 -0
  8. package/check/coda/adapters/plugin-test-host.d.mts +316 -0
  9. package/check/coda/adapters/plugin-test-host.mjs +404 -0
  10. package/check/coda/adapters/process-relay.mjs +74 -0
  11. package/check/coda/adapters/provider-api.mjs +147 -40
  12. package/check/coda/application/contributions.mjs +1 -0
  13. package/check/coda/builtin.json +66 -67
  14. package/check/coda/components/composers/schemas.mjs +4 -2
  15. package/check/coda/components/concurrency-groups/schemas.mjs +102 -0
  16. package/check/coda/components/plugins/plugin-extensions.mjs +104 -10
  17. package/check/coda/components/plugins/plugin-rules.mjs +19 -1
  18. package/check/coda/components/plugins/plugin-source-rules.mjs +34 -14
  19. package/check/coda/components/plugins/process-contributions.mjs +9 -0
  20. package/check/coda/components/prompt-recovery/prompt-recovery.mjs +2 -49
  21. package/check/coda/components/protocols/record-rules.mjs +70 -0
  22. package/check/coda/components/protocols/types.mjs +22 -4
  23. package/check/coda/components/workflows/contributions.mjs +2 -6
  24. package/check/coda/contract.json +29 -21
  25. package/check/coda/domain/errors.mjs +5 -1
  26. package/check/coda/domain/resume-prompt.mjs +93 -0
  27. package/check/coda/domain/session-env.mjs +1 -1
  28. package/check/coda/resources/plugins/resources/panels/panels.mjs +26 -17
  29. package/check/coda/resources/plugins/resources/panels/rules.mjs +0 -4
  30. package/check/coda/resources/plugins/resources/panels/sign-in.mjs +32 -41
  31. package/check/manifest.mjs +0 -1
  32. package/check/panel.mjs +6 -5
  33. package/package.json +2 -2
  34. package/check/coda/adapters/admission-api.mjs +0 -22
  35. package/check/coda/components/protocols/creation.mjs +0 -19
  36. package/check/coda/domain/resource-admission.mjs +0 -15
  37. package/check/coda/resources/plugins/resources/panels/command.mjs +0 -46
  38. package/check/command.mjs +0 -48
@@ -0,0 +1,404 @@
1
+ // A plugin host for a plugin's own tests (coda#2749 第 7 节), on the trial surface (docs/plugins.md「模块」): the module's
2
+ // real `coda` and its handlers' real `ctx`, as the plugin host makes them (adapters/plugin-modules.mjs), with no backend —
3
+ // only the channel to it is this one's. A plugin's tests activate their module with `coda`, call its handlers as a caller
4
+ // would (`call`), a query or a doing call, call one off with a signal or a timeout, see each failure with its code as a
5
+ // caller does, and see a doing call's progress and answer its questions; and hand a doing call to its `resume` as the
6
+ // backend does once the process that had it ended (`resume`); query what its module registered with `coda.self.handle` as its own
7
+ // processes do (`self`); and call the operations its commands implement, run as the backend runs them
8
+ // (adapters/plugin-command.mjs). How the backend hosts a doing call beyond that (handing it
9
+ // over, the grace after it is called off, when `resume` is called and for how long) is the backend's, and its tests'.
10
+ //
11
+ // const host = createTestHost({ plugin: { id: 'translator', protocols, protocolImplementations: ['translator/service@1'] } });
12
+ // await activate(host.coda);
13
+ // await host.call({ kind: 'translator/service@1', id: 'default' }, 'translate', { text: 'x' });
14
+ //
15
+ // What the module queries (`coda.query`, `ctx.query`) of a record of a protocol it implements its own handlers answer; of
16
+ // another's, `call` given. A doing call it makes (`coda.call`, `ctx.call`) its own handlers answer, of a protocol it implements. Its settings (`coda.settings`) are those the test gives, or sets again with `setSettings`, which
17
+ // tells the module's `onChange` as the backend does. What it starts (`coda.spawn`, `ctx.spawn`) is a real child process of
18
+ // the test's, its streams and its end relayed as the backend relays them (adapters/process-relay.mjs), with no token and
19
+ // no entry in a registry: ended with the call or the module only as the test ends it, or as the host closes. The records
20
+ // (`coda.get`, `list`, `watch`, `put`, `delete`, `replace`, coda#2749 3.7) are those it writes, on this one machine, by its
21
+ // keys (their IDs derived as the backend derives them, of `TEST_OWNER`), and the others' the test gives (`records`), held
22
+ // to what the backend holds them to (components/protocols/record-rules.mjs, the kinds' schemas) but the record directory's
23
+ // size. Anything else of the backend's it asks is refused. A command implementing an operation is started as the module's
24
+ // processes are, with no token: what it asks with `coda` (`progress`, `ask`, `query`, `self`) is not answered here, but by the backend's.
25
+ import { CORE_PROTOCOLS } from '@coda-console/protocol/protocol';
26
+ import { spawn } from 'node:child_process';
27
+ import { randomUUID } from 'node:crypto';
28
+ import { ContractError } from '../domain/errors.mjs';
29
+ import { ProtocolTypes } from '../components/protocols/types.mjs';
30
+ import { commandOf, implementations } from '../components/plugins/plugin-rules.mjs';
31
+ import { checkGiven, checkHeld, checkKept, groupType, keptStatus } from '../components/concurrency-groups/schemas.mjs';
32
+ import { validate } from '../components/protocols/types.mjs';
33
+ import { LOCAL_KINDS, checkLabels, checkReplace, checkWrite, labelled, picked, readFilter, readRef, recordId, writeRef } from '../components/protocols/record-rules.mjs';
34
+ import { canonical } from '../domain/values.mjs';
35
+ import { checkInput, checkRequest, checkResult, limit, stopped } from './call-limit.mjs';
36
+ import { Clock } from './clock.mjs';
37
+ import { callEnv, fileCommand, queryCommand, queryId, settle, startPluginCommand } from './plugin-command.mjs';
38
+ import { pluginModules } from './plugin-modules.mjs';
39
+ import { checkNamed, relayProcess, unstarted } from './process-relay.mjs';
40
+ import { cancelOf, failed, failureOf, givenUp, outcomeOf } from './provider-api.mjs';
41
+
42
+ const refused = (code, message) => new ContractError(code, message, { effects: 'none' });
43
+ // What starts a command implementing an operation: a child of the test's, in a group of its own, registered nowhere.
44
+ const unregistered = { spawn: (_owner, _entry, file, args, options) => spawn(file, args, { ...options, detached: true }), remove: () => {} };
45
+ // This machine's backend, as the records the module writes name their holder, and where they are.
46
+ export const TEST_OWNER = 'test-host';
47
+ const open = { type: 'object' };
48
+
49
+ // `plugin`: the plugin under test as its manifest has it — its `id`, the `protocols` it defines, the
50
+ // `protocolImplementations` it handles (a protocol's name, or `{ kind, commands }`) and the named `processes` it declares —
51
+ // and its `path` and `state` directories.
52
+ // `call(record, operation, input, { signal, deadline })`: what answers the module's queries of records of protocols it does not implement. `clock`: what
53
+ // the calls' deadlines go by (adapters/clock.mjs), for a test to move. `settings`: the plugin's settings to begin with.
54
+ // `records`: others' records the module reads, each `{ kind, id, spec, status?, labels?, plugin?, owner?, location? }`,
55
+ // another machine's (`owner`, by default `other`; `plugin`, by default the plugin under test) or, `owner` this one's
56
+ // (`TEST_OWNER`), another plugin's here (`plugin`, by default `other`).
57
+ export function createTestHost({ plugin = {}, call = null, clock = new Clock(), settings = {}, records = [] } = {}) {
58
+ // The protocols as the backend compiles them: Coda's own, those of its concurrency groups (RunGroups.attach), those it
59
+ // keeps out of the record directory, and the plugin's.
60
+ const types = new ProtocolTypes();
61
+ for (const { name, spec, status, operations = {} } of [...Object.values(CORE_PROTOCOLS), { ...groupType, name: groupType.kind },
62
+ ...(plugin.protocols ?? [])]) types.register({ kind: name, spec, status, operations });
63
+ for (const kind of LOCAL_KINDS) if (!types.types.has(kind)) types.register({ kind, spec: open, status: open, operations: {} });
64
+ const manifest = { protocolImplementations: implementations(plugin.protocolImplementations ?? []) };
65
+ const implemented = manifest.protocolImplementations.map(entry => entry.kind);
66
+ const operationOf = (kind, operation) => types.types.get(kind)?.operations.get(operation);
67
+ const described = { id: plugin.id ?? 'test', path: plugin.path ?? process.cwd(), state: plugin.state ?? null, protocolImplementations: implemented };
68
+ // Requests to the module waiting for its answer, the module's queries under way, and the doing calls handed to it, with what
69
+ // their caller is told of them, by the request's ID each.
70
+ const waiting = new Map(), querying = new Map(), runs = new Map();
71
+ // The processes the module started, by the key it gave each, until they have exited.
72
+ const started = new Map();
73
+ let next = 0, current = JSON.parse(JSON.stringify(settings));
74
+ // Goes off as the host closes: the commands running are killed with it.
75
+ const ending = new AbortController();
76
+ // What the module sends the backend, taken after the turn it is sent in, as over a process's channel.
77
+ const modules = pluginModules({ send: message => queueMicrotask(() => taken(message)) });
78
+ const coda = modules.adopt(described, randomUUID());
79
+ // The records, by kind, each an entry (`{ owner, location, id, plugin, local, spec, status, labels?, version }`) by its holder and
80
+ // ID, and the keys of those of each kind the plugin holds, by their IDs (record-rules.mjs `recordId`); and the module's
81
+ // watches of them, by the watch's key, each with what it was last told.
82
+ let version = 0;
83
+ const kept = new Map(), held = new Map(), watching = new Map();
84
+ const idOf = (kind, key) => recordId(TEST_OWNER, described.id, kind, key);
85
+ const keyOf = entry => JSON.stringify([entry.owner, entry.id]);
86
+ const entryOf = ({ owner, location, id, plugin, spec, status, labels }) =>
87
+ ({ owner, location, id, plugin, local: owner === TEST_OWNER, spec, status, ...(labels === null ? {} : { labels }), version: String(++version) });
88
+ const kindOf = kind => {
89
+ if (typeof kind !== 'string' || !types.types.has(kind)) throw refused('not_found', `没有协议:${kind}`);
90
+ if (!kept.has(kind)) { kept.set(kind, new Map()); held.set(kind, new Map()); }
91
+ return kept.get(kind);
92
+ };
93
+ for (const { kind, id, spec, status = {}, labels = null, owner = 'other', location = owner, plugin = owner === TEST_OWNER ? 'other' : described.id } of records)
94
+ kindOf(kind).set(keyOf({ owner, id }), entryOf({ owner, location, id, plugin, spec, status, labels }));
95
+ // As the plugin reads them: its own with their keys.
96
+ const listed = (kind, filter) => {
97
+ const { scope, id, labels } = readFilter(filter), records = kindOf(kind), mine = held.get(kind);
98
+ return [...records.values()].filter(entry => (scope === 'available' || entry.local) && (id === undefined || entry.id === id) && labelled(entry.labels, labels))
99
+ .sort(({ local: one }, { local: other }) => Number(other) - Number(one))
100
+ .map(entry => entry.local && mine.has(entry.id) ? { ...entry, key: mine.get(entry.id) } : entry);
101
+ };
102
+ // The record a call is of, as the module's handler is given it (`ctx.record`): the plugin's own with its key.
103
+ const recordFor = ({ kind, id }) => held.get(kind)?.has(id) ? { kind, id, key: held.get(kind).get(id) } : { kind, id };
104
+ // Written as the backend writes it (components/protocols/providers.mjs), all of it or, refused, none of it: by the
105
+ // plugin's key, its ID derived from it; made by a plugin implementing its kind, then its holder's alone; its spec and
106
+ // status as its kind's schemas have them, defaults filled in, one not given as Coda keeps it (schemas.mjs `keptStatus`: a
107
+ // group's of capacity 1 `free` unless it is lent); unchanged, no new version; what it leaves of the groups'
108
+ // names checked as a whole. Then each watch of the kind is told what moved, as the plugin host tells it
109
+ // (components/plugins/plugin-host.mjs). Answered with the entries of the IDs `fn` says, as the plugin reads them.
110
+ function written(kind, fn) {
111
+ const records = new Map(kindOf(kind)), mine = new Map(held.get(kind));
112
+ // Coda's kinds only this machine keeps (record-rules.mjs `LOCAL_KINDS`), as the backend refuses them
113
+ // (components/protocols/providers.mjs `writing`).
114
+ if (LOCAL_KINDS.has(kind)) throw refused('forbidden', `插件不能写 ${kind}:它的记录只在本机,由 Coda 自己维护`);
115
+ const hold = key => {
116
+ const id = idOf(kind, key), at = keyOf({ owner: TEST_OWNER, id });
117
+ if (records.has(at) ? !mine.has(id) : !implemented.includes(kind)) throw refused('forbidden', `插件 ${described.id} 不能写 ${kind}/${key}`);
118
+ return [id, at];
119
+ };
120
+ const put = (key, value) => {
121
+ checkWrite(value); checkGiven(kind, value);
122
+ const [id, at] = hold(key), before = records.get(at), given = structuredClone(value), { spec, labels = null } = given, type = types.types.get(kind);
123
+ validate(type.spec, spec, `${kind}.spec`);
124
+ const status = Object.hasOwn(given, 'status') ? given.status : keptStatus(kind, spec, before ?? null);
125
+ validate(type.status, status, `${kind}.status`); checkLabels(labels);
126
+ checkHeld({ kind, id, spec, status });
127
+ mine.set(id, key);
128
+ if (!before || canonical([before.spec, before.status, before.labels ?? null]) !== canonical([spec, status, labels]))
129
+ records.set(at, entryOf({ owner: TEST_OWNER, location: TEST_OWNER, id, plugin: described.id, spec, status, labels }));
130
+ return id;
131
+ };
132
+ const remove = key => { const [id, at] = hold(key); records.delete(at); mine.delete(id); };
133
+ let answer;
134
+ try {
135
+ answer = fn({ put, remove, mine });
136
+ checkKept(kind, [...records.values()].filter(({ local }) => local));
137
+ } catch (error) { throw error instanceof ContractError ? error : refused('invalid_input', error.message); }
138
+ kept.set(kind, records); held.set(kind, mine);
139
+ for (const [key, watch] of watching) {
140
+ if (watch.kind !== kind) continue;
141
+ const now = new Map(listed(kind, watch.filter).map(entry => [keyOf(entry), entry])), events = [];
142
+ for (const [id, entry] of now) if (canonical(entry) !== canonical(watch.seen.get(id) ?? null)) events.push({ type: watch.seen.has(id) ? 'MODIFIED' : 'ADDED', id, object: entry });
143
+ for (const [id, entry] of watch.seen) if (!now.has(id)) events.push({ type: 'DELETED', id, object: entry });
144
+ watch.seen = now;
145
+ // A copy, as a message over the channel is: what the module does with it is none of the records.
146
+ if (events.length) modules.receive({ method: 'changed', params: { watch: key, events: structuredClone(events) } });
147
+ }
148
+ const entry = id => listed(kind, { scope: 'local', id })[0];
149
+ return Array.isArray(answer) ? answer.map(entry) : answer === null ? null : entry(answer);
150
+ }
151
+ const recordRequests = {
152
+ getRecord: ([ref]) => { const read = readRef(ref); return picked(listed(read.kind, { id: read.id })); },
153
+ listRecords: ([kind, filter]) => listed(kind, filter),
154
+ putRecord: ([ref, value]) => written(ref?.kind, ({ put }) => put(writeRef(ref).key, value)),
155
+ deleteRecord: ([ref]) => written(ref?.kind, ({ remove }) => { remove(writeRef(ref).key); return null; }),
156
+ replaceRecords: ([kind, entries]) => written(kind, ({ put, remove, mine }) => {
157
+ const given = new Set(checkReplace(entries).map(key => idOf(kind, key)));
158
+ for (const [id, key] of [...mine]) if (!given.has(id)) remove(key);
159
+ return entries.map(({ key, ...value }) => put(key, value));
160
+ }),
161
+ };
162
+
163
+ function taken(message) {
164
+ if (!message.method) {
165
+ const asked = waiting.get(message.id);
166
+ waiting.delete(message.id);
167
+ if (message.error !== undefined) asked?.reject(failed(message.error)); else asked?.resolve(message.result);
168
+ return;
169
+ }
170
+ if (message.method === 'cancel') return querying.get(message.params?.id)?.abort();
171
+ if (message.method === 'progress') return runs.get(message.params?.run)?.onProgress?.(message.params.value);
172
+ if (message.method === 'drained') return started.get(message.params?.process)?.drained(message.params);
173
+ if (message.method === 'kill') return started.get(message.params?.process)?.kill(message.params.signal);
174
+ if (message.method === 'unwatch') return watching.delete(message.params?.watch);
175
+ if (message.id === undefined) return;
176
+ const reply = answer => modules.receive({ id: message.id, ...answer });
177
+ // Answered with a copy, as over the channel: a record read is not the one kept.
178
+ const answered = work => Promise.resolve().then(work).then(result => reply({ result: structuredClone(result ?? null) }), error => reply({ error: failureOf(error) }));
179
+ if (message.method === 'spawn') return answered(() => spawned(message.params));
180
+ if (message.method === 'input') {
181
+ return answered(() => {
182
+ const running = started.get(message.params?.process);
183
+ if (!running) throw new ContractError('not_found', '进程已经结束');
184
+ return running.input(message.params);
185
+ });
186
+ }
187
+ if (message.method === 'settings') return reply({ result: JSON.parse(JSON.stringify(current)) });
188
+ // A doing call's question, answered as its caller's `answer` says; one at a time, as the backend has it
189
+ // (components/plugins/hosted-calls.mjs `question`).
190
+ if (message.method === 'question') {
191
+ const run = runs.get(message.params?.run);
192
+ return Promise.resolve().then(() => {
193
+ if (!run?.answer) throw new ContractError('not_ready', '这次调用的调用方不回答提问');
194
+ if (run.asking) throw new ContractError('invalid_state', '上一个提问还没有回答,不能再问', { effects: 'none' });
195
+ run.asking = true;
196
+ return Promise.resolve(run.answer(message.params.question)).finally(() => { run.asking = false; });
197
+ }).then(result => reply({ result }), error => reply({ error: failureOf(error) }));
198
+ }
199
+ // A record read or written, as the backend answers it once what the module wrote before is done.
200
+ if (message.method === 'provider' && Object.hasOwn(recordRequests, message.params?.method)) {
201
+ return answered(() => {
202
+ try { return recordRequests[message.params.method](message.params.args); } catch (error) {
203
+ throw error instanceof ContractError ? new ContractError(error.code, error.message, { effects: 'none' }) : refused('invalid_input', error.message);
204
+ }
205
+ });
206
+ }
207
+ // A kind's records watched: each entry, by its holder and ID (`{ type, id, entry }` to the module's listeners).
208
+ if (message.method === 'watch' && types.types.has(message.params?.collection)) {
209
+ return answered(() => {
210
+ const { collection: kind, selector } = message.params, entries = listed(kind, selector);
211
+ // Keyed as the module keys it: by the one plugin here.
212
+ watching.set(JSON.stringify([kind, selector, described.id]), { kind, filter: selector, seen: new Map(entries.map(entry => [keyOf(entry), entry])) });
213
+ return { items: entries.map(entry => ({ id: keyOf(entry), object: entry })), entries: true };
214
+ });
215
+ }
216
+ // A doing call the module makes (`coda.call`, `ctx.call`): handed to its own handler of it, as `call` hands one, given
217
+ // its `timeout`, at most what is left of the call it is made under; an idempotency key is not kept here. One only Coda
218
+ // calls (`codaOnly`, a group's `lend` and `return`) is refused, as the backend refuses it
219
+ // (components/plugins/plugin-callers.mjs): the test calls it, as Coda, with `call`.
220
+ if (message.method === 'call') {
221
+ const { record, operation, input, timeout, deadline, progress } = message.params, controller = new AbortController();
222
+ querying.set(message.id, controller);
223
+ return Promise.resolve().then(() => {
224
+ const found = operationOf(record?.kind, operation);
225
+ if (found?.codaOnly) throw refused('forbidden', `${record.kind}/${operation} 只由 Coda 调用,插件不能调`);
226
+ if (!found || found.safe || !implemented.includes(record.kind)) throw refused('not_found', `测试宿主里没有做事的操作 ${record?.kind}/${operation} 的处理函数`);
227
+ const left = deadline === null ? Infinity : deadline - clock.now(), within = Math.min(timeout ?? Infinity, left);
228
+ return run(record, operation, input, found, { signal: controller.signal, timeout: within === Infinity ? null : within,
229
+ onProgress: progress ? value => modules.receive({ method: 'callProgress', params: { id: message.id, value } }) : null });
230
+ }).then(result => reply({ result }), error => reply({ error: failureOf(error) })).finally(() => querying.delete(message.id));
231
+ }
232
+ if (message.method !== 'query') return reply({ error: `测试宿主没有后端,不答 ${message.method}` });
233
+ const { record, operation, input, timeout, deadline } = message.params, controller = new AbortController();
234
+ querying.set(message.id, controller);
235
+ query(record, operation, input, { signal: controller.signal, deadline: Math.min(timeout ? clock.now() + timeout : Infinity, deadline ?? Infinity) })
236
+ .then(result => reply({ result }), error => reply({ error: failureOf(error) }))
237
+ .finally(() => querying.delete(message.id));
238
+ }
239
+ // A process the module starts, as a child of the test's own, with the test's environment and what `env` adds; in the
240
+ // plugin's directory unless `cwd` says. A named one only as the manifest names it, as the backend has it; its output goes
241
+ // nowhere: there is no log here. One that does not start fails as the backend's does.
242
+ async function spawned(params) {
243
+ if (params.name !== null) checkNamed(described.id, plugin.processes, params.name);
244
+ let child;
245
+ try {
246
+ child = spawn(params.command, params.args, { cwd: params.cwd ?? described.path, env: { ...process.env, ...params.env },
247
+ stdio: params.name === null ? 'pipe' : 'ignore' });
248
+ } catch (error) { throw unstarted(params.command, error); }
249
+ if (!child.pid) throw unstarted(params.command, await new Promise(resolve => child.once('error', resolve)));
250
+ started.set(params.process, { child, ...relayProcess(child, params.process, message => modules.receive(message)) });
251
+ child.on('close', () => started.delete(params.process));
252
+ return { pid: child.pid };
253
+ }
254
+ // A query as the backend's unified call takes it: only of a `safe` operation, checked and given what a call goes by
255
+ // (adapters/call-limit.mjs); of a protocol the plugin implements, handed to its module, of another's, to `call`. However it
256
+ // fails, it did nothing (`none`), whatever its handler says; given up on with its caller's `signal`, it fails with that
257
+ // signal's reason itself, as the backend's `coda.query` does (`givenUp`: `none` unless it says its own `effects`).
258
+ async function query(record, operation, input, { signal = null, deadline = null } = {}) {
259
+ const found = operationOf(record?.kind, operation);
260
+ if (!found) throw refused('not_found', `没有这个操作:${record?.kind}/${operation}`);
261
+ if (!found.safe) throw refused('unsupported', `${record.kind}/${operation} 不是只读的操作(safe),不能查询:做事经调用内核`);
262
+ const own = implemented.includes(record.kind);
263
+ if (!own && !call) throw refused('not_found', `测试宿主里没有 ${record.kind} 的 provider`);
264
+ const name = `${record.kind}/${operation}`, request = { record: recordFor(record), operation, input,
265
+ requestId: randomUUID(), parent: { kind: 'plugin', id: described.id }, awaited: true };
266
+ const limited = limit(clock, found, { signal, deadline }), given = () => signal?.aborted ? givenUp(signal, 'none') : null;
267
+ try {
268
+ checkInput(found, name, input); checkRequest(request);
269
+ if (limited.signal.aborted) throw limited.signal.reason;
270
+ const command = own && commandOf(manifest, record.kind, operation);
271
+ const answer = command ? queried(command, { ...request, id: queryId(request), deadline: limited.deadline }, limited.signal) : own ? handed(request, limited)
272
+ : call(record, operation, input, { signal: limited.signal, deadline: limited.deadline });
273
+ const result = await Promise.race([answer, stopped(limited.signal)]);
274
+ checkResult(found, name, result);
275
+ return result;
276
+ } catch (error) {
277
+ throw given() ?? Object.assign(limited.signal.aborted ? limited.signal.reason : error, { effects: 'none' });
278
+ } finally { limited.end(); }
279
+ }
280
+ // Handed to the module as the plugin host hands it (`query`); called off, its handler's `ctx.signal` goes off with why.
281
+ function handed(request, limited) {
282
+ return new Promise((resolve, reject) => {
283
+ const id = ++next;
284
+ waiting.set(id, { resolve, reject });
285
+ limited.signal.addEventListener('abort', () => {
286
+ if (waiting.delete(id)) modules.receive({ method: 'cancel', params: { id, reason: cancelOf(limited.signal.reason) } });
287
+ }, { once: true });
288
+ modules.receive({ id, method: 'query', params: { plugin: described, request, deadline: limited.deadline } });
289
+ });
290
+ }
291
+
292
+ // A run of the plugin's command `file` implementing an operation, as the backend runs one (components/plugins/plugin-host.mjs
293
+ // `startCommand`): `sh -c` from the plugin's directory, the call's input as JSON on its standard input, its record, ID and
294
+ // deadline in its environment (`callEnv`); cancelled (`cancel`), its group asked to end, and made to once the grace has
295
+ // passed on the host's clock; the host closing kills it at once.
296
+ const commanded = (file, call, cancel) => startPluginCommand(fileCommand(file), { cwd: described.path, env: { ...process.env, ...callEnv(call) },
297
+ clock, timeoutMs: Infinity, signal: ending.signal, cancel, input: JSON.stringify(call.input), start: unregistered, label: `${described.id} · ${file}` });
298
+ // A query its command answers, as the backend's (`queryCommand`).
299
+ const queried = (file, call, signal) => queryCommand(() => commanded(file, call, signal), signal);
300
+ // A doing call its command has (`runCommand`): what it said, as a module's handler says it, as the command ended; called off
301
+ // with `signal`, or past its deadline, its command is stopped, and it ends as cancelled, or as timed out.
302
+ async function commandRun(file, call, signal) {
303
+ const cancel = new AbortController(), running = commanded(file, call, cancel.signal).done;
304
+ let late = false;
305
+ const off = timedOut => () => { late = timedOut; cancel.abort(); };
306
+ const given = off(false), unarm = call.deadline === null ? () => {} : clock.at(call.deadline, off(true));
307
+ if (signal?.aborted) given(); else signal?.addEventListener('abort', given, { once: true });
308
+ try {
309
+ const ran = await running;
310
+ const { result, error } = settle(late && ran.canceled ? { ...ran, canceled: false, timedOut: true } : ran);
311
+ return error ? { outcome: 'failed', error } : { outcome: 'completed', result };
312
+ } finally { unarm(); signal?.removeEventListener('abort', given); }
313
+ }
314
+
315
+ // A doing call of a protocol the plugin implements, handed to its module as the backend hands it (coda#2749 3.2–3.4): its
316
+ // input checked as the operation has it, its deadline its `timeout` from now or the operation's own, or none; called
317
+ // off with `signal`, or past its deadline, its handler's `ctx.signal` goes off (`AbortError`, `TimeoutError`) and its
318
+ // handler ends it still. Its result as the module's outcome says (`outcomeOf`); failed, thrown with its code; cancelled,
319
+ // thrown as `canceled`. Each progress is given to `onProgress`, each question to `answer`, which answers it.
320
+ async function run(record, operation, input, found, { signal, timeout, onProgress, answer }) {
321
+ const name = `${record.kind}/${operation}`, at = timeout ?? found.timeout;
322
+ const call = { id: randomUUID(), record: recordFor(record), operation, input, deadline: at ? clock.now() + at : null };
323
+ try { checkInput(found, name, input); checkRequest(call); } catch (error) { throw Object.assign(error, { effects: 'none' }); }
324
+ const command = commandOf(manifest, record.kind, operation);
325
+ if (command) return ended(found, name, await commandRun(command, call, signal));
326
+ const id = ++next, off = reason => () => modules.receive({ method: 'cancel', params: { id, reason: { name: reason } } });
327
+ const given = off('AbortError'), unarm = call.deadline === null ? () => {} : clock.at(call.deadline, off('TimeoutError'));
328
+ runs.set(id, { onProgress, answer });
329
+ try {
330
+ return ended(found, name, await new Promise((resolve, reject) => {
331
+ waiting.set(id, { resolve, reject });
332
+ modules.receive({ id, method: 'run', params: { plugin: described, call } });
333
+ if (signal?.aborted) given(); else signal?.addEventListener('abort', given, { once: true });
334
+ }));
335
+ } finally { runs.delete(id); unarm(); signal?.removeEventListener('abort', given); }
336
+ }
337
+ // A doing call's result as the module's outcome says (`outcomeOf`); failed, thrown with its code; cancelled, thrown as
338
+ // `canceled`.
339
+ function ended(found, name, said) {
340
+ const outcome = outcomeOf(found, name, said);
341
+ if (outcome.outcome === 'failed') throw failed(outcome.error);
342
+ if (outcome.outcome === 'canceled') throw new ContractError('canceled', '调用被取消了');
343
+ return outcome.result;
344
+ }
345
+
346
+ return {
347
+ // The plugin's `coda`, for its module's `activate`.
348
+ coda,
349
+ // Calls the plugin's module (or, for another's record, `call`) as a caller would: its result, or a failure with its
350
+ // `code`, `effects` and `retryAfterMs`. A query given up on with `signal` fails as an `AbortError`, past `timeout` as a
351
+ // `timeout`; a doing call of a protocol the plugin implements ends as its handler ends it (`run`).
352
+ call(record, operation, input = {}, { signal = null, timeout = null, onProgress = null, answer = null } = {}) {
353
+ const found = operationOf(record?.kind, operation);
354
+ if (found && !found.safe && implemented.includes(record.kind)) return run(record, operation, input, found, { signal, timeout, onProgress, answer });
355
+ return query(record, operation, input, { signal, deadline: timeout ? clock.now() + timeout : null });
356
+ },
357
+ // A query of the module's own (`coda self <名字>`, docs/plugins.md「只给自己用的查询」), handed to what it registered with
358
+ // `coda.self.handle` as the backend hands it (components/plugins/plugin-host.mjs `querySelf`): its result, given 30 seconds by
359
+ // the host's clock; or its failure, `not_found` for a name it did not register. Given up on before it is handed over, it is
360
+ // not handed over: nothing done.
361
+ async self(operation, input = {}, { signal = null } = {}) {
362
+ const limited = limit(clock, {}, { signal });
363
+ try {
364
+ if (limited.signal.aborted) throw Object.assign(limited.signal.reason, { effects: 'none' });
365
+ const request = { record: { kind: 'self', id: described.id }, operation, input, requestId: randomUUID(),
366
+ parent: { kind: 'plugin', id: described.id }, awaited: true };
367
+ const result = await Promise.race([handed(request, limited), stopped(limited.signal)]);
368
+ checkResult({}, `self/${operation}`, result);
369
+ return result;
370
+ } catch (error) { throw Object.assign(error, { effects: 'none' }); } finally { limited.end(); }
371
+ },
372
+ // A doing call of a protocol the plugin implements, left by a process of the plugin's that ended before its handler did,
373
+ // handed to its operation's `resume` as the backend hands it (coda#2749 3.6), with the call's `deadline` (`ctx.deadline`),
374
+ // or none: asked to be cancelled (`canceled`), or past its deadline, its `ctx.signal` gone off already as an
375
+ // `AbortError` or a `TimeoutError`; its result, or its failure, as `call`'s; with no `resume`, interrupted, of unknown
376
+ // effect, as the backend ends it then.
377
+ async resume(record, operation, { id = randomUUID(), input = {}, progress = null, canceled = false, deadline = null } = {}) {
378
+ const found = operationOf(record?.kind, operation), name = `${record?.kind}/${operation}`;
379
+ if (!found || found.safe || !implemented.includes(record.kind)) throw refused('not_found', `插件没有实现做事的操作 ${name}`);
380
+ const halted = canceled ? { name: 'AbortError' } : deadline !== null && deadline <= clock.now() ? { name: 'TimeoutError' } : null;
381
+ const call = { id, record: recordFor(record), operation, input, deadline, progress, canceled,
382
+ ...(halted ? { halted } : {}) }, at = ++next;
383
+ const said = await new Promise((resolve, reject) => {
384
+ waiting.set(at, { resolve, reject });
385
+ modules.receive({ id: at, method: 'resume', params: { plugin: described, call } });
386
+ });
387
+ if (said === null) throw new ContractError('interrupted', `插件没有给 ${name} 写 resume`, { effects: 'unknown' });
388
+ return ended(found, name, said);
389
+ },
390
+ // The plugin's settings written again, as `Plugins.setSettings` leaves them: what the module's `settings.get` gives from now
391
+ // on, and what its `settings.onChange` listeners are told, which have been by the time this is done.
392
+ setSettings: async next => {
393
+ current = JSON.parse(JSON.stringify(next));
394
+ await modules.receive({ method: 'settingsChanged', params: { plugin: described.id, settings: JSON.parse(JSON.stringify(current)) } });
395
+ },
396
+ // What the module started ends (`services`, and its processes, killed), as when the host stops; and the commands running.
397
+ close: () => {
398
+ ending.abort();
399
+ clock.close();
400
+ for (const { child } of started.values()) child.kill('SIGKILL');
401
+ return modules.stop();
402
+ },
403
+ };
404
+ }
@@ -0,0 +1,74 @@
1
+ // A process a plugin's module started (`coda.spawn`, `ctx.spawn`; docs/plugins.md「起进程」), relayed to the module over
2
+ // the plugin host's channel: by the backend for the processes it starts (components/plugins/plugin-processes.mjs), and
3
+ // by the plugins' test host for its own (adapters/plugin-test-host.mjs), so that its output, its input and its end cross
4
+ // alike. To the module: `output { process, stream, data }` (base64) and `output { process, stream, end: true }` for
5
+ // `stdout` and `stderr` each, then `exited { process, code, signal }` once both have ended and the process has (the
6
+ // child's `close`): nothing of it comes after. From it: what it wrote to `stdin` (`input`, answered once written, so a
7
+ // writer waits on each), what it has read of an output (`drained`) and `kill`. What it wrote that the process has not
8
+ // taken once it has closed (Node calls back no write or end on an input it destroyed as the process exited) fails then,
9
+ // and what it writes after fails at once.
10
+ //
11
+ // A process started with no pipes (a named one, its output in a log file) has none of these but its end and `kill`.
12
+ //
13
+ // Each output may be at most WINDOW bytes ahead of what the module has read: past it, the stream is paused, and the
14
+ // process waits on its pipe as it would on a reader of its own, until the module reads. Detached (the module's process
15
+ // gone), what it writes is read and dropped: nobody waits on it.
16
+ import { ContractError, requireCondition as check } from '../domain/errors.mjs';
17
+
18
+ export const WINDOW = 256 * 1024;
19
+
20
+ // What both say of one asked for: a named one only as the plugin's manifest names it (`contributes.processes`); one that
21
+ // did not start at all (no such program; Node refusing its arguments or directory) did nothing.
22
+ export const checkNamed = (plugin, processes, name) =>
23
+ check((processes ?? []).includes(name), 'not_found', `插件 ${plugin} 的清单里没有进程 ${name}(contributes.processes)`);
24
+ export const unstarted = (command, error) => new ContractError('spawn_failed', `起不了 ${command}:${error.message}`, { effects: 'none' });
25
+
26
+ export function relayProcess(child, key, send) {
27
+ let attached = true;
28
+ const tell = (method, params) => { if (attached) try { send({ method, params: { process: key, ...params } }); } catch {} };
29
+ const ahead = { stdout: 0, stderr: 0 };
30
+ for (const name of ['stdout', 'stderr']) {
31
+ const stream = child[name];
32
+ if (!stream) continue;
33
+ stream.on('data', chunk => {
34
+ if (!attached) return;
35
+ tell('output', { stream: name, data: chunk.toString('base64') });
36
+ if ((ahead[name] += chunk.length) >= WINDOW) stream.pause();
37
+ });
38
+ stream.on('end', () => tell('output', { stream: name, end: true }));
39
+ }
40
+ child.stdin?.on('error', () => {});
41
+ // The input written or ended and not answered yet, by how each fails.
42
+ const pending = new Set();
43
+ let closed = false;
44
+ const gone = () => Object.assign(new Error('进程已经结束,写不进去了'), { code: 'EPIPE' });
45
+ child.on('close', (code, signal) => {
46
+ closed = true;
47
+ for (const reject of pending) reject(gone());
48
+ pending.clear();
49
+ tell('exited', { code, signal });
50
+ });
51
+ return {
52
+ // What the module wrote, written: done once the pipe has taken it, or its end; failing as either does.
53
+ input({ data, end }) {
54
+ return new Promise((resolve, reject) => {
55
+ if (closed) return reject(gone());
56
+ pending.add(reject);
57
+ const done = error => { pending.delete(reject); if (error) reject(error); else resolve(); };
58
+ if (end) return child.stdin.end(done);
59
+ child.stdin.write(Buffer.from(String(data), 'base64'), done);
60
+ });
61
+ },
62
+ drained({ stream, bytes }) {
63
+ if (!Object.hasOwn(ahead, stream) || !Number.isSafeInteger(bytes) || bytes < 0) return;
64
+ ahead[stream] = Math.max(0, ahead[stream] - bytes);
65
+ if (ahead[stream] < WINDOW) child[stream].resume();
66
+ },
67
+ // A signal Node does not know is sent to nobody.
68
+ kill(signal = 'SIGTERM') { try { child.kill(signal); } catch {} },
69
+ detach() {
70
+ attached = false;
71
+ child.stdout?.resume(); child.stderr?.resume();
72
+ },
73
+ };
74
+ }