diff --git a/.changeset/wait-interrupted.md b/.changeset/wait-interrupted.md new file mode 100644 index 00000000..5dec9870 --- /dev/null +++ b/.changeset/wait-interrupted.md @@ -0,0 +1,5 @@ +--- +"@meilisearch/cli": minor +--- + +Change `--wait`: Ctrl-C exits 130 and says how to follow the task or project. ([#86](https://github.com/meilisearch/cli/pull/86)) diff --git a/docs/contract/output.md b/docs/contract/output.md index 813b6325..94196689 100644 --- a/docs/contract/output.md +++ b/docs/contract/output.md @@ -106,6 +106,7 @@ The CLI warns when the config file is readable by others, see `config.md`. | 5 | Timeout: `--wait` exceeded `--timeout`, or the HTTP request timed out. | | 6 | Cannot connect: DNS failure, connection refused, TLS error. | | 7 | Task finished with status `failed` or `canceled`, or the project of `project add` with status `failed` (only with `--wait`). The final task or project is still printed on stdout. | +| 130 | Interrupted: Ctrl-C (SIGINT) stopped `--wait`, or `teleport`. | No other code is used on purpose. If a new situation needs its own code, add it to this table first. @@ -118,6 +119,7 @@ Most write operations of the Meilisearch API return a task, not a result. The CL - Polling starts at 100 ms and grows to a maximum of 1 s between calls. - `--timeout` accepts a duration: `500ms`, `30s`, `2m`. Default `10m`. On timeout, the CLI prints an error with code `cli_timeout` and exits 5. The task keeps running on the server. - Progress goes to stderr, and only when stderr is a TTY: one line each time the status changes, with the time spent, such as "◐ Task 42 is processing (3s)". +- Ctrl-C stops the wait and exits 130. The task keeps running on the server. A human reads that the CLI stopped watching it, and the command to follow it: `meili task view --id `. A Cloud project is not ready when `POST /api/v2/projects` answers. Its `status` says when it is ready, and its `url` may be `null` until then. `meili project add --wait` follows the same rules, with the project instead of the task: @@ -126,6 +128,7 @@ A Cloud project is not ready when `POST /api/v2/projects` answers. Its `status` - The final project is printed as `GET /api/v2/projects/{id}` returns it, without `masterKey`: only the creation returns it. `--sync-config` writes the key from the creation to the config file. - On timeout, the CLI returns `cli_timeout` and exits 5. The creation continues on the server, and nothing is written to the config file. - Progress goes to stderr, and only when stderr is a TTY: one line each time the status changes, such as "◐ Project 343 is health checking (95s)". +- Ctrl-C stops the wait and exits 130, like a timeout: the creation continues, and nothing is written to the config file. A human reads the command to follow it: `meili project view --id `. With `--sync-config`, the human also reads that the project is not in the config file, and the command that adds it later: `meili config sync-with-cloud`. ## Destructive commands diff --git a/src/commands/project/add.ts b/src/commands/project/add.ts index ea3543fe..074cca04 100644 --- a/src/commands/project/add.ts +++ b/src/commands/project/add.ts @@ -74,15 +74,26 @@ Creates it in a team, on a resource. The master key is printed masked: give --sy sync = { file, entry: body.name }; } const created = await postApiV2Projects({ client: this.managementClient, body }); - const progress = this.waitProgress(`Project ${created.id}`); const project = timeoutMs === undefined ? created - : await waitForProject(this.managementClient, created.id, { - timeoutMs, - onProgress: (current) => progress.update(current.status), - }); - progress.end(); + : await this.watch( + `Project ${created.id}`, + { + status: sync === undefined ? [] : ["It was not added to the config file."], + next: [ + `${paint("dim", "Follow it:")} meili project view --id ${created.id}`, + ...(sync === undefined + ? [] + : [ + paint("dim", "Once it is Running, add it to the config file:"), + ` meili config sync-with-cloud --project-name ${sync.entry}`, + ]), + ], + }, + (onProgress) => + waitForProject(this.managementClient, created.id, { timeoutMs, onProgress }), + ); const running = project.status === "running"; await this.output( project.masterKey === undefined diff --git a/src/commands/teleport.ts b/src/commands/teleport.ts index ab569a1b..d337abe1 100644 --- a/src/commands/teleport.ts +++ b/src/commands/teleport.ts @@ -21,6 +21,7 @@ import { regionLatency } from "../lib/clients/ping.js"; import { cloudOf, everyPage, type ReachableProject, waitForProject } from "../lib/cloud-sync.js"; import { assertNoProject, type ConfigFile, isProjectUrl, writeConfigFile } from "../lib/config.js"; import { + EXIT_CODES, ManagementApiError, MeiliCliError, parseErrorBody, @@ -151,7 +152,7 @@ The same steps, without questions: ${WITHOUT_TELEPORT}`; return; } this.sayWhatExists(); - void this.exitNow(130); + void this.exitNow(EXIT_CODES.interrupted); }; process.once("SIGINT", onInterrupt); try { @@ -407,7 +408,7 @@ ${paint("dim", `Tip: ${tip.replaceAll("", name)}`)}`; // Ctrl-C on a question. if (isPromptExit(error)) { this.sayWhatExists(); - this.exit(130); + this.exit(EXIT_CODES.interrupted); } const { body, exitCode } = toRenderedError(error); say(); diff --git a/src/lib/base-command.ts b/src/lib/base-command.ts index 7a5ae96d..10aa85fa 100644 --- a/src/lib/base-command.ts +++ b/src/lib/base-command.ts @@ -21,7 +21,14 @@ import { resolveCloudProjectId, resolveProjectConnection, } from "./config.js"; -import { MeiliCliError, toRenderedError, writeError, writeNotice, writeWarning } from "./errors.js"; +import { + EXIT_CODES, + MeiliCliError, + toRenderedError, + writeError, + writeNotice, + writeWarning, +} from "./errors.js"; import { defaultView, itemView, taskOutcome } from "./human.js"; import { readStdin } from "./input.js"; import { @@ -413,25 +420,53 @@ export abstract class BaseCommand extends Command { } /** - * What `--wait` writes on stderr while it polls: one line each time the - * status changes, with the time spent, and a blank line once it is over. + * The `--wait` of `what`: `poll` polls it until its final status. On stderr, + * one line each time the status changes, with the time spent, and a blank + * line once it is over. Ctrl-C exits 130, and tells a human that `what` goes + * on, then `interrupted`: what the command did not do, and how to follow it. */ - protected waitProgress(what: string): { update: (status: string) => void; end: () => void } { + protected async watch( + what: string, + interrupted: { status?: string[]; next: string[] }, + poll: (onProgress: (current: { status: string }) => void) => Promise, + ): Promise { const startedAt = performance.now(); let last: string | undefined; - return { - update: (status) => { + let exiting: Promise | undefined; + const onInterrupt = () => { + if (outputMode().human) { + writeView({ + status: [ + "", + `${paint("yellow", "◐")} ${what} is still in progress. meili CLI stopped watching it.`, + ...(interrupted.status ?? []), + ], + next: interrupted.next, + }); + } + exiting = this.exitNow(EXIT_CODES.interrupted); + }; + process.once("SIGINT", onInterrupt); + let final: T; + try { + final = await poll(({ status }) => { if (status === last) return; last = status; const seconds = Math.round((performance.now() - startedAt) / 1000); writeNotice( `${paint("yellow", "◐")} ${what} is ${status.replaceAll("_", " ")} (${seconds}s)`, ); - }, - end: () => { - if (last !== undefined) writeNotice(""); - }, - }; + }); + } finally { + process.removeListener("SIGINT", onInterrupt); + // Ctrl-C during the last poll: the command never goes on with its result or its error. + if (exiting !== undefined) { + await exiting; + this.exit(EXIT_CODES.interrupted); + } + } + if (last !== undefined) writeNotice(""); + return final; } /** The `--timeout` of `--wait`, or `MEILI_TIMEOUT`, or the default, in milliseconds. */ @@ -460,12 +495,12 @@ export abstract class BaseCommand extends Command { })); return; } - const progress = this.waitProgress(`Task ${task.taskUid}`); - const finalTask = await waitForTask(this.meilisearch, task.taskUid, { - timeoutMs: this.waitTimeoutMs(flags), - onProgress: (current) => progress.update(current.status), - }); - progress.end(); + const timeoutMs = this.waitTimeoutMs(flags); + const finalTask = await this.watch( + `Task ${task.taskUid}`, + { next: [`${paint("dim", "Follow it:")} meili task view --id ${task.taskUid}`] }, + (onProgress) => waitForTask(this.meilisearch, task.taskUid, { timeoutMs, onProgress }), + ); await this.output(finalTask, () => itemView(taskOutcome(finalTask, sentences.succeeded), finalTask), ); diff --git a/src/lib/errors.ts b/src/lib/errors.ts index efb12b7e..d9fc81fc 100644 --- a/src/lib/errors.ts +++ b/src/lib/errors.ts @@ -23,6 +23,7 @@ export const EXIT_CODES = { timeout: 5, network: 6, taskFailed: 7, + interrupted: 130, } as const; export type ExitCode = (typeof EXIT_CODES)[keyof typeof EXIT_CODES]; diff --git a/test/commands/document/__snapshots__/add.test.ts.snap b/test/commands/document/__snapshots__/add.test.ts.snap index 58177cf4..c1df9faf 100644 --- a/test/commands/document/__snapshots__/add.test.ts.snap +++ b/test/commands/document/__snapshots__/add.test.ts.snap @@ -1,5 +1,23 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html +exports[`meili document add > exits 130 on Ctrl-C during --wait, and tells a human how to follow the task 1`] = ` +{ + "code": 130, + "stderr": " +◐ Task 42 is still in progress. meili CLI stopped watching it. + +Follow it: meili task view --id 42 +", +} +`; + +exports[`meili document add > exits 130 on Ctrl-C during --wait, and writes nothing more without a human 1`] = ` +{ + "code": 130, + "stderr": "", +} +`; + exports[`meili document add > passes the 404 of an unknown index through and exits 4 1`] = ` { "exitCode": 4, diff --git a/test/commands/document/add.test.ts b/test/commands/document/add.test.ts index 32dd458e..74a642b3 100644 --- a/test/commands/document/add.test.ts +++ b/test/commands/document/add.test.ts @@ -1,7 +1,8 @@ import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { describe, expect, it } from "vitest"; +import { HttpResponse, http } from "msw"; +import { describe, expect, it, vi } from "vitest"; import DocumentAdd from "../../../src/commands/document/add.js"; import { MEILISEARCH_URL, @@ -121,6 +122,56 @@ describe("meili document add", () => { expect(JSON.parse(result.stdout)).toMatchObject({ uid: 42, status: "succeeded" }); }); + it.each([ + ["tells a human how to follow the task", true], + ["writes nothing more without a human", false], + ])("exits 130 on Ctrl-C during --wait, and %s", async (_, tty) => { + let exit: { code: unknown; stderr: string } | undefined; + let stderr = ""; + vi.spyOn(process, "exit").mockImplementationOnce((code) => { + exit = { code, stderr }; + return undefined as never; + }); + server.use( + meilisearchHandlers.documentsAdd(makeEnqueuedTask()), + http.get(`${MEILISEARCH_URL}/tasks/42`, () => { + process.emit("SIGINT"); + return HttpResponse.json(makeTask({ uid: 42, status: "succeeded" })); + }), + ); + await runCommand( + DocumentAdd, + ["--index", "movies", "--data", documents, "--wait", ...project], + { + tty, + onStderr: (chunk) => { + stderr += chunk; + }, + }, + ); + expect(exit).toMatchSnapshot(); + }); + + it("exits 130 without an error when the last poll fails after Ctrl-C", async () => { + vi.spyOn(process, "exit").mockImplementationOnce(() => undefined as never); + server.use( + meilisearchHandlers.documentsAdd(makeEnqueuedTask()), + http.get(`${MEILISEARCH_URL}/tasks/42`, () => { + process.emit("SIGINT"); + return HttpResponse.error(); + }), + ); + const result = await runCommand(DocumentAdd, [ + "--index", + "movies", + "--data", + documents, + "--wait", + ...project, + ]); + expect(result).toEqual({ stdout: "", stderr: "", exitCode: 130 }); + }); + it("prints the final task and exits 7 when the task failed", async () => { server.use( meilisearchHandlers.documentsAdd(makeEnqueuedTask()), diff --git a/test/commands/project/__snapshots__/add.test.ts.snap b/test/commands/project/__snapshots__/add.test.ts.snap index f7065190..15e32532 100644 --- a/test/commands/project/__snapshots__/add.test.ts.snap +++ b/test/commands/project/__snapshots__/add.test.ts.snap @@ -1,5 +1,19 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html +exports[`meili project add > exits 130 on Ctrl-C during --wait, tells a human how to follow the project, and writes no config 1`] = ` +{ + "code": 130, + "stderr": " +◐ Project 343 is still in progress. meili CLI stopped watching it. +It was not added to the config file. + +Follow it: meili project view --id 343 +Once it is Running, add it to the config file: + meili config sync-with-cloud --project-name demo +", +} +`; + exports[`meili project add > fails with cli_timeout and exit 5 when the project is not running within --timeout 1`] = ` { "exitCode": 5, diff --git a/test/commands/project/add.test.ts b/test/commands/project/add.test.ts index 4ad996e1..9b4a54d6 100644 --- a/test/commands/project/add.test.ts +++ b/test/commands/project/add.test.ts @@ -1,5 +1,5 @@ import { HttpResponse, http } from "msw"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import ProjectAdd from "../../../src/commands/project/add.js"; import { writeConfigFile } from "../../../src/lib/config.js"; import { @@ -243,6 +243,37 @@ describe("meili project add", () => { expect(readJson(path)).toEqual({ projects: {} }); }); + it("exits 130 on Ctrl-C during --wait, tells a human how to follow the project, and writes no config", async () => { + let exit: { code: unknown; stderr: string } | undefined; + let stderr = ""; + vi.spyOn(process, "exit").mockImplementationOnce((code) => { + exit = { code, stderr }; + return undefined as never; + }); + server.use( + http.get(`${MANAGEMENT_URL}/api/v2/projects/343`, () => { + process.emit("SIGINT"); + return HttpResponse.json(polled); + }), + ...creation("running"), + ); + const { path, env: configEnv } = tempConfig("wait-interrupted.json", {}); + const result = await runCommand( + ProjectAdd, + ["--name", "demo", "--team-id", "12", "--resource-id", "3", "--wait", "--sync-config"], + { + env: { ...env, ...configEnv }, + tty: true, + onStderr: (chunk) => { + stderr += chunk; + }, + }, + ); + expect(exit).toMatchSnapshot(); + expect(result).toEqual({ stdout: "", stderr, exitCode: 130 }); + expect(readJson(path)).toEqual({ projects: {} }); + }); + it("tells a human in a terminal that the project is starting, and how to save it once running", async () => { server.use(...creation("running")); const result = await runCommand( diff --git a/test/contract/errors.test.ts b/test/contract/errors.test.ts index ecc2c9fb..f2265877 100644 --- a/test/contract/errors.test.ts +++ b/test/contract/errors.test.ts @@ -16,9 +16,9 @@ describe("error codes", () => { describe("exit codes", () => { const table = tableRows(section(outputDoc, "Exit codes")).map((row) => Number(row[0])); - it("EXIT_CODES is exactly the table 0 to 7", () => { - expect(table).toEqual([0, 1, 2, 3, 4, 5, 6, 7]); - expect([...Object.values(EXIT_CODES)].sort()).toEqual(table); + it("EXIT_CODES is exactly the table 0 to 7 and 130", () => { + expect(table).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 130]); + expect([...Object.values(EXIT_CODES)].sort((a, b) => a - b)).toEqual(table); }); it("every code maps to the exit code its situation has in the table", () => {