Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/wait-interrupted.md
Original file line number Diff line number Diff line change
@@ -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))
3 changes: 3 additions & 0 deletions docs/contract/output.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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 <uid>`.

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:

Expand All @@ -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 <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

Expand Down
23 changes: 17 additions & 6 deletions src/commands/project/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions src/commands/teleport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -407,7 +408,7 @@ ${paint("dim", `Tip: ${tip.replaceAll("<name>", 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();
Expand Down
69 changes: 52 additions & 17 deletions src/lib/base-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<T>(
what: string,
interrupted: { status?: string[]; next: string[] },
poll: (onProgress: (current: { status: string }) => void) => Promise<T>,
): Promise<T> {
const startedAt = performance.now();
let last: string | undefined;
return {
update: (status) => {
let exiting: Promise<never> | 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)`,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
);
},
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) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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. */
Expand Down Expand Up @@ -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),
);
Expand Down
1 change: 1 addition & 0 deletions src/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
18 changes: 18 additions & 0 deletions test/commands/document/__snapshots__/add.test.ts.snap
Original file line number Diff line number Diff line change
@@ -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,
Expand Down
53 changes: 52 additions & 1 deletion test/commands/document/add.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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()),
Expand Down
14 changes: 14 additions & 0 deletions test/commands/project/__snapshots__/add.test.ts.snap
Original file line number Diff line number Diff line change
@@ -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,
Expand Down
33 changes: 32 additions & 1 deletion test/commands/project/add.test.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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(
Expand Down
6 changes: 3 additions & 3 deletions test/contract/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
Loading