@elaraai/e3-cli 1.0.108 → 1.0.110

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 (68) hide show
  1. package/README.md +12 -1
  2. package/dist/src/cli.js +14 -4
  3. package/dist/src/cli.js.map +1 -1
  4. package/dist/src/commands/call.d.ts +102 -10
  5. package/dist/src/commands/call.d.ts.map +1 -1
  6. package/dist/src/commands/call.js +436 -99
  7. package/dist/src/commands/call.js.map +1 -1
  8. package/dist/src/commands/call.spec.d.ts +6 -0
  9. package/dist/src/commands/call.spec.d.ts.map +1 -0
  10. package/dist/src/commands/call.spec.js +154 -0
  11. package/dist/src/commands/call.spec.js.map +1 -0
  12. package/dist/src/commands/convert.impl.d.ts.map +1 -1
  13. package/dist/src/commands/convert.impl.js +4 -7
  14. package/dist/src/commands/convert.impl.js.map +1 -1
  15. package/dist/src/commands/convert.impl.spec.js +11 -1
  16. package/dist/src/commands/convert.impl.spec.js.map +1 -1
  17. package/dist/src/commands/mutate.d.ts.map +1 -1
  18. package/dist/src/commands/mutate.js +5 -17
  19. package/dist/src/commands/mutate.js.map +1 -1
  20. package/dist/src/commands/mutation-spec.d.ts +35 -0
  21. package/dist/src/commands/mutation-spec.d.ts.map +1 -0
  22. package/dist/src/commands/mutation-spec.js +42 -0
  23. package/dist/src/commands/mutation-spec.js.map +1 -0
  24. package/dist/src/commands/mutation-spec.spec.d.ts +6 -0
  25. package/dist/src/commands/mutation-spec.spec.d.ts.map +1 -0
  26. package/dist/src/commands/mutation-spec.spec.js +28 -0
  27. package/dist/src/commands/mutation-spec.spec.js.map +1 -0
  28. package/dist/src/commands/package.d.ts.map +1 -1
  29. package/dist/src/commands/package.js +4 -2
  30. package/dist/src/commands/package.js.map +1 -1
  31. package/dist/src/commands/rack-options.d.ts +100 -4
  32. package/dist/src/commands/rack-options.d.ts.map +1 -1
  33. package/dist/src/commands/rack-options.js +119 -9
  34. package/dist/src/commands/rack-options.js.map +1 -1
  35. package/dist/src/commands/rack-options.spec.js +62 -1
  36. package/dist/src/commands/rack-options.spec.js.map +1 -1
  37. package/dist/src/commands/run.d.ts +4 -2
  38. package/dist/src/commands/run.d.ts.map +1 -1
  39. package/dist/src/commands/run.js +123 -36
  40. package/dist/src/commands/run.js.map +1 -1
  41. package/dist/src/commands/seed.d.ts.map +1 -1
  42. package/dist/src/commands/seed.js +3 -19
  43. package/dist/src/commands/seed.js.map +1 -1
  44. package/dist/src/commands/watch.d.ts.map +1 -1
  45. package/dist/src/commands/watch.js +2 -2
  46. package/dist/src/commands/watch.js.map +1 -1
  47. package/dist/src/commands/workspace.d.ts.map +1 -1
  48. package/dist/src/commands/workspace.js +10 -24
  49. package/dist/src/commands/workspace.js.map +1 -1
  50. package/dist/src/intake.d.ts +49 -1
  51. package/dist/src/intake.d.ts.map +1 -1
  52. package/dist/src/intake.js +36 -20
  53. package/dist/src/intake.js.map +1 -1
  54. package/dist/src/interrupt.d.ts +33 -0
  55. package/dist/src/interrupt.d.ts.map +1 -0
  56. package/dist/src/interrupt.js +52 -0
  57. package/dist/src/interrupt.js.map +1 -0
  58. package/dist/src/interrupt.spec.d.ts +6 -0
  59. package/dist/src/interrupt.spec.d.ts.map +1 -0
  60. package/dist/src/interrupt.spec.js +65 -0
  61. package/dist/src/interrupt.spec.js.map +1 -0
  62. package/dist/src/utils.d.ts +17 -0
  63. package/dist/src/utils.d.ts.map +1 -1
  64. package/dist/src/utils.js +35 -2
  65. package/dist/src/utils.js.map +1 -1
  66. package/dist/src/utils.spec.js +28 -1
  67. package/dist/src/utils.spec.js.map +1 -1
  68. package/package.json +7 -7
@@ -3,13 +3,19 @@
3
3
  * Licensed under BSL 1.1. See LICENSE for details.
4
4
  */
5
5
  /**
6
- * e3 call command - Invoke a named package function with argument values.
6
+ * e3 call command - Invoke a function with argument values: a named package
7
+ * function, or a function from its IR file.
7
8
  *
8
9
  * Usage:
9
10
  * e3 call <repo> <pkg.fn> [args...] [-o out.beast2] # package-scoped
10
11
  * e3 call <repo> <pkg@1.0.0.fn> [args...]
11
12
  * e3 call <repo> -w <ws> <fn> [args...] # workspace-scoped
12
13
  * e3 call <repo> -w <ws> <fn> @.inputs.sales 5 # a dataset argument
14
+ * e3 call <repo> -w <ws> <fn> [args...] --draft <record>.<mutation> [args...]
15
+ * # over an unsaved edit
16
+ * e3 call <repo> --ir score.beast2 [args...] # a function from its IR file
17
+ * e3 call <url> -w <ws> --ir score.beast2 @.inputs.sales # through a server's one-shot calls
18
+ * e3 call <repo> -w <ws> <fn> [args...] --rack # on an enrolled rack
13
19
  *
14
20
  * Each positional argument is an .east literal (e.g. `5`, `"hello"`,
15
21
  * `[1.0, 2.0]`) or a path to a .beast2 / .json / .east file, parsed against
@@ -21,6 +27,32 @@
21
27
  * A function that declares inputs reads them from the workspace itself, so
22
28
  * its caller passes the arguments alone, and calls it with -w.
23
29
  *
30
+ * With -w, each `--draft <record>.<mutation> [args...]` lays an unsaved edit
31
+ * over a record the function reads (east-workspace#1619): the mutation runs as
32
+ * `e3 mutate` would run it, its arguments read the same way, and the function
33
+ * reads the record at the state that leaves. Nothing is saved. Drafts are laid
34
+ * in the order written. `--draft` reads every word up to the next option, so it
35
+ * is written after the call's own arguments, or the drafts are ended with `--`;
36
+ * a draft ends where its mutation's arguments do; and a word that starts with
37
+ * a dash is written `--draft=<word>`.
38
+ *
39
+ * With --ir the function is the IR file's — a function's or an async
40
+ * function's IR bundle, `.beast2`, or `.json` / `.east` as the runners' CLIs
41
+ * read one — and its signature is read from the IR. It runs on --runner's
42
+ * runtime, east-node unless named, with that runtime's standard platform
43
+ * package, or the packages --platform names (`none` for none). Through a
44
+ * server it is one of the workspace's one-shot calls, under the grant the
45
+ * server gives the caller: a reader may make a platform-free call alone. It
46
+ * reads no record, so it is passed no draft.
47
+ *
48
+ * With --rack a call of a local repository runs on an enrolled rack, whatever
49
+ * the repository's rack policy selects: a rule that names it (`fn:<name>`)
50
+ * still sizes it, and gives it its time, which its drafts and its function
51
+ * share. A call no rack can run runs here, judged before any rack session is
52
+ * opened for it, and a line on the terminal's stderr says where it ran and
53
+ * why. Its drafts are laid here, over this repository's records, and its
54
+ * function runs on the rack.
55
+ *
24
56
  * Calls are graph-free: the result is printed (or written with -o), and the
25
57
  * function's stdout and stderr go to the terminal's stderr, so the value can
26
58
  * be piped. A call of a local repository runs in this process and keeps
@@ -29,23 +61,33 @@
29
61
  * it for its lifetime, and Ctrl-C asks the server to stop it. A call through a
30
62
  * server's package runs within one request and keeps nothing.
31
63
  */
32
- import { readFile, writeFile } from 'fs/promises';
33
- import { decodeBeast2For, encodeBeast2For, fromEastTypeValue, decodeJSONFor, parseFor, printFor, none, variant, } from '@elaraai/east';
34
- import { packageRead, packageGetLatestVersion, workspaceGetPackage, detachedToExecuteResult, pinCallArguments, LocalStorage, LocalTaskRunner, } from '@elaraai/e3-core';
35
- import { decodeFunctionObject, parseKeypath, pathToString } from '@elaraai/e3-types';
36
- import { functionDescribe, functionCall, workspaceFunctionDescribe, workspaceFunctionCall, packageList as packageListRemote, } from '@elaraai/e3-api-client';
37
- import { parseRepoLocation, formatError, exitError } from '../utils.js';
64
+ import { readFile } from 'fs/promises';
65
+ import { basename, extname } from 'path';
66
+ import { IntegerType, decodeBeast2For, encodeBeast2For, fromEastTypeValue, decodeJSONFor, parseFor, printFor, none, variant, } from '@elaraai/east';
67
+ import { STANDARD_PLATFORM_BY_RUNNER, runnerToVariant } from '@elaraai/e3';
68
+ import { packageObjectRead, packageRead, workspaceGetPackage, detachedToExecuteResult, functionCallUnkept, pinCallArguments, readProgram, recordDescribe, withRunningWork, writeOutputFile, LocalStorage, LocalTaskRunner, } from '@elaraai/e3-core';
69
+ import { decodeFunctionObject, functionDraftEnded, functionDraftsOutlasted, inputLabel, parseKeypath, } from '@elaraai/e3-types';
70
+ import { ApiError, functionDescribe, functionCall, oneShotCall, workspaceFunctionDescribe, workspaceFunctionCall, workspaceRecordDescribe, } from '@elaraai/e3-api-client';
71
+ import { parseRepoLocation, resolvePackageVersion, formatError, exitError } from '../utils.js';
38
72
  import { parseTaskSpec } from './run.js';
39
73
  import { commandBudget, refuseRemoteBudget } from './budget.js';
74
+ import { openCommandRack, planRackCall, rackAsked, refuseRemoteRack, unattachedLine } from './rack-options.js';
75
+ import { arityRefusal, parseMutationSpec } from './mutation-spec.js';
76
+ import { untilInterrupted } from '../interrupt.js';
40
77
  /** How long a remote call's start waits for it to end before the call is
41
78
  * named, and polled: a call any longer can be stopped with Ctrl-C at once. */
42
79
  const CALL_START_WAIT_MS = 1_000;
43
- // Local calls have no transport ceiling — be generous but still bounded.
80
+ // Local calls have no transport ceiling — be generous but still bounded. A
81
+ // call's timeout covers the laying of its drafts and its function's run.
44
82
  const LOCAL_LIMITS = {
45
83
  timeoutMs: 10 * 60_000,
46
84
  maxResultBytes: 64 * 1024 * 1024,
47
85
  maxLogBytes: 64 * 1024,
48
86
  };
87
+ /** An Integer a message names, as East prints it: a draft's place among a call's. */
88
+ const printInteger = printFor(IntegerType);
89
+ /** Where a call's own arguments are written when it passes drafts. */
90
+ const OWN_ARGUMENTS_FIRST = "a call's own arguments are written before the first --draft, which reads every word up to the next option";
49
91
  /**
50
92
  * Checks a call's arguments against the function's signature: the arguments
51
93
  * alone are counted, never the inputs a call reads, and a function with inputs
@@ -55,15 +97,18 @@ const LOCAL_LIMITS = {
55
97
  * @param signature - Its signature
56
98
  * @param rawArgs - The arguments as written
57
99
  * @param workspace - The workspace the call runs in, when it names one
100
+ * @param drafted - Whether the call was written with a `--draft`, which reads
101
+ * every word after it: a miscount then says where a call's own arguments go
58
102
  * @throws {Error} When the count differs, or the function reads inputs and
59
103
  * the call names no workspace
60
104
  */
61
- export function checkCallArguments(fn, signature, rawArgs, workspace) {
105
+ export function checkCallArguments(fn, signature, rawArgs, workspace, drafted = false) {
62
106
  if (signature.inputs.length > 0 && workspace === undefined) {
63
- throw new Error(`Function '${fn}' reads ${signature.inputs.map((path) => pathToString(path)).join(', ')} from the workspace it is called through: pass -w <ws>`);
107
+ throw new Error(`Function '${fn}' reads ${signature.inputs.map((input) => inputLabel(input)).join(', ')} from the workspace it is called through: pass -w <ws>`);
64
108
  }
65
109
  if (rawArgs.length !== signature.argTypes.length) {
66
- throw new Error(`Function '${fn}' expects ${signature.argTypes.length} argument(s), got ${rawArgs.length}`);
110
+ const where = drafted ? ` — ${OWN_ARGUMENTS_FIRST}` : '';
111
+ throw new Error(`Function '${fn}' expects ${signature.argTypes.length} argument(s), got ${rawArgs.length}${where}`);
67
112
  }
68
113
  }
69
114
  /**
@@ -79,6 +124,56 @@ export function parseFunctionSpec(spec, workspaceScoped) {
79
124
  const { name, version, task } = parseTaskSpec(spec);
80
125
  return { name, version, fn: task };
81
126
  }
127
+ /** The runtimes `--runner` names, each with its standard platform package. */
128
+ const RUNTIMES = {
129
+ 'east-node': STANDARD_PLATFORM_BY_RUNNER.east_node,
130
+ 'east-c': STANDARD_PLATFORM_BY_RUNNER.east_c,
131
+ 'east-py': STANDARD_PLATFORM_BY_RUNNER.east_py,
132
+ };
133
+ /**
134
+ * The runner an IR file's function runs on: a stock runtime, east-node unless
135
+ * named, given the runtime's standard platform package, as `e3.function`'s
136
+ * default runner is, or the packages named in its place — none for `none`,
137
+ * which makes a platform-free call.
138
+ *
139
+ * @param runtime - `east-node`, `east-c` or `east-py`
140
+ * @param platforms - The packages it loads, in place of its standard one; `none` alone for none
141
+ * @returns The runner, as `e3.function` writes one ({@link runnerToVariant})
142
+ * @throws {Error} For another runtime, and for `none` named beside a package
143
+ */
144
+ export function irRunner(runtime = 'east-node', platforms) {
145
+ if (!Object.hasOwn(RUNTIMES, runtime))
146
+ throw new Error(`--runner names east-node, east-c or east-py, not '${runtime}'`);
147
+ const name = runtime;
148
+ if (platforms?.includes('none') === true && platforms.length > 1)
149
+ throw new Error('--platform none loads no package, and is named alone');
150
+ const named = platforms === undefined ? [RUNTIMES[name]] : platforms.includes('none') ? [] : [...platforms];
151
+ return runnerToVariant({ runtime: name, platforms: named.map((custom) => ({ custom })) });
152
+ }
153
+ /**
154
+ * Reads the function an IR file holds: its program as the bundle a runner is
155
+ * handed, its signature from the IR, and the runner it runs on.
156
+ *
157
+ * @param path - The IR file: `.beast2`, `.json` or `.east`
158
+ * @param runtime - The runtime it runs on ({@link irRunner})
159
+ * @param platforms - The packages it loads ({@link irRunner})
160
+ * @returns The program, named by its file without its extension
161
+ * @throws {Error} When the file cannot be read, holds no function's IR, or the
162
+ * runner is not one
163
+ */
164
+ export async function irProgram(path, runtime, platforms) {
165
+ const runner = irRunner(runtime, platforms);
166
+ const bytes = new Uint8Array(await readFile(path));
167
+ let program;
168
+ try {
169
+ program = readProgram(path, bytes);
170
+ }
171
+ catch (err) {
172
+ throw new Error(`${path} holds no function's IR: ${err instanceof Error ? err.message : String(err)}`);
173
+ }
174
+ return { name: basename(path, extname(path)), bodyIr: program.bodyIr, runner,
175
+ signature: { inputs: [], argTypes: program.argTypes, outputType: program.outputType } };
176
+ }
82
177
  /**
83
178
  * Encode one positional argument against its declared parameter type.
84
179
  * Accepts an inline .east literal or a .beast2/.json/.east file path.
@@ -141,6 +236,81 @@ export async function callArg(raw, typeValue, index) {
141
236
  }
142
237
  return variant('dataset', path);
143
238
  }
239
+ /**
240
+ * Reads the drafts a call was written with (`--draft`): unsaved edits to lay
241
+ * over the records its function reads, each a mutation call as `e3 mutate`
242
+ * takes one.
243
+ *
244
+ * @remarks
245
+ * The command line hands over the words of every `--draft` as one list, so a
246
+ * draft ends where its mutation's arguments do: `<record>.<mutation>`, then as
247
+ * many words as the mutation declares arguments, each read against its type as
248
+ * {@link encodeArg} reads one. The word after them names the next draft. A
249
+ * record is described once, however many drafts name it.
250
+ *
251
+ * @param words - Every word written after a `--draft`, in order
252
+ * @param workspace - The workspace the call runs in, which a refusal names
253
+ * @param describe - Describes a record of that workspace: its mutations, each
254
+ * with its form and the types of its arguments; `null` when it has no such
255
+ * record
256
+ * @returns The drafts, in the order written
257
+ * @throws {Error} Where a draft starts, for a word that names no mutation of a
258
+ * record of the workspace; for a draft with fewer words than its mutation
259
+ * takes; and for an argument that does not match its type. Each names the
260
+ * draft by its place and, where the draft before it decided how a word was
261
+ * read, says so
262
+ */
263
+ export async function readDrafts(words, workspace, describe) {
264
+ const drafts = [];
265
+ const described = new Map();
266
+ /** The draft before the one being read, and how many words it took. */
267
+ let before = null;
268
+ let at = 0;
269
+ while (at < words.length) {
270
+ const spec = words[at];
271
+ const place = drafts.length + 1;
272
+ // This word starts a draft because the one before it took the words it did
273
+ const readAs = before === null
274
+ ? ''
275
+ : ` — draft ${place - 1} (${before.spec}) takes ${before.takes} argument(s), so '${spec}' was read as the draft after it; ${OWN_ARGUMENTS_FIRST}`;
276
+ let named;
277
+ try {
278
+ named = parseMutationSpec(spec);
279
+ }
280
+ catch {
281
+ throw new Error(`Draft ${place}: '${spec}' is not a mutation, written <record>.<mutation>${readAs}`);
282
+ }
283
+ const { record, mutation } = named;
284
+ if (!described.has(record))
285
+ described.set(record, await describe(record));
286
+ const signature = described.get(record) ?? null;
287
+ if (signature === null) {
288
+ throw new Error(`Draft ${place} (${spec}): record '${record}' not found in workspace '${workspace}'${readAs}`);
289
+ }
290
+ const mut = signature.mutations.find((m) => m.name === mutation);
291
+ if (mut === undefined) {
292
+ const available = signature.mutations.map((m) => m.name).join(', ') || '(none)';
293
+ throw new Error(`Draft ${place} (${spec}): mutation '${mutation}' not found on record '${record}'. Available: ${available}${readAs}`);
294
+ }
295
+ const raw = words.slice(at + 1, at + 1 + mut.argTypes.length);
296
+ const refusal = arityRefusal(mutation, mut, raw.length);
297
+ if (refusal !== null)
298
+ throw new Error(`Draft ${place} (${spec}): ${refusal}`);
299
+ const args = [];
300
+ for (const [i, word] of raw.entries()) {
301
+ try {
302
+ args.push(await encodeArg(word, mut.argTypes[i], i));
303
+ }
304
+ catch (err) {
305
+ throw new Error(`Draft ${place} (${spec}): ${err instanceof Error ? err.message : String(err)}`);
306
+ }
307
+ }
308
+ drafts.push({ record, mutation, args });
309
+ before = { spec, takes: mut.argTypes.length };
310
+ at += 1 + mut.argTypes.length;
311
+ }
312
+ return drafts;
313
+ }
144
314
  /**
145
315
  * Writes a log tail of the function's to the terminal's stderr, the value's
146
316
  * stdout left to the value alone.
@@ -157,7 +327,8 @@ function forwardLog(text, truncated, stream) {
157
327
  }
158
328
  /**
159
329
  * Render a terminal ExecuteResult: print/write the value on success,
160
- * report the diagnostic and exit non-zero otherwise.
330
+ * report the diagnostic and exit non-zero otherwise. A call one of its drafts
331
+ * ended, before its function ran, is reported as that draft's.
161
332
  */
162
333
  async function renderResult(result, outputType, outputPath) {
163
334
  // Forward the function's captured logs — its stdout, then its stderr — to
@@ -166,11 +337,20 @@ async function renderResult(result, outputType, outputPath) {
166
337
  forwardLog(result.stdout, result.stdoutTruncated, 'stdout');
167
338
  forwardLog(result.stderr, result.stderrTruncated, 'stderr');
168
339
  const outcome = result.outcome;
340
+ // The draft whose mutation ended the call, as its result names it: never read
341
+ // from its stderr, whose first line says so for people, and which a function's
342
+ // own stderr may begin the same way (#1680's review)
343
+ const draft = functionDraftEnded(result);
344
+ const drafted = draft === null ? null : `Draft ${draft.record}.${draft.mutation} (${printInteger(draft.place)} of ${printInteger(draft.of)})`;
345
+ // Every draft laid, and the call's timeout ended before its function ran, as
346
+ // its result names it
347
+ const outlasted = functionDraftsOutlasted(result);
169
348
  switch (outcome.type) {
170
349
  case 'success': {
171
350
  const bytes = outcome.value.value;
172
351
  if (outputPath) {
173
- await writeFile(outputPath, bytes);
352
+ // Replaced, never written into: the file may be a store's object
353
+ await writeOutputFile(outputPath, bytes);
174
354
  console.log(`Output: ${outputPath}`);
175
355
  }
176
356
  else {
@@ -188,7 +368,9 @@ async function renderResult(result, outputType, outputPath) {
188
368
  break;
189
369
  }
190
370
  case 'failed': {
191
- console.error(`Function failed with exit code: ${outcome.value.exitCode}`);
371
+ console.error(drafted === null
372
+ ? `Function failed with exit code: ${outcome.value.exitCode}`
373
+ : `${drafted} failed with exit code: ${outcome.value.exitCode}; the function did not run`);
192
374
  process.exit(1);
193
375
  break;
194
376
  }
@@ -199,48 +381,150 @@ async function renderResult(result, outputType, outputPath) {
199
381
  break;
200
382
  }
201
383
  case 'timed_out': {
202
- console.error(`Function timed out after ${outcome.value.ms}ms`);
384
+ console.error(drafted !== null
385
+ ? `${drafted} had not been laid when the call timed out after ${outcome.value.ms}ms; the function did not run`
386
+ : outlasted
387
+ ? `The call's drafts were laid, and its timeout of ${outcome.value.ms}ms ended before the function ran: the function did not run`
388
+ : `Function timed out after ${outcome.value.ms}ms`);
389
+ process.exit(1);
390
+ break;
391
+ }
392
+ case 'conflict': {
393
+ console.error(`Draft ${outcome.value.record}.${outcome.value.mutation} (${printInteger(outcome.value.place)} of ${printInteger(outcome.value.of)}) `
394
+ + `conflicted: ${outcome.value.message} — `
395
+ + 'the edit no longer matches the record; re-read it and call again');
203
396
  process.exit(1);
204
397
  break;
205
398
  }
206
399
  }
207
400
  }
208
401
  /**
209
- * Call a function in a local repository (no server round trip).
402
+ * A named function of a local repository: of the package a workspace runs,
403
+ * or of a package by its name and version.
210
404
  */
211
- async function callLocal(repoPath, spec, workspace, rawArgs, budget, outputPath, verbose) {
212
- const storage = new LocalStorage();
405
+ async function namedProgram(storage, repoPath, spec, workspace) {
406
+ // Through a workspace, the package it names by its hash, which a call
407
+ // through it runs: never the package a name and a version name now, which
408
+ // an import under the same version replaces before any deploy of it
213
409
  let pkgName;
214
410
  let version;
411
+ let pkg;
215
412
  if (workspace) {
216
413
  const deployed = await workspaceGetPackage(storage, repoPath, workspace);
217
414
  pkgName = deployed.name;
218
415
  version = deployed.version;
416
+ pkg = await packageObjectRead(storage, repoPath, deployed.hash);
219
417
  }
220
418
  else {
221
419
  pkgName = spec.name;
222
- version = spec.version;
223
- if (version === 'latest') {
224
- const resolved = await packageGetLatestVersion(storage, repoPath, pkgName);
225
- if (!resolved) {
226
- exitError(`Package '${pkgName}' not found`);
227
- }
228
- version = resolved;
229
- }
420
+ version = await resolvePackageVersion({ type: 'local', path: repoPath }, pkgName, spec.version);
421
+ pkg = await packageRead(storage, repoPath, pkgName, version);
230
422
  }
231
- const pkg = await packageRead(storage, repoPath, pkgName, version);
232
423
  const fnHash = pkg.functions.get(spec.fn);
233
424
  if (!fnHash) {
234
425
  const available = Array.from(pkg.functions.keys()).join(', ');
235
426
  exitError(`Function '${spec.fn}' not found in ${pkgName}@${version}. Available: ${available || '(none)'}`);
236
427
  }
237
428
  const fnObj = decodeFunctionObject(Buffer.from(await storage.objects.read(repoPath, fnHash)));
238
- const signature = { inputs: fnObj.inputs, argTypes: fnObj.argTypes, outputType: fnObj.outputType };
239
- checkCallArguments(spec.fn, signature, rawArgs, workspace);
240
- // Through a workspace the function's inputs, and an argument that names one
241
- // of its datasets, are pinned at the hash each holds now, as a server pins
242
- // them, and named in the result; a call with none takes values only
243
- // (`callCommand` refuses a dataset without -w)
429
+ return {
430
+ name: spec.fn,
431
+ pkg: `${pkgName}@${version}`,
432
+ bodyIr: await storage.objects.read(repoPath, fnObj.bodyIr),
433
+ runner: fnObj.runner,
434
+ ...(fnObj.environment.type === 'some' && { environment: fnObj.environment.value }),
435
+ signature: { inputs: fnObj.inputs, argTypes: fnObj.argTypes, outputType: fnObj.outputType },
436
+ };
437
+ }
438
+ /**
439
+ * Runs a call on an enrolled rack, through a session opened for it alone: a
440
+ * rack is leased the call whatever the repository's policy selects, and where
441
+ * no rack can run it, it runs here. Where it ran, and why, goes to the
442
+ * terminal's stderr. Its program, and an argument too large to travel inline,
443
+ * are objects of the repository until the call ends, so no sweep takes them
444
+ * meanwhile. Ctrl-C leaves its lease, whose rack is told to stop it.
445
+ *
446
+ * @param label - What the rack's activity view names the call by: the
447
+ * workspace, the package, or nothing for an IR file's call
448
+ * @param policy - The repository's rack policy, read for the call already
449
+ * @param run - Runs the call's function on the rack's runner, which the
450
+ * signal stops
451
+ * @param finished - Whether what `run` answered is a value in hand, which a
452
+ * Ctrl-C that came with it did not stop
453
+ * @returns The call's outcome, or null once Ctrl-C has stopped it
454
+ */
455
+ async function callOnRack(storage, repoPath, program, label, budget, options, policy, run, finished) {
456
+ // Ctrl-C ends the wait for a rack and leaves the call's lease, from before
457
+ // its session opens
458
+ return untilInterrupted(async (signal) => {
459
+ const rack = await openCommandRack({ repoPath, workspace: label, storage, label: `e3 call ${program.name} (pid ${process.pid})`, budget,
460
+ rackOnly: options.rackOnly, signal, policy, print: (line) => console.error(line) });
461
+ try {
462
+ // A call always runs: with no session, here
463
+ const unattached = unattachedLine(rack, `fn:${program.name}`, true);
464
+ if (unattached !== undefined)
465
+ console.error(unattached);
466
+ return await withRunningWork(storage, repoPath, () => run(rack.runner, signal));
467
+ }
468
+ finally {
469
+ await rack.close();
470
+ }
471
+ // A value that came as Ctrl-C did is the call's: nothing was stopped
472
+ }, 'the call\'s rack is told to stop it', finished);
473
+ }
474
+ /**
475
+ * Call a function in a local repository (no server round trip): here, or
476
+ * with --rack on an enrolled rack.
477
+ *
478
+ * @remarks
479
+ * With --rack the repository's rack policy is read before anything of the
480
+ * call runs ({@link planRackCall}): a call no rack may run runs here at once,
481
+ * saying why, and a rule that names the call gives it its time, which its
482
+ * drafts and its function share, wherever it runs.
483
+ */
484
+ async function callLocal(storage, repoPath, program, rawArgs, draftWords, budget, options) {
485
+ const { signature } = program;
486
+ const workspace = options.workspace;
487
+ // What the rack's activity view names the call by: the workspace, the
488
+ // package, or nothing for an IR file's call through no workspace
489
+ const label = workspace ?? program.pkg ?? '';
490
+ checkCallArguments(program.name, signature, rawArgs, workspace, draftWords.length > 0);
491
+ const local = new LocalTaskRunner(repoPath, budget);
492
+ const plan = rackAsked(options)
493
+ ? await planRackCall(repoPath, storage, program.name, { bodyIr: program.bodyIr, args: [], runner: program.runner, limits: LOCAL_LIMITS,
494
+ ...(program.environment !== undefined && { environment: program.environment }) })
495
+ : undefined;
496
+ if (plan?.kind === 'here')
497
+ console.error(plan.line);
498
+ const policy = plan?.kind === 'rack' ? plan.policy : undefined;
499
+ const limits = { ...LOCAL_LIMITS, timeoutMs: plan?.timeoutMs ?? LOCAL_LIMITS.timeoutMs };
500
+ if (workspace !== undefined && program.pkg !== undefined) {
501
+ const args = await serverArgs(signature, rawArgs);
502
+ const drafts = await readDrafts(draftWords, workspace, (record) => recordDescribe(storage, repoPath, workspace, record));
503
+ // Through a workspace the function is resolved again, its inputs and an
504
+ // argument that names one of its datasets pinned at the hash each holds
505
+ // now, under the workspace's shared lock, and its drafts are laid over the
506
+ // records it reads, as a server's call resolves, pins and lays them: the
507
+ // result names what was read. Nothing of the call is kept, and nothing of a
508
+ // draft is saved. With --rack its drafts are laid here and its function
509
+ // runs on the rack
510
+ const call = (functionRunner, signal) => functionCallUnkept(storage, local, repoPath, workspace, program.name, { args, drafts }, {
511
+ limits,
512
+ ...(options.verbose !== undefined && { verbose: options.verbose }),
513
+ ...(functionRunner !== undefined && { functionRunner }),
514
+ ...(signal !== undefined && { signal }),
515
+ });
516
+ const result = policy !== undefined
517
+ ? await callOnRack(storage, repoPath, program, label, budget, options, policy, call, (answer) => answer.outcome.type === 'success')
518
+ : await call();
519
+ if (result !== null)
520
+ await renderResult(result, signature.outputType, options.output);
521
+ return;
522
+ }
523
+ // An IR file's function, or a package's through no workspace: through a
524
+ // workspace an argument that names one of its datasets is pinned at the
525
+ // hash it holds now, as a server pins it, and named in the result; a call
526
+ // with none takes values only (`callCommand` refuses a dataset and a draft
527
+ // without -w, and a draft for an IR file's function)
244
528
  let pinned;
245
529
  if (workspace === undefined) {
246
530
  const values = [];
@@ -250,108 +534,161 @@ async function callLocal(repoPath, spec, workspace, rawArgs, budget, outputPath,
250
534
  pinned = { args: values, inputs: [] };
251
535
  }
252
536
  else {
253
- const args = [];
254
- for (let i = 0; i < rawArgs.length; i++) {
255
- args.push(await callArg(rawArgs[i], signature.argTypes[i], i));
256
- }
257
- pinned = await pinCallArguments(storage, repoPath, workspace, args, { inputs: signature.inputs });
537
+ // The workspace is the call's whatever its arguments are: one it does not
538
+ // name is refused as a named function's call through it is, though no
539
+ // argument reads it
540
+ await workspaceGetPackage(storage, repoPath, workspace);
541
+ pinned = await pinCallArguments(storage, repoPath, workspace, await serverArgs(signature, rawArgs), { inputs: signature.inputs });
258
542
  }
259
543
  if (!('args' in pinned)) {
260
544
  // An unassigned dataset, and nothing ran
261
- await renderResult(pinned, signature.outputType, outputPath);
545
+ await renderResult(pinned, signature.outputType, options.output);
262
546
  return;
263
547
  }
264
- const runner = new LocalTaskRunner(repoPath, budget);
265
- const bodyIr = await storage.objects.read(repoPath, fnObj.bodyIr);
266
- const detached = await runner.runDetached({
267
- bodyIr,
268
- args: pinned.args,
269
- runner: fnObj.runner,
270
- limits: LOCAL_LIMITS,
271
- environment: fnObj.environment.type === 'some' ? fnObj.environment.value : undefined,
272
- }, { storage, verbose });
548
+ const spec = { bodyIr: program.bodyIr, args: pinned.args, runner: program.runner, limits,
549
+ ...(program.environment !== undefined && { environment: program.environment }) };
550
+ const detached = policy !== undefined
551
+ ? await callOnRack(storage, repoPath, program, label, budget, options, policy, (runner, signal) => runner.runDetached(spec, { storage, functionName: program.name, signal,
552
+ ...(options.verbose !== undefined && { verbose: options.verbose }) }), (answer) => answer.kind === 'success')
553
+ : await local.runDetached(spec, { storage, verbose: options.verbose });
554
+ if (detached === null)
555
+ return;
273
556
  // The wire shape a server answers, rendered the same way
274
- await renderResult(detachedToExecuteResult(detached, pinned.inputs), signature.outputType, outputPath);
557
+ await renderResult(detachedToExecuteResult(detached, pinned.inputs), signature.outputType, options.output);
558
+ }
559
+ /**
560
+ * Waits for a call a server keeps, which `start` starts: a call longer than a
561
+ * second is named then, so Ctrl-C reaches it at once, and Ctrl-C asks the
562
+ * server to stop it. A second Ctrl-C stops this process at once.
563
+ *
564
+ * @param start - Starts the call, given how it is stopped and told of
565
+ * @returns The call's result, or null once Ctrl-C has stopped it
566
+ */
567
+ function keptCall(start) {
568
+ // The client asks the server to stop the call as it gives it up: this
569
+ // process exits once that request has gone
570
+ return untilInterrupted((signal) => start({
571
+ signal,
572
+ startWaitMs: CALL_START_WAIT_MS,
573
+ onStarted: (id) => console.error(`Call ${id} runs on; Ctrl-C asks the server to stop it`),
574
+ }), 'the server is asked to stop the call');
575
+ }
576
+ /** Reads a call's arguments as a server takes them: values, and with a
577
+ * workspace its datasets, which the server pins. */
578
+ async function serverArgs(signature, rawArgs) {
579
+ const args = [];
580
+ for (let i = 0; i < rawArgs.length; i++) {
581
+ args.push(await callArg(rawArgs[i], signature.argTypes[i], i));
582
+ }
583
+ return args;
275
584
  }
276
585
  /**
277
586
  * Call a function on a remote repository via the API client.
278
587
  */
279
- async function callRemote(baseUrl, repo, token, spec, workspace, rawArgs, outputPath, verbose) {
588
+ async function callRemote(baseUrl, repo, token, spec, workspace, rawArgs, draftWords, outputPath, verbose) {
280
589
  const opts = { token, verbose };
281
- let version = spec.version;
282
- if (!workspace && version === 'latest') {
283
- const versions = (await packageListRemote(baseUrl, repo, opts))
284
- .filter((p) => p.name === spec.name)
285
- .map((p) => p.version)
286
- .sort();
287
- if (versions.length === 0) {
288
- exitError(`Package '${spec.name}' not found`);
289
- }
290
- version = versions[versions.length - 1];
291
- }
590
+ // A bare package name calls the greatest version the server holds
591
+ const version = workspace ? undefined : await resolvePackageVersion({ type: 'remote', baseUrl, repo, token }, spec.name, spec.version);
292
592
  const signature = workspace
293
593
  ? await workspaceFunctionDescribe(baseUrl, repo, workspace, spec.fn, opts)
294
594
  : await functionDescribe(baseUrl, repo, spec.name, version, spec.fn, opts);
295
- checkCallArguments(spec.fn, signature, rawArgs, workspace);
595
+ checkCallArguments(spec.fn, signature, rawArgs, workspace, draftWords.length > 0);
296
596
  // The server pins the function's inputs and a dataset argument in the
297
597
  // workspace
298
- const args = [];
299
- for (let i = 0; i < rawArgs.length; i++) {
300
- args.push(await callArg(rawArgs[i], signature.argTypes[i], i));
301
- }
302
- const request = { args, runner: none, limits: none };
598
+ const args = await serverArgs(signature, rawArgs);
599
+ // The server lays the drafts; each is read here against its mutation's
600
+ // types, which the server describes (`callCommand` refuses one without -w)
601
+ const drafts = workspace === undefined ? [] : await readDrafts(draftWords, workspace, async (record) => {
602
+ try {
603
+ return await workspaceRecordDescribe(baseUrl, repo, workspace, record, opts);
604
+ }
605
+ catch (err) {
606
+ // The workspace has no such record
607
+ if (err instanceof ApiError && err.code === 'dataset_not_found')
608
+ return null;
609
+ throw err;
610
+ }
611
+ });
612
+ const request = { args, runner: none, limits: none, drafts };
303
613
  if (!workspace) {
304
614
  await renderResult(await functionCall(baseUrl, repo, spec.name, version, spec.fn, request, opts), signature.outputType, outputPath);
305
615
  return;
306
616
  }
307
617
  // A call through a workspace is the server's, and outlives any request: it
308
- // is started and polled to its end, and Ctrl-C asks the server to stop it.
309
- // A second Ctrl-C stops this process at once.
310
- const stop = new AbortController();
311
- const interrupt = () => stop.abort(new Error('interrupted'));
312
- process.once('SIGINT', interrupt);
313
- let result;
314
- try {
315
- result = await workspaceFunctionCall(baseUrl, repo, workspace, spec.fn, request, opts, {
316
- signal: stop.signal,
317
- // A call longer than a second is named then, so Ctrl-C reaches it at once
318
- startWaitMs: CALL_START_WAIT_MS,
319
- onStarted: (id) => console.error(`Call ${id} runs on; Ctrl-C asks the server to stop it`),
320
- });
321
- }
322
- catch (err) {
323
- if (!stop.signal.aborted)
324
- throw err;
325
- // The client asks the server to stop the call as it gives it up: this
326
- // process exits once that request has gone
327
- console.error('Interrupted: the server is asked to stop the call');
328
- process.exitCode = 130;
329
- return;
330
- }
331
- finally {
332
- process.off('SIGINT', interrupt);
333
- }
334
- await renderResult(result, signature.outputType, outputPath);
618
+ // is started and polled to its end
619
+ const result = await keptCall((call) => workspaceFunctionCall(baseUrl, repo, workspace, spec.fn, request, opts, call));
620
+ if (result !== null)
621
+ await renderResult(result, signature.outputType, outputPath);
622
+ }
623
+ /**
624
+ * Call a function from its IR file through a server: one of a workspace's
625
+ * one-shot calls, under the grant the server gives the caller, started and
626
+ * polled as a workspace's function call is.
627
+ */
628
+ async function callIrRemote(baseUrl, repo, token, program, workspace, rawArgs, outputPath, verbose) {
629
+ if (workspace === undefined)
630
+ throw new Error('A call of an IR file through a server is one of a workspace\'s calls: pass -w <ws>');
631
+ checkCallArguments(program.name, program.signature, rawArgs, workspace);
632
+ const request = { bodyIr: program.bodyIr, args: await serverArgs(program.signature, rawArgs), runner: program.runner, limits: none };
633
+ const result = await keptCall((call) => oneShotCall(baseUrl, repo, workspace, request, { token, verbose }, call));
634
+ if (result !== null)
635
+ await renderResult(result, program.signature.outputType, outputPath);
335
636
  }
336
637
  /**
337
638
  * `e3 call` entry point.
639
+ *
640
+ * @param repoArg - The repository: a local path or a server's URL
641
+ * @param fnSpec - The function, as `pkg.fn` (or `fn` with -w); with --ir, the
642
+ * first argument, or none
643
+ * @param args - The arguments
644
+ * @param options - The call's options
338
645
  */
339
646
  export async function callCommand(repoArg, fnSpec, args, options) {
340
647
  try {
341
- const spec = parseFunctionSpec(fnSpec, options.workspace !== undefined);
648
+ // A server decides where its own work runs: refused before any credential is read
649
+ refuseRemoteRack(repoArg, options);
650
+ if (options.ir === undefined && (options.runner !== undefined || options.platform !== undefined)) {
651
+ throw new Error('--runner and --platform say what a function from its IR file runs on: a named function runs on its own runner');
652
+ }
653
+ if (options.ir === undefined && fnSpec === undefined) {
654
+ throw new Error('Name the function to call, as pkg.fn (or fn with -w), or call one from its IR file with --ir <file>');
655
+ }
656
+ // With --ir every positional is an argument
657
+ const positional = options.ir === undefined || fnSpec === undefined ? args : [fnSpec, ...args];
658
+ const spec = options.ir === undefined ? parseFunctionSpec(fnSpec, options.workspace !== undefined) : undefined;
342
659
  // A dataset argument is the workspace's: without one it is refused,
343
660
  // before anything is read
344
- const dataset = args.findIndex((arg) => arg.startsWith('@'));
661
+ const dataset = positional.findIndex((arg) => arg.startsWith('@'));
345
662
  if (dataset !== -1 && options.workspace === undefined) {
346
- throw new Error(`Argument ${dataset + 1} (${args[dataset]}) is a dataset, which a call reads from the workspace it runs in: pass -w <ws>`);
663
+ throw new Error(`Argument ${dataset + 1} (${positional[dataset]}) is a dataset, which a call reads from the workspace it runs in: pass -w <ws>`);
664
+ }
665
+ // A function from its IR file reads no record, whatever workspace is
666
+ // named: a draft is refused first by that
667
+ const drafts = options.draft ?? [];
668
+ if (drafts.length > 0 && options.ir !== undefined) {
669
+ throw new Error(`A draft (--draft ${drafts[0]}) is laid over a record a named function reads: a function from its IR file reads none`);
670
+ }
671
+ // A draft is laid over a record of the workspace, and a call through the
672
+ // package reads none: it is refused the same way
673
+ if (drafts.length > 0 && options.workspace === undefined) {
674
+ throw new Error(`A draft (--draft ${drafts[0]}) is laid over a record of the workspace the call runs in: pass -w <ws>`);
347
675
  }
348
676
  const location = await parseRepoLocation(repoArg);
349
677
  if (location.type === 'local') {
350
- await callLocal(location.path, spec, options.workspace, args, commandBudget(options), options.output, options.verbose);
678
+ const storage = new LocalStorage();
679
+ const program = spec === undefined
680
+ ? await irProgram(options.ir, options.runner, options.platform)
681
+ : await namedProgram(storage, location.path, spec, options.workspace);
682
+ await callLocal(storage, location.path, program, positional, drafts, commandBudget(options), options);
351
683
  }
352
684
  else {
353
685
  refuseRemoteBudget(options);
354
- await callRemote(location.baseUrl, location.repo, location.token, spec, options.workspace, args, options.output, options.verbose);
686
+ if (spec === undefined) {
687
+ await callIrRemote(location.baseUrl, location.repo, location.token, await irProgram(options.ir, options.runner, options.platform), options.workspace, positional, options.output, options.verbose);
688
+ }
689
+ else {
690
+ await callRemote(location.baseUrl, location.repo, location.token, spec, options.workspace, positional, drafts, options.output, options.verbose);
691
+ }
355
692
  }
356
693
  }
357
694
  catch (err) {