diff --git a/docs/n8n_data-table_row_insert.md b/docs/n8n_data-table_row_insert.md index 3b65b12..7d6e3c1 100644 --- a/docs/n8n_data-table_row_insert.md +++ b/docs/n8n_data-table_row_insert.md @@ -15,6 +15,10 @@ selects what comes back: count, the inserted ids, or the full rows. The whole batch is one request, so the API accepts or rejects it as a whole. Requires dataTableRow:create. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + ``` n8n data-table row insert [flags] ``` @@ -24,20 +28,21 @@ n8n data-table row insert [flags] ``` n8n data-table row insert TABLE_ID --set email=a@example.com --set age=30 n8n data-table row insert TABLE_ID --set email=b@example.com --return all --output json - n8n data-table row insert TABLE_ID --input rows.json --return id + n8n data-table row insert TABLE_ID --input rows.json --return id --idempotency-key auto printf '%s\n' '[{"email":"c@example.com"}]' | n8n data-table row insert TABLE_ID --input - ``` ### Options ``` - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - -h, --help help for insert - --input string row JSON array or object, from a file path or - for stdin (cannot combine with --set; maximum 1 MiB) - --output string output format: text or json (JSON preserves the count, ids and rows the API sent) (default "text") - --return string what the API returns: count, id or all (default: the server default of count) - --set stringArray column value as COLUMN=VALUE for one row, repeatable (cannot combine with --input) - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for insert + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) + --input string row JSON array or object, from a file path or - for stdin (cannot combine with --set; maximum 1 MiB) + --output string output format: text or json (JSON preserves the count, ids and rows the API sent) (default "text") + --return string what the API returns: count, id or all (default: the server default of count) + --set stringArray column value as COLUMN=VALUE for one row, repeatable (cannot combine with --input) + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) ``` ### SEE ALSO diff --git a/docs/n8n_data-table_row_upsert.md b/docs/n8n_data-table_row_upsert.md index 4df607f..5b059f3 100644 --- a/docs/n8n_data-table_row_upsert.md +++ b/docs/n8n_data-table_row_upsert.md @@ -12,6 +12,10 @@ The inserted row is built from the values given, not from the filter, so include the matched column in --set when the new row should carry it. Use --dry-run to see what would happen first. Requires dataTableRow:upsert. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + ``` n8n data-table row upsert [flags] ``` @@ -27,17 +31,18 @@ n8n data-table row upsert [flags] ### Options ``` - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - --dry-run ask the server to report the change without persisting it (implies --return-data) - --filter string whole filter object as JSON, e.g. '{"type":"and","filters":[{"columnName":"status","condition":"eq","value":"active"}]}' (cannot combine with --where) - -h, --help help for upsert - --input string column values as a JSON object, from a file path or - for stdin (cannot combine with --set; maximum 1 MiB) - --match string how several --where expressions combine: and or or (default "and") - --output string output format: text or json (JSON contains the acknowledgement and any returned rows) (default "text") - --return-data ask the API for the affected rows instead of a bare acknowledgement - --set stringArray column value to write as COLUMN=VALUE, repeatable (cannot combine with --input) - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) - --where stringArray row condition as COLUMN=VALUE or COLUMN=CONDITION=VALUE, repeatable, conditions: eq, neq, like, ilike, gt, gte, lt, lte (required unless --filter is given) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --dry-run ask the server to report the change without persisting it (implies --return-data) + --filter string whole filter object as JSON, e.g. '{"type":"and","filters":[{"columnName":"status","condition":"eq","value":"active"}]}' (cannot combine with --where) + -h, --help help for upsert + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) + --input string column values as a JSON object, from a file path or - for stdin (cannot combine with --set; maximum 1 MiB) + --match string how several --where expressions combine: and or or (default "and") + --output string output format: text or json (JSON contains the acknowledgement and any returned rows) (default "text") + --return-data ask the API for the affected rows instead of a bare acknowledgement + --set stringArray column value to write as COLUMN=VALUE, repeatable (cannot combine with --input) + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --where stringArray row condition as COLUMN=VALUE or COLUMN=CONDITION=VALUE, repeatable, conditions: eq, neq, like, ilike, gt, gte, lt, lte (required unless --filter is given) ``` ### SEE ALSO diff --git a/docs/n8n_execution_retry.md b/docs/n8n_execution_retry.md index 7abb58c..e072495 100644 --- a/docs/n8n_execution_retry.md +++ b/docs/n8n_execution_retry.md @@ -13,6 +13,10 @@ The original execution is retained and the response identifies the new run. A run that cannot be retried returns a conflict. This starts workflow work and may repeat its external side effects. Requires execution:retry. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + ``` n8n execution retry [flags] ``` @@ -22,17 +26,18 @@ n8n execution retry [flags] ``` n8n execution retry EXECUTION_ID n8n execution retry EXECUTION_ID --latest-workflow - n8n execution retry EXECUTION_ID --output json + n8n execution retry EXECUTION_ID --idempotency-key auto --output json ``` ### Options ``` - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - -h, --help help for retry - --latest-workflow run the workflow currently saved instead of the definition stored with the original execution (default: stored definition) - --output string output format: text or json (JSON is the newly started execution) (default "text") - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for retry + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) + --latest-workflow run the workflow currently saved instead of the definition stored with the original execution (default: stored definition) + --output string output format: text or json (JSON is the newly started execution) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) ``` ### SEE ALSO diff --git a/docs/n8n_execution_stop-many.md b/docs/n8n_execution_stop-many.md index e35ea0d..fb95875 100644 --- a/docs/n8n_execution_stop-many.md +++ b/docs/n8n_execution_stop-many.md @@ -14,6 +14,10 @@ workflows globally by accident; the literal workflow ID 'all' is rejected, use or canceled run may later be retried. Interactive runs ask for confirmation and non-interactive runs require --yes. Requires execution:stop. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + ``` n8n execution stop-many [flags] ``` @@ -29,16 +33,17 @@ n8n execution stop-many [flags] ### Options ``` - --all stop matching executions across every accessible workflow (cannot combine with --workflow-id) - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - -h, --help help for stop-many - --output string output format: text or json (JSON contains the number stopped) (default "text") - --started-after string only executions started after this RFC3339 timestamp, e.g. 2026-09-17T00:00:00Z (default: no lower bound) - --started-before string only executions started before this RFC3339 timestamp, e.g. 2026-09-18T00:00:00Z (default: no upper bound) - --status stringArray status to stop: queued, running, or waiting; repeatable (at least one required) - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) - --workflow-id string only executions of this workflow, from 'n8n workflow list' (required unless --all) - --yes confirm stopping every match without prompting (required when stdin is not interactive) + --all stop matching executions across every accessible workflow (cannot combine with --workflow-id) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for stop-many + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) + --output string output format: text or json (JSON contains the number stopped) (default "text") + --started-after string only executions started after this RFC3339 timestamp, e.g. 2026-09-17T00:00:00Z (default: no lower bound) + --started-before string only executions started before this RFC3339 timestamp, e.g. 2026-09-18T00:00:00Z (default: no upper bound) + --status stringArray status to stop: queued, running, or waiting; repeatable (at least one required) + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --workflow-id string only executions of this workflow, from 'n8n workflow list' (required unless --all) + --yes confirm stopping every match without prompting (required when stdin is not interactive) ``` ### SEE ALSO diff --git a/docs/n8n_execution_stop.md b/docs/n8n_execution_stop.md index f5b1ce3..44376e6 100644 --- a/docs/n8n_execution_stop.md +++ b/docs/n8n_execution_stop.md @@ -11,6 +11,10 @@ execution. A run already finished or otherwise not stoppable returns a conflict. Interactive runs ask for confirmation and non-interactive runs require --yes. The workflow definition is untouched. Requires execution:stop. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + ``` n8n execution stop [flags] ``` @@ -26,11 +30,12 @@ n8n execution stop [flags] ### Options ``` - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - -h, --help help for stop - --output string output format: text or json (JSON is the resulting stop state) (default "text") - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) - --yes confirm canceling the execution without prompting (required when stdin is not interactive) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for stop + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) + --output string output format: text or json (JSON is the resulting stop state) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm canceling the execution without prompting (required when stdin is not interactive) ``` ### SEE ALSO diff --git a/docs/n8n_package_import-selection.md b/docs/n8n_package_import-selection.md index 9cc656f..7e0d886 100644 --- a/docs/n8n_package_import-selection.md +++ b/docs/n8n_package_import-selection.md @@ -33,6 +33,11 @@ deleting or when an update changes a workflow's archive state, and the licensed Packages feature. Output is the same import result as 'n8n package import'. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). A retry must send +the same archive under the same file name with the same flags. + ``` n8n package import-selection [flags] ``` @@ -52,6 +57,7 @@ n8n package import-selection [flags] --delete-workflow-id stringArray destination workflow ID to remove from the target project, repeatable; needs workflow:delete and must not match a --workflow-id (default: none) --file string project package archive (.n8np) to import from: a file path, or - for stdin (required; stdin requires --yes) -h, --help help for import-selection + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) --output string output format: text or json (JSON is the full import result) (default "text") --overwrite-deletion-policy string how --delete-workflow-id removes workflows: archive (recoverable) or hard-delete (also drops executions permanently; prefer archive); needs --delete-workflow-id (default: server default archive) --project-id string source project ID as it appears in the package; also the target project ID, created if missing (required) diff --git a/docs/n8n_package_import.md b/docs/n8n_package_import.md index 7e001cf..9b3256c 100644 --- a/docs/n8n_package_import.md +++ b/docs/n8n_package_import.md @@ -30,6 +30,11 @@ credential, variable, tag, data-table, folder, and delete scopes, and the Packages, Variables, and Folders features where the contents require them. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). A retry must send +the same archive under the same file name with the same flags. + ``` n8n package import [flags] ``` @@ -56,6 +61,7 @@ n8n package import [flags] --folder-conflict-policy string existing folder handling: merge, fail, or overwrite; empty follows --project-conflict-policy on project packages, merge otherwise (default: follow) --folder-id string folder within the target project, from 'n8n folder list PROJECT_ID' (default: the project root) -h, --help help for import + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) --missing-node-type-mode string unknown node type handling: fail rejects before anything is written, import-anyway imports without publishing those workflows (default: server default fail) --output string output format: text or json (JSON is the full import result) (default "text") --overwrite-deletion-policy string how folder overwrite removes missing workflows: archive (recoverable) or hard-delete (also drops executions; prefer archive) (default: server default archive) diff --git a/docs/n8n_promotion_apply-continue.md b/docs/n8n_promotion_apply-continue.md index bd3cf0c..599d26b 100644 --- a/docs/n8n_promotion_apply-continue.md +++ b/docs/n8n_promotion_apply-continue.md @@ -28,6 +28,10 @@ mutually exclusive. Interactive runs ask for confirmation; non-interactive runs and stdin input require --yes. JSON returns the server result; text shows counts and the commit after success. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + ``` n8n promotion apply-continue [flags] ``` @@ -49,6 +53,7 @@ n8n promotion apply-continue [flags] --expected-config-id string reviewed config ID, 1 to 36 characters (default: omitted; requires expected branch and commit) --expected-from string changes or blocked-apply JSON file, or - for stdin (default: explicit expected-source flags; stdin requires --yes) -h, --help help for apply-continue + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) --input string request JSON file path or - for stdin, maximum 1 MiB (default: use document flags; stdin requires --yes) --output string output format: text or json (default: text; JSON is the full server result) (default "text") --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) diff --git a/docs/n8n_promotion_apply.md b/docs/n8n_promotion_apply.md index 98b1104..b4f9383 100644 --- a/docs/n8n_promotion_apply.md +++ b/docs/n8n_promotion_apply.md @@ -27,6 +27,10 @@ Exit codes: 0 applied, 3 blocked, 4 source-changed, 1 any other error or an unknown status. --output json prints the full result on stdout in every status; the next step goes to stderr. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + ``` n8n promotion apply [flags] ``` @@ -42,11 +46,12 @@ n8n promotion apply [flags] ### Options ``` - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - -h, --help help for apply - --output string output format: text or json (JSON is the full apply result: status, git, and counts or preflight) (default "text") - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) - --yes confirm overwriting instance content from the remote without prompting (required when stdin is not interactive) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + -h, --help help for apply + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) + --output string output format: text or json (JSON is the full apply result: status, git, and counts or preflight) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm overwriting instance content from the remote without prompting (required when stdin is not interactive) ``` ### SEE ALSO diff --git a/docs/n8n_promotion_project_apply-continue.md b/docs/n8n_promotion_project_apply-continue.md index 0c4c7c7..8b99bec 100644 --- a/docs/n8n_promotion_project_apply-continue.md +++ b/docs/n8n_promotion_project_apply-continue.md @@ -31,6 +31,10 @@ mutually exclusive. Interactive runs ask for confirmation; non-interactive runs and stdin input require --yes. JSON returns the server result; text shows counts and the commit after success. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + ``` n8n promotion project apply-continue [flags] ``` @@ -52,6 +56,7 @@ n8n promotion project apply-continue [flags] --expected-config-id string reviewed config ID, 1 to 36 characters (default: omitted; requires expected branch and commit) --expected-from string changes or blocked-apply JSON file, or - for stdin (default: explicit expected-source flags; stdin requires --yes) -h, --help help for apply-continue + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) --input string request JSON file path or - for stdin, maximum 1 MiB (default: use document flags; stdin requires --yes) --output string output format: text or json (default: text; JSON is the full server result) (default "text") --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) diff --git a/docs/n8n_promotion_project_apply.md b/docs/n8n_promotion_project_apply.md index 4d6c317..54bbcde 100644 --- a/docs/n8n_promotion_project_apply.md +++ b/docs/n8n_promotion_project_apply.md @@ -25,6 +25,10 @@ mutually exclusive. Interactive runs ask for confirmation; non-interactive runs and stdin input require --yes. JSON returns the server result; text shows counts and the commit after success. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + ``` n8n promotion project apply [flags] ``` @@ -45,6 +49,7 @@ n8n promotion project apply [flags] --expected-config-id string reviewed config ID, 1 to 36 characters (default: omitted; requires expected branch and commit) --expected-from string changes or blocked-apply JSON file, or - for stdin (default: explicit expected-source flags; stdin requires --yes) -h, --help help for apply + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) --input string request JSON file path or - for stdin, maximum 1 MiB (default: use document flags; stdin requires --yes) --output string output format: text or json (default: text; JSON is the full server result) (default "text") --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) diff --git a/docs/n8n_promotion_project_promote.md b/docs/n8n_promotion_project_promote.md index 2fb5c76..f81626d 100644 --- a/docs/n8n_promotion_project_promote.md +++ b/docs/n8n_promotion_project_promote.md @@ -19,6 +19,10 @@ mutually exclusive. Interactive runs ask for confirmation; non-interactive runs and stdin input require --yes. JSON returns the server result; text shows counts and the commit after success. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + ``` n8n promotion project promote [flags] ``` @@ -36,6 +40,7 @@ n8n promotion project promote [flags] --commit-message string commit message, 1 to 1000 characters (default: server-generated message) --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') -h, --help help for promote + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) --input string request JSON file path or - for stdin, maximum 1 MiB (default: use document flags; stdin requires --yes) --output string output format: text or json (default: text; JSON is the full server result) (default "text") --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) diff --git a/docs/n8n_promotion_promote.md b/docs/n8n_promotion_promote.md index 3da258e..f4e9ad9 100644 --- a/docs/n8n_promotion_promote.md +++ b/docs/n8n_promotion_promote.md @@ -18,6 +18,10 @@ pushed; --force pushes anyway and rewrites remote history. This mutates the remote branch. Interactive runs ask for confirmation and non-interactive runs require --yes. Requires gitConnection:push. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + ``` n8n promotion promote [flags] ``` @@ -33,13 +37,14 @@ n8n promotion promote [flags] ### Options ``` - --commit-message string commit message for the promote, 1 to 1000 characters (required) - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - --force promote even when the remote would reject it, rewriting remote history (default: reject a rejected promote with 409) - -h, --help help for promote - --output string output format: text or json (JSON is the promote result with counts and commit) (default "text") - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) - --yes confirm promoting every team project to the remote without prompting (required when stdin is not interactive) + --commit-message string commit message for the promote, 1 to 1000 characters (required) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --force promote even when the remote would reject it, rewriting remote history (default: reject a rejected promote with 409) + -h, --help help for promote + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) + --output string output format: text or json (JSON is the promote result with counts and commit) (default "text") + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --yes confirm promoting every team project to the remote without prompting (required when stdin is not interactive) ``` ### SEE ALSO diff --git a/docs/n8n_workflow_create.md b/docs/n8n_workflow_create.md index 60d3460..984ea1d 100644 --- a/docs/n8n_workflow_create.md +++ b/docs/n8n_workflow_create.md @@ -18,6 +18,10 @@ override what the document says. A created workflow is never published: publish it with 'n8n workflow publish'. Requires workflow:create. +--idempotency-key KEY makes a retry after a timeout or lost response safe: +the same request with the same key returns the first result instead of +running again (auto generates a key and prints it on stderr). + ``` n8n workflow create [flags] ``` @@ -30,6 +34,7 @@ n8n workflow create [flags] n8n workflow create --input - < workflow.json n8n workflow create --input workflow.json --name "Invoice sync copy" --project-id PROJECT_ID n8n workflow create --name Scratch --output json + n8n workflow create --input workflow.json --idempotency-key deploy-invoice-sync-v3 ``` ### Options @@ -37,6 +42,7 @@ n8n workflow create [flags] ``` --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') -h, --help help for create + --idempotency-key string retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency) --input string workflow definition as JSON: a file path, or - for stdin (default: an empty workflow built from --name) --name string workflow name; overrides the name in --input (required when --input is absent) --output string output format: text or json (JSON is the created workflow) (default "text") diff --git a/internal/cli/datatable.go b/internal/cli/datatable.go index c4a6652..e83271d 100644 --- a/internal/cli/datatable.go +++ b/internal/cli/datatable.go @@ -684,11 +684,12 @@ func writeDataTableRows(w io.Writer, rows []n8n.DataTableRow) error { } type dataTableRowInsertFlags struct { - instance instanceFlags - set []string - input string - returnType string - output string + instance instanceFlags + set []string + input string + returnType string + output string + idempotency idempotencyFlag } func newDataTableRowInsertCommand(opts Options) *cobra.Command { @@ -704,10 +705,11 @@ func newDataTableRowInsertCommand(opts Options) *cobra.Command { "must already exist; add them with 'n8n data-table column create'. --return\n" + "selects what comes back: count, the inserted ids, or the full rows. The whole\n" + "batch is one request, so the API accepts or rejects it as a whole. Requires\n" + - "dataTableRow:create.", + "dataTableRow:create.\n\n" + + idempotencyHelp, Example: " n8n data-table row insert TABLE_ID --set email=a@example.com --set age=30\n" + " n8n data-table row insert TABLE_ID --set email=b@example.com --return all --output json\n" + - " n8n data-table row insert TABLE_ID --input rows.json --return id\n" + + " n8n data-table row insert TABLE_ID --input rows.json --return id --idempotency-key auto\n" + " printf '%s\\n' '[{\"email\":\"c@example.com\"}]' | n8n data-table row insert TABLE_ID --input -", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { @@ -719,6 +721,7 @@ func newDataTableRowInsertCommand(opts Options) *cobra.Command { cmd.Flags().StringVar(&f.input, "input", "", "row JSON array or object, from a file path or - for stdin (cannot combine with --set; maximum 1 MiB)") cmd.Flags().StringVar(&f.returnType, "return", "", "what the API returns: count, id or all (default: the server default of count)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON preserves the count, ids and rows the API sent)") + f.idempotency.register(cmd) return cmd } @@ -737,12 +740,18 @@ func runDataTableRowInsert(ctx context.Context, opts Options, tableID string, f if err := request.Validate(); err != nil { return err } + if err := f.idempotency.validate(); err != nil { + return err + } client, resolution, err := opts.dataTableClient(f.instance) if err != nil { return err } - result, err := client.InsertDataTableRows(ctx, tableID, request) + result, err := client.InsertDataTableRows(ctx, tableID, request, f.idempotency.resolve(opts.Streams.Err)...) if err != nil { + if refused := f.idempotency.refusal(err, resolution); refused != nil { + return refused + } return dataTableAPIError(err, resolution, "row insert") } if f.output == outputJSON { @@ -812,6 +821,9 @@ type rowWriteFlags struct { returnData bool dryRun bool output string + // idempotency is registered by upsert only: update is a PATCH, which the + // API does not deduplicate. + idempotency idempotencyFlag } func (f *rowWriteFlags) register(cmd *cobra.Command) { @@ -918,7 +930,8 @@ func newDataTableRowUpsertCommand(opts Options) *cobra.Command { "with repeatable --set COLUMN=VALUE or a JSON object through --input.\n\n" + "The inserted row is built from the values given, not from the filter, so\n" + "include the matched column in --set when the new row should carry it. Use\n" + - "--dry-run to see what would happen first. Requires dataTableRow:upsert.", + "--dry-run to see what would happen first. Requires dataTableRow:upsert.\n\n" + + idempotencyHelp, Example: " n8n data-table row upsert TABLE_ID --where email=a@example.com --set email=a@example.com --set name=Jane\n" + " n8n data-table row upsert TABLE_ID --where email=a@example.com --set name=Jane --return-data\n" + " n8n data-table row upsert TABLE_ID --where email=a@example.com --set name=Jane --dry-run --output json", @@ -928,6 +941,7 @@ func newDataTableRowUpsertCommand(opts Options) *cobra.Command { }, } f.register(cmd) + f.idempotency.register(cmd) return cmd } @@ -955,12 +969,18 @@ func runDataTableRowUpsert(ctx context.Context, opts Options, tableID string, f if err := request.Validate(); err != nil { return err } + if err := f.idempotency.validate(); err != nil { + return err + } client, resolution, err := opts.dataTableClient(f.instance) if err != nil { return err } - result, err := client.UpsertDataTableRow(ctx, tableID, request) + result, err := client.UpsertDataTableRow(ctx, tableID, request, f.idempotency.resolve(opts.Streams.Err)...) if err != nil { + if refused := f.idempotency.refusal(err, resolution); refused != nil { + return refused + } return dataTableAPIError(err, resolution, "row upsert") } return writeRowMutation(opts, resolution, tableID, "row upserted", f.dryRun, result, f.output) diff --git a/internal/cli/execution.go b/internal/cli/execution.go index 19d2f62..c886d49 100644 --- a/internal/cli/execution.go +++ b/internal/cli/execution.go @@ -449,6 +449,7 @@ type executionStopManyFlags struct { startedBefore string yes bool output string + idempotency idempotencyFlag } func newExecutionStopManyCommand(opts Options) *cobra.Command { @@ -463,7 +464,8 @@ func newExecutionStopManyCommand(opts Options) *cobra.Command { "workflows globally by accident; the literal workflow ID 'all' is rejected, use\n" + "--all instead. Stopping is irreversible for each matched run, though a failed\n" + "or canceled run may later be retried. Interactive runs ask for confirmation and\n" + - "non-interactive runs require --yes. Requires execution:stop.", + "non-interactive runs require --yes. Requires execution:stop.\n\n" + + idempotencyHelp, Example: " n8n execution stop-many --status running --workflow-id WORKFLOW_ID\n" + " n8n execution stop-many --status queued --status waiting --all --yes\n" + " n8n execution stop-many --status running --workflow-id WORKFLOW_ID --started-after 2026-09-17T00:00:00Z --yes --output json", @@ -480,6 +482,7 @@ func newExecutionStopManyCommand(opts Options) *cobra.Command { cmd.Flags().StringVar(&f.startedBefore, "started-before", "", "only executions started before this RFC3339 timestamp, e.g. 2026-09-18T00:00:00Z (default: no upper bound)") cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm stopping every match without prompting (required when stdin is not interactive)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON contains the number stopped)") + f.idempotency.register(cmd) return cmd } @@ -505,6 +508,9 @@ func runExecutionStopMany(ctx context.Context, opts Options, f executionStopMany if !f.all && strings.TrimSpace(f.workflowID) == "" { return fmt.Errorf("--workflow-id or --all is required: pass the workflow ID to scope the stop, or --all to stop across every accessible workflow") } + if err := f.idempotency.validate(); err != nil { + return err + } if f.all { request.WorkflowID = "" } @@ -520,8 +526,11 @@ func runExecutionStopMany(ctx context.Context, opts Options, f executionStopMany if err := opts.confirmer(f.yes).Confirm(question); err != nil { return err } - result, err := client.StopManyExecutions(ctx, request) + result, err := client.StopManyExecutions(ctx, request, f.idempotency.resolve(opts.Streams.Err)...) if err != nil { + if refused := f.idempotency.refusal(err, resolution); refused != nil { + return refused + } return executionAPIError(err, resolution, "", "stop") } if f.output == outputJSON { @@ -534,8 +543,15 @@ func runExecutionStopMany(ctx context.Context, opts Options, f executionStopMany return tw.Flush() } +type executionStopFlags struct { + instance instanceFlags + yes bool + output string + idempotency idempotencyFlag +} + func newExecutionStopCommand(opts Options) *cobra.Command { - var f executionConfirmedFlags + var f executionStopFlags cmd := &cobra.Command{ Use: "stop ", Short: "Stop one queued, running, or waiting execution", @@ -543,7 +559,8 @@ func newExecutionStopCommand(opts Options) *cobra.Command { "use 'n8n execution retry ID' afterwards when it should run again as a new\n" + "execution. A run already finished or otherwise not stoppable returns a conflict.\n\n" + "Interactive runs ask for confirmation and non-interactive runs require --yes.\n" + - "The workflow definition is untouched. Requires execution:stop.", + "The workflow definition is untouched. Requires execution:stop.\n\n" + + idempotencyHelp, Example: " n8n execution stop EXECUTION_ID\n" + " n8n execution stop EXECUTION_ID --yes\n" + " n8n execution stop EXECUTION_ID --yes --output json", @@ -555,16 +572,20 @@ func newExecutionStopCommand(opts Options) *cobra.Command { f.instance.register(cmd) cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm canceling the execution without prompting (required when stdin is not interactive)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the resulting stop state)") + f.idempotency.register(cmd) return cmd } -func runExecutionStop(ctx context.Context, opts Options, id string, f executionConfirmedFlags) error { +func runExecutionStop(ctx context.Context, opts Options, id string, f executionStopFlags) error { if err := validateOutput(f.output); err != nil { return err } if err := validateExecutionArgument(id); err != nil { return err } + if err := f.idempotency.validate(); err != nil { + return err + } client, resolution, err := opts.apiClient(f.instance) if err != nil { return err @@ -573,8 +594,11 @@ func runExecutionStop(ctx context.Context, opts Options, id string, f executionC if err := opts.confirmer(f.yes).Confirm(question); err != nil { return err } - result, err := client.StopExecution(ctx, id) + result, err := client.StopExecution(ctx, id, f.idempotency.resolve(opts.Streams.Err)...) if err != nil { + if refused := f.idempotency.refusal(err, resolution); refused != nil { + return refused + } if n8n.IsConflict(err) { return fmt.Errorf("%s cannot stop execution %q (409): it is already finished or is not in a stoppable state", resolution.URL, id) } @@ -597,6 +621,7 @@ type executionRetryFlags struct { instance instanceFlags latestWorkflow bool output string + idempotency idempotencyFlag } func newExecutionRetryCommand(opts Options) *cobra.Command { @@ -610,10 +635,11 @@ func newExecutionRetryCommand(opts Options) *cobra.Command { "the instance.\n\n" + "The original execution is retained and the response identifies the new run. A\n" + "run that cannot be retried returns a conflict. This starts workflow work and may\n" + - "repeat its external side effects. Requires execution:retry.", + "repeat its external side effects. Requires execution:retry.\n\n" + + idempotencyHelp, Example: " n8n execution retry EXECUTION_ID\n" + " n8n execution retry EXECUTION_ID --latest-workflow\n" + - " n8n execution retry EXECUTION_ID --output json", + " n8n execution retry EXECUTION_ID --idempotency-key auto --output json", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { return runExecutionRetry(cmd.Context(), opts, args[0], f) @@ -622,6 +648,7 @@ func newExecutionRetryCommand(opts Options) *cobra.Command { f.instance.register(cmd) cmd.Flags().BoolVar(&f.latestWorkflow, "latest-workflow", false, "run the workflow currently saved instead of the definition stored with the original execution (default: stored definition)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the newly started execution)") + f.idempotency.register(cmd) return cmd } @@ -632,12 +659,18 @@ func runExecutionRetry(ctx context.Context, opts Options, id string, f execution if err := validateExecutionArgument(id); err != nil { return err } + if err := f.idempotency.validate(); err != nil { + return err + } client, resolution, err := opts.apiClient(f.instance) if err != nil { return err } - execution, err := client.RetryExecution(ctx, id, n8n.RetryExecutionOptions{LoadWorkflow: f.latestWorkflow}) + execution, err := client.RetryExecution(ctx, id, n8n.RetryExecutionOptions{LoadWorkflow: f.latestWorkflow}, f.idempotency.resolve(opts.Streams.Err)...) if err != nil { + if refused := f.idempotency.refusal(err, resolution); refused != nil { + return refused + } if n8n.IsConflict(err) { return fmt.Errorf("%s cannot retry execution %q (409): its state or stored data does not permit a retry", resolution.URL, id) } diff --git a/internal/cli/idempotency.go b/internal/cli/idempotency.go new file mode 100644 index 0000000..5bba35b --- /dev/null +++ b/internal/cli/idempotency.go @@ -0,0 +1,71 @@ +package cli + +import ( + "fmt" + "io" + + "github.com/spf13/cobra" + + "github.com/SomeoneWithOptions/n8n-cli/internal/config" + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" +) + +// idempotencyAuto asks for a generated key instead of a literal one. +const idempotencyAuto = "auto" + +// idempotencyHelp is the sentence a command's Long adds for the flag. +const idempotencyHelp = "--idempotency-key KEY makes a retry after a timeout or lost response safe:\n" + + "the same request with the same key returns the first result instead of\n" + + "running again (auto generates a key and prints it on stderr)." + +// idempotencyFlag is the --idempotency-key flag of a POST command whose repeat +// would start work or write content twice. The CLI never retries on its own: +// the key only makes the caller's own retry safe. +type idempotencyFlag struct { + key string +} + +func (f *idempotencyFlag) register(cmd *cobra.Command) { + cmd.Flags().StringVar(&f.key, "idempotency-key", "", "retry key sent as the Idempotency-Key header: 1 to 128 visible ASCII characters, or auto for a random UUID printed on stderr; rerun the same command with the same key to get the first result instead of a second run (default: none, no idempotency)") +} + +// validate checks a literal key before any prompt or request. +func (f idempotencyFlag) validate() error { + if f.key == "" || f.key == idempotencyAuto { + return nil + } + if err := n8n.ValidateIdempotencyKey(f.key); err != nil { + return fmt.Errorf("--idempotency-key: %w", err) + } + return nil +} + +// resolve turns the flag into call options right before the request. auto +// becomes a fresh key, announced on stderr first so an interrupted or failed +// run can be retried with it. +func (f *idempotencyFlag) resolve(stderr io.Writer) []n8n.CallOption { + switch f.key { + case "": + return nil + case idempotencyAuto: + f.key = n8n.NewIdempotencyKey() + fmt.Fprintf(stderr, "Idempotency key: %s (to retry this exact request, rerun with --idempotency-key %s)\n", f.key, f.key) + } + return []n8n.CallOption{n8n.IdempotencyKey(f.key)} +} + +// refusal reports the two failures the key itself causes, or nil when err is +// something else and the command's own error handling applies. It runs before +// that handling because the same status codes also mean resource conflicts. +func (f idempotencyFlag) refusal(err error, resolution config.Resolution) error { + if f.key == "" { + return nil + } + switch { + case n8n.IsIdempotencyMismatch(err): + return fmt.Errorf("%s refused idempotency key %q (422): the key was already used with a different request; rerun with a new key, e.g. --idempotency-key auto\n server said: %w", resolution.URL, f.key, err) + case n8n.IsIdempotencyInProgress(err): + return fmt.Errorf("%s is still running the original request for idempotency key %q (409): retry later with the same key to get its result without running it twice\n server said: %w", resolution.URL, f.key, err) + } + return nil +} diff --git a/internal/cli/idempotency_test.go b/internal/cli/idempotency_test.go new file mode 100644 index 0000000..08446ed --- /dev/null +++ b/internal/cli/idempotency_test.go @@ -0,0 +1,185 @@ +package cli + +import ( + "encoding/json" + "net/http" + "regexp" + "strings" + "testing" + + "github.com/SomeoneWithOptions/n8n-cli/internal/n8n" +) + +const ( + cliIdempotencyInProgress = `{"message":"A request with this Idempotency-Key is already in progress."}` + cliIdempotencyMismatch = `{"message":"This Idempotency-Key was already used with a different request."}` +) + +// idempotentCommand is one command that takes --idempotency-key, with the +// arguments and response a successful non-interactive run needs. +type idempotentCommand struct { + name string + args func(t *testing.T) []string + path string + response string +} + +func idempotentCommands() []idempotentCommand { + fixed := func(args ...string) func(*testing.T) []string { + return func(*testing.T) []string { return args } + } + expected := []string{"--expected-config-id", "cfg", "--expected-branch", "main", "--expected-commit", cliSelectionSHA} + applied := `{"status":"applied","counts":{},"warnings":[]}` + return []idempotentCommand{ + {"execution stop", fixed("execution", "stop", "1000", "--yes"), "/executions/1000/stop", `{"status":"canceled"}`}, + {"execution stop-many", fixed("execution", "stop-many", "--status", "running", "--workflow-id", "wf-1", "--yes"), "/executions/stop", `{"stopped":1}`}, + {"execution retry", fixed("execution", "retry", "1000"), "/executions/1000/retry", cliExecution}, + {"workflow create", fixed("workflow", "create", "--name", "Scratch"), "/workflows", `{"id":"wf-1","name":"Scratch","nodes":[],"connections":{}}`}, + {"row insert", fixed("data-table", "row", "insert", "dt-1", "--set", "age=30"), "/data-tables/dt-1/rows", `{"success":true,"insertedRows":1}`}, + {"row upsert", fixed("data-table", "row", "upsert", "dt-1", "--where", "email=a@example.com", "--set", "age=31"), "/data-tables/dt-1/rows/upsert", `true`}, + {"promotion promote", fixed("promotion", "promote", "conn-1", "--commit-message", "sync", "--yes"), "/promotions/connections/conn-1/promote", cliPromotionPromoteBody}, + {"promotion apply", fixed("promotion", "apply", "conn-1", "--yes"), "/promotions/connections/conn-1/apply", applied}, + {"promotion apply-continue", fixed(append([]string{"promotion", "apply-continue", "conn-1", "--yes"}, expected...)...), "/promotions/connections/conn-1/apply/continue", applied}, + {"project apply", fixed("promotion", "project", "apply", "proj-1", "--workflow-id", "wf", "--yes"), "/promotions/projects/proj-1/apply", applied}, + {"project apply-continue", fixed(append([]string{"promotion", "project", "apply-continue", "proj-1", "--workflow-id", "wf", "--yes"}, expected...)...), "/promotions/projects/proj-1/apply/continue", applied}, + {"project promote", fixed("promotion", "project", "promote", "proj-1", "--workflow-id", "wf", "--yes"), "/promotions/projects/proj-1/promote", cliPromotionPromoteBody}, + {"package import", func(t *testing.T) []string { + return []string{"package", "import", "--file", writePackageArchive(t, cliPackageArchive), "--workflow-conflict-policy", "fail", "--yes"} + }, n8n.N8nPackageImportPath, cliPackageImportResult}, + {"package import-selection", func(t *testing.T) []string { + return []string{"package", "import-selection", "--file", writePackageArchive(t, cliPackageArchive), "--project-id", "p1", "--workflow-id", "wf-1", "--yes"} + }, n8n.N8nPackageImportSelectionPath, cliPackageImportResult}, + } +} + +func TestIdempotencyKeyHeaderOnlyWhenSet(t *testing.T) { + for _, tc := range idempotentCommands() { + t.Run(tc.name, func(t *testing.T) { + f := newFixture(t) + f.login() + f.interactive = false + f.body = tc.response + args := tc.args(t) + + got := f.run(args...) + if got.code != ExitSuccess { + t.Fatalf("without key: exit = %d, stderr: %s", got.code, got.stderr) + } + if values, sent := f.lastRequest().Header[n8n.IdempotencyKeyHeader]; sent { + t.Errorf("without key: %s = %q, want no header", n8n.IdempotencyKeyHeader, values) + } + plainBody := f.lastBody() + + got = f.run(append(args, "--idempotency-key", "cli-key-1")...) + if got.code != ExitSuccess { + t.Fatalf("with key: exit = %d, stderr: %s", got.code, got.stderr) + } + req := f.lastRequest() + if req.Method != http.MethodPost || req.URL.EscapedPath() != n8n.BasePath+tc.path { + t.Errorf("request = %s %s, want POST %s", req.Method, req.URL.EscapedPath(), n8n.BasePath+tc.path) + } + if key := req.Header.Get(n8n.IdempotencyKeyHeader); key != "cli-key-1" { + t.Errorf("%s = %q, want cli-key-1", n8n.IdempotencyKeyHeader, key) + } + if strings.Contains(got.stderr, "Idempotency key:") { + t.Errorf("stderr = %q, want no announcement for a literal key", got.stderr) + } + if !strings.HasPrefix(req.Header.Get("Content-Type"), "multipart/") && f.lastBody() != plainBody { + t.Errorf("body with key = %q, without = %q; the key must not change the body", f.lastBody(), plainBody) + } + }) + } +} + +func TestIdempotencyKeyAutoIsPrintedOnStderr(t *testing.T) { + f := executionFixture(t, cliExecution) + got := f.run("execution", "retry", "1000", "--idempotency-key", "auto", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + sent := f.lastRequest().Header.Get(n8n.IdempotencyKeyHeader) + uuidV4 := regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) + if !uuidV4.MatchString(sent) { + t.Fatalf("%s = %q, want a generated version 4 UUID", n8n.IdempotencyKeyHeader, sent) + } + if !strings.Contains(got.stderr, sent) || !strings.Contains(got.stderr, "--idempotency-key "+sent) { + t.Errorf("stderr = %q, want the generated key and how to retry with it", got.stderr) + } + if strings.Contains(got.stdout, sent) { + t.Errorf("stdout = %q, want the key on stderr only", got.stdout) + } + var execution n8n.Execution + if err := json.Unmarshal([]byte(got.stdout), &execution); err != nil || execution.ID != "1000" { + t.Errorf("stdout = %q, want only the execution JSON (error: %v)", got.stdout, err) + } + + got = f.run("execution", "retry", "1000", "--idempotency-key", "auto") + if again := f.lastRequest().Header.Get(n8n.IdempotencyKeyHeader); again == sent || got.code != ExitSuccess { + t.Errorf("second auto key = %q (exit %d), want a fresh key", again, got.code) + } +} + +func TestIdempotencyKeyInvalidRejectedBeforeTransport(t *testing.T) { + f := newFixture(t) + f.login() + f.interactive = false + for _, tc := range idempotentCommands() { + for _, key := range []string{"two words", strings.Repeat("k", n8n.MaxIdempotencyKeyLength+1), "clé"} { + before := f.requestCount() + got := f.run(append(tc.args(t), "--idempotency-key", key)...) + if got.code != ExitError || !strings.Contains(got.stderr, "--idempotency-key") { + t.Errorf("%s with %q: exit = %d, stderr = %q, want a flag error", tc.name, key, got.code, got.stderr) + } + if f.requestCount() != before { + t.Errorf("%s with %q: request reached the instance", tc.name, key) + } + } + } +} + +func TestIdempotencyRefusalMessages(t *testing.T) { + for _, tc := range idempotentCommands() { + t.Run(tc.name, func(t *testing.T) { + f := newFixture(t) + f.login() + f.interactive = false + args := tc.args(t) + for _, refusal := range []struct { + status int + body string + want []string + notFound string + }{ + {http.StatusConflict, cliIdempotencyInProgress, []string{"(409)", "still running", "retry later with the same key", `"cli-key-1"`, "already in progress"}, "new key"}, + {http.StatusUnprocessableEntity, cliIdempotencyMismatch, []string{"(422)", "different request", "new key", "--idempotency-key auto", `"cli-key-1"`}, "retry later"}, + } { + f.route = func(*http.Request, int) (int, string) { return refusal.status, refusal.body } + got := f.run(append(args, "--idempotency-key", "cli-key-1")...) + if got.code != ExitError { + t.Fatalf("%d: exit = %d, want error; stderr: %s", refusal.status, got.code, got.stderr) + } + for _, want := range refusal.want { + if !strings.Contains(got.stderr, want) { + t.Errorf("%d: stderr = %q, want %q", refusal.status, got.stderr, want) + } + } + if strings.Contains(got.stderr, refusal.notFound) { + t.Errorf("%d: stderr = %q, want no %q", refusal.status, got.stderr, refusal.notFound) + } + } + }) + } +} + +// TestIdempotencyKeyKeepsResourceConflicts checks that a 409 the resource +// itself sends keeps its own diagnostic when a key was set. +func TestIdempotencyKeyKeepsResourceConflicts(t *testing.T) { + f := executionFixture(t, "") + f.route = func(*http.Request, int) (int, string) { + return http.StatusConflict, `{"message":"The execution cannot be retried"}` + } + got := f.run("execution", "retry", "1000", "--idempotency-key", "cli-key-1") + if got.code != ExitError || !strings.Contains(got.stderr, "cannot retry execution") || strings.Contains(got.stderr, "still running") { + t.Errorf("result = %+v, want the retry conflict diagnostic", got) + } +} diff --git a/internal/cli/n8n_package.go b/internal/cli/n8n_package.go index 2189cde..6fe613b 100644 --- a/internal/cli/n8n_package.go +++ b/internal/cli/n8n_package.go @@ -383,6 +383,7 @@ type packageImportFlags struct { tagConflict string yes bool output string + idempotency idempotencyFlag } func newPackageImportCommand(opts Options) *cobra.Command { @@ -413,7 +414,9 @@ func newPackageImportCommand(opts Options) *cobra.Command { "workflow:import plus, depending on the package and the policies,\n" + "credential, variable, tag, data-table, folder, and delete scopes, and\n" + "the Packages, Variables, and Folders features where the contents\n" + - "require them.", + "require them.\n\n" + + idempotencyHelp + " A retry must send\n" + + "the same archive under the same file name with the same flags.", Example: " n8n package import --file workflows.n8np --workflow-conflict-policy new-version --yes\n" + " n8n package import --file project.n8np --workflow-conflict-policy fail --project-id Ox8O54VQrmBrb4qL --yes --output json\n" + " n8n package import --file update.n8np --workflow-conflict-policy skip --workflow-publishing-policy publish-all --yes", @@ -446,6 +449,7 @@ func newPackageImportCommand(opts Options) *cobra.Command { cmd.Flags().StringVar(&f.tagConflict, "tag-conflict-policy", "", "conflicted tag handling: skip, fail, or rename (default: server default skip)") cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm importing, publishing, archiving, deleting, and overwriting without prompting (required when stdin is not interactive)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the full import result)") + f.idempotency.register(cmd) return cmd } @@ -484,6 +488,9 @@ func runPackageImport(ctx context.Context, opts Options, f packageImportFlags) e if err := request.Validate(); err != nil { return err } + if err := f.idempotency.validate(); err != nil { + return err + } client, resolution, err := opts.apiClient(f.instance) if err != nil { return err @@ -496,8 +503,11 @@ func runPackageImport(ctx context.Context, opts Options, f packageImportFlags) e return err } defer cleanup() - result, err := client.ImportPackage(ctx, request, archive, filename) + result, err := client.ImportPackage(ctx, request, archive, filename, f.idempotency.resolve(opts.Streams.Err)...) if err != nil { + if refused := f.idempotency.refusal(err, resolution); refused != nil { + return refused + } return packageAPIError(err, resolution, "import", allOf("workflow:import")) } if f.output == outputJSON { @@ -658,6 +668,7 @@ type packageImportSelectionFlags struct { deletionPolicy string yes bool output string + idempotency idempotencyFlag } func newPackageImportSelectionCommand(opts Options) *cobra.Command { @@ -690,7 +701,9 @@ func newPackageImportSelectionCommand(opts Options) *cobra.Command { "stdin cannot answer. Needs workflow:import, plus workflow:delete when\n" + "deleting or when an update changes a workflow's archive state, and the\n" + "licensed Packages feature. Output is the same import result as\n" + - "'n8n package import'.", + "'n8n package import'.\n\n" + + idempotencyHelp + " A retry must send\n" + + "the same archive under the same file name with the same flags.", Example: " n8n package import-selection --file project.n8np --project-id Ox8O54VQrmBrb4qL --workflow-id 2tUt1wbLX592XDdX --workflow-id 7pQr3sTuVwXyZaBc --yes\n" + " n8n package import-selection --file project.n8np --project-id Ox8O54VQrmBrb4qL --workflow-id 2tUt1wbLX592XDdX --delete-workflow-id 9xKp2mNqRzAbCdEf --workflow-conflict-policy fail --output json --yes\n" + " n8n package import-selection --file project.n8np --project-id Ox8O54VQrmBrb4qL --delete-workflow-id 9xKp2mNqRzAbCdEf --overwrite-deletion-policy hard-delete", @@ -709,6 +722,7 @@ func newPackageImportSelectionCommand(opts Options) *cobra.Command { cmd.Flags().StringVar(&f.deletionPolicy, "overwrite-deletion-policy", "", "how --delete-workflow-id removes workflows: archive (recoverable) or hard-delete (also drops executions permanently; prefer archive); needs --delete-workflow-id (default: server default archive)") cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm importing and deleting the listed workflows without prompting (required when stdin is not interactive)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the full import result)") + f.idempotency.register(cmd) return cmd } @@ -739,6 +753,9 @@ func runPackageImportSelection(ctx context.Context, opts Options, f packageImpor if err := request.Validate(); err != nil { return err } + if err := f.idempotency.validate(); err != nil { + return err + } client, resolution, err := opts.apiClient(f.instance) if err != nil { return err @@ -751,8 +768,11 @@ func runPackageImportSelection(ctx context.Context, opts Options, f packageImpor return err } defer cleanup() - result, err := client.ImportPackageSelection(ctx, request, archive, filename) + result, err := client.ImportPackageSelection(ctx, request, archive, filename, f.idempotency.resolve(opts.Streams.Err)...) if err != nil { + if refused := f.idempotency.refusal(err, resolution); refused != nil { + return refused + } need := allOf("workflow:import") if len(request.DeletedWorkflowIDs) > 0 { need = allOf("workflow:import", "workflow:delete") diff --git a/internal/cli/promotion.go b/internal/cli/promotion.go index a6e4fac..72c7020 100644 --- a/internal/cli/promotion.go +++ b/internal/cli/promotion.go @@ -1488,11 +1488,12 @@ func runPromotionProjectRemove(ctx context.Context, opts Options, id, projectID // Promote and apply. type promotionPromoteFlags struct { - instance instanceFlags - commit string - force bool - yes bool - output string + instance instanceFlags + commit string + force bool + yes bool + output string + idempotency idempotencyFlag } func newPromotionPromoteCommand(opts Options) *cobra.Command { @@ -1511,7 +1512,8 @@ func newPromotionPromoteCommand(opts Options) *cobra.Command { "promote the remote would reject is refused with 409 and nothing is\n" + "pushed; --force pushes anyway and rewrites remote history. This\n" + "mutates the remote branch. Interactive runs ask for confirmation and\n" + - "non-interactive runs require --yes. Requires gitConnection:push.", + "non-interactive runs require --yes. Requires gitConnection:push.\n\n" + + idempotencyHelp, Example: " n8n promotion promote CONNECTION_ID --commit-message \"sync workflows\"\n" + " n8n promotion promote CONNECTION_ID --commit-message \"sync\" --force --yes\n" + " n8n promotion promote CONNECTION_ID --commit-message \"sync\" --yes --output json", @@ -1525,6 +1527,7 @@ func newPromotionPromoteCommand(opts Options) *cobra.Command { cmd.Flags().BoolVar(&f.force, "force", false, "promote even when the remote would reject it, rewriting remote history (default: reject a rejected promote with 409)") cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm promoting every team project to the remote without prompting (required when stdin is not interactive)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the promote result with counts and commit)") + f.idempotency.register(cmd) return cmd } @@ -1542,6 +1545,9 @@ func runPromotionPromote(ctx context.Context, opts Options, id string, f promoti if err := request.Validate(); err != nil { return err } + if err := f.idempotency.validate(); err != nil { + return err + } client, resolution, err := opts.apiClient(f.instance) if err != nil { return err @@ -1553,8 +1559,11 @@ func runPromotionPromote(ctx context.Context, opts Options, id string, f promoti if err := opts.confirmer(f.yes).Confirm(question); err != nil { return err } - result, err := client.PromotePackage(ctx, id, request) + result, err := client.PromotePackage(ctx, id, request, f.idempotency.resolve(opts.Streams.Err)...) if err != nil { + if refused := f.idempotency.refusal(err, resolution); refused != nil { + return refused + } return promotionAPIError(err, resolution, "promote", promotionConnectionSubject(id)) } if f.output == outputJSON { @@ -1564,9 +1573,10 @@ func runPromotionPromote(ctx context.Context, opts Options, id string, f promoti } type promotionApplyFlags struct { - instance instanceFlags - yes bool - output string + instance instanceFlags + yes bool + output string + idempotency idempotencyFlag } func newPromotionApplyCommand(opts Options) *cobra.Command { @@ -1592,7 +1602,8 @@ func newPromotionApplyCommand(opts Options) *cobra.Command { "non-interactive runs require --yes. Requires gitConnection:pull.\n\n" + "Exit codes: 0 applied, 3 blocked, 4 source-changed, 1 any other error\n" + "or an unknown status. --output json prints the full result on stdout\n" + - "in every status; the next step goes to stderr.", + "in every status; the next step goes to stderr.\n\n" + + idempotencyHelp, Example: " n8n promotion apply CONNECTION_ID\n" + " n8n promotion apply CONNECTION_ID --yes\n" + " n8n promotion apply CONNECTION_ID --yes --output json", @@ -1604,6 +1615,7 @@ func newPromotionApplyCommand(opts Options) *cobra.Command { f.instance.register(cmd) cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm overwriting instance content from the remote without prompting (required when stdin is not interactive)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the full apply result: status, git, and counts or preflight)") + f.idempotency.register(cmd) return cmd } @@ -1617,6 +1629,9 @@ func runPromotionApply(ctx context.Context, opts Options, id string, f promotion if strings.TrimSpace(id) != id { return fmt.Errorf("connection ID must not start or end with whitespace") } + if err := f.idempotency.validate(); err != nil { + return err + } client, resolution, err := opts.apiClient(f.instance) if err != nil { return err @@ -1625,8 +1640,11 @@ func runPromotionApply(ctx context.Context, opts Options, id string, f promotion if err := opts.confirmer(f.yes).Confirm(question); err != nil { return err } - result, err := client.ApplyPackage(ctx, id) + result, err := client.ApplyPackage(ctx, id, f.idempotency.resolve(opts.Streams.Err)...) if err != nil { + if refused := f.idempotency.refusal(err, resolution); refused != nil { + return refused + } return promotionAPIError(err, resolution, "apply", promotionConnectionSubject(id)) } if f.output == outputJSON { diff --git a/internal/cli/promotion_selection.go b/internal/cli/promotion_selection.go index 8e3b092..fa3e070 100644 --- a/internal/cli/promotion_selection.go +++ b/internal/cli/promotion_selection.go @@ -181,6 +181,7 @@ type promotionSelectionFlags struct { source n8n.PromotionExpectedSource commit string yes, destructive bool + idempotency idempotencyFlag } // Separate commands keep the required source and selection explicit at continue time. @@ -251,7 +252,7 @@ func newPromotionSelectionCommand(opts Options, action string, project bool) *co long += "Read request JSON with --input FILE|- (maximum 1 MiB). Input and document flags are\n" + "mutually exclusive. Interactive runs ask for confirmation; non-interactive\n" + "runs and stdin input require --yes. JSON returns the server result; text\n" + - "shows counts and the commit after success." + "shows counts and the commit after success.\n\n" + idempotencyHelp example := " " + prefix + action + " " + strings.ToUpper(target) + "_ID" flags := "" if project { @@ -266,6 +267,7 @@ func newPromotionSelectionCommand(opts Options, action string, project bool) *co cmd.Flags().StringVar(&f.input, "input", "", "request JSON file path or - for stdin, maximum 1 MiB (default: use document flags; stdin requires --yes)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (default: text; JSON is the full server result)") cmd.Flags().BoolVar(&f.yes, "yes", false, "confirm content changes without prompting (default: prompt; required for non-interactive or stdin input)") + f.idempotency.register(cmd) documentFlags := []string{} if project { cmd.Flags().StringArrayVar(&f.workflowIDs, "workflow-id", nil, "selected workflow ID, 1 to 36 characters; repeat for each ID (default: none; required unless --input is used)") @@ -305,6 +307,9 @@ func newPromotionSelectionCommand(opts Options, action string, project bool) *co if (f.input == "-" || f.expectedFrom == "-") && !f.yes { return fmt.Errorf("stdin input requires --yes because stdin cannot answer confirmation") } + if err := f.idempotency.validate(); err != nil { + return err + } var source *n8n.PromotionExpectedSource if !isPromote && f.input == "" { explicit := cmd.Flags().Changed("expected-config-id") || cmd.Flags().Changed("expected-branch") || cmd.Flags().Changed("expected-commit") @@ -438,11 +443,15 @@ func runPromotionSelection(ctx context.Context, opts Options, id string, f promo if err := opts.confirmer(f.yes).Confirm(question); err != nil { return err } + callOpts := f.idempotency.resolve(opts.Streams.Err) var result *n8n.ApplyPromotionResult switch r := request.(type) { case *n8n.PromoteProjectSelectionRequest: - promoted, err := client.PromoteProjectSelection(ctx, id, *r) + promoted, err := client.PromoteProjectSelection(ctx, id, *r, callOpts...) if err != nil { + if refused := f.idempotency.refusal(err, resolution); refused != nil { + return refused + } return promotionAPIError(err, resolution, action, subject) } if f.output == outputJSON { @@ -450,13 +459,16 @@ func runPromotionSelection(ctx context.Context, opts Options, id string, f promo } return writePromotionPromoteResult(opts, resolution, promoted) case *n8n.ApplyProjectSelectionRequest: - result, err = client.ApplyProjectSelection(ctx, id, *r) + result, err = client.ApplyProjectSelection(ctx, id, *r, callOpts...) case *n8n.ContinueApplyProjectSelectionRequest: - result, err = client.ContinueApplyProjectSelection(ctx, id, *r) + result, err = client.ContinueApplyProjectSelection(ctx, id, *r, callOpts...) case *n8n.ContinueApplyPromotionRequest: - result, err = client.ContinueApplyPackage(ctx, id, *r) + result, err = client.ContinueApplyPackage(ctx, id, *r, callOpts...) } if err != nil { + if refused := f.idempotency.refusal(err, resolution); refused != nil { + return refused + } return promotionAPIError(err, resolution, action, subject) } if f.output == outputJSON { diff --git a/internal/cli/workflow.go b/internal/cli/workflow.go index 5a6f786..5ac8e87 100644 --- a/internal/cli/workflow.go +++ b/internal/cli/workflow.go @@ -334,12 +334,13 @@ func writeWorkflowDetail(opts Options, resolution config.Resolution, workflow *n } type workflowCreateFlags struct { - instance instanceFlags - input string - name string - projectID string - folderID string - output string + instance instanceFlags + input string + name string + projectID string + folderID string + output string + idempotency idempotencyFlag } func newWorkflowCreateCommand(opts Options) *cobra.Command { @@ -357,12 +358,14 @@ func newWorkflowCreateCommand(opts Options) *cobra.Command { "null settings is sent as {}. --name, --project-id and --parent-folder-id\n" + "override what the document says.\n\n" + "A created workflow is never published: publish it with 'n8n workflow publish'.\n" + - "Requires workflow:create.", + "Requires workflow:create.\n\n" + + idempotencyHelp, Example: " n8n workflow create --name \"Invoice sync\"\n" + " n8n workflow create --input workflow.json\n" + " n8n workflow create --input - < workflow.json\n" + " n8n workflow create --input workflow.json --name \"Invoice sync copy\" --project-id PROJECT_ID\n" + - " n8n workflow create --name Scratch --output json", + " n8n workflow create --name Scratch --output json\n" + + " n8n workflow create --input workflow.json --idempotency-key deploy-invoice-sync-v3", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { return runWorkflowCreate(cmd.Context(), opts, f) @@ -374,6 +377,7 @@ func newWorkflowCreateCommand(opts Options) *cobra.Command { cmd.Flags().StringVar(&f.projectID, "project-id", "", "project to create the workflow in, from 'n8n project list' (default: the caller's personal project)") cmd.Flags().StringVar(&f.folderID, "parent-folder-id", "", "folder to create the workflow in, from 'n8n folder list PROJECT_ID' (default: the project root)") cmd.Flags().StringVar(&f.output, "output", outputText, "output format: text or json (JSON is the created workflow)") + f.idempotency.register(cmd) return cmd } @@ -388,12 +392,18 @@ func runWorkflowCreate(ctx context.Context, opts Options, f workflowCreateFlags) if err := doc.Validate(); err != nil { return err } + if err := f.idempotency.validate(); err != nil { + return err + } client, resolution, err := opts.apiClient(f.instance) if err != nil { return err } - created, err := client.CreateWorkflow(ctx, doc) + created, err := client.CreateWorkflow(ctx, doc, f.idempotency.resolve(opts.Streams.Err)...) if err != nil { + if refused := f.idempotency.refusal(err, resolution); refused != nil { + return refused + } return workflowAPIError(err, resolution, "create") } return writeWorkflowResult(opts, resolution, "Created", created, f.output) diff --git a/internal/n8n/client.go b/internal/n8n/client.go index 9028bc4..673bd04 100644 --- a/internal/n8n/client.go +++ b/internal/n8n/client.go @@ -136,6 +136,9 @@ type Request struct { ContentType string // Accept overrides the Accept header. Defaults to application/json. Accept string + // IdempotencyKey is sent as the Idempotency-Key header when set. It is + // validated before transport; see [IdempotencyKey]. + IdempotencyKey string } // Response is the metadata of a successful call. The body is already decoded. @@ -164,6 +167,11 @@ func (c *Client) Do(ctx context.Context, r Request, out any) (*Response, error) if method == "" { method = http.MethodGet } + if r.IdempotencyKey != "" { + if err := ValidateIdempotencyKey(r.IdempotencyKey); err != nil { + return nil, err + } + } endpoint, err := c.resolve(r.Path, r.Query) if err != nil { @@ -196,6 +204,9 @@ func (c *Client) Do(ctx context.Context, r Request, out any) (*Response, error) if contentType != "" { req.Header.Set("Content-Type", contentType) } + if r.IdempotencyKey != "" { + req.Header.Set(IdempotencyKeyHeader, r.IdempotencyKey) + } accept := r.Accept if accept == "" { accept = contentTypeJSON diff --git a/internal/n8n/datatable.go b/internal/n8n/datatable.go index 86f977f..4ee4f39 100644 --- a/internal/n8n/datatable.go +++ b/internal/n8n/datatable.go @@ -652,7 +652,8 @@ func (c *Client) ListDataTableRows(ctx context.Context, tableID string, opts Lis // InsertDataTableRows inserts one or more rows and preserves whichever // response shape the requested return type produced. -func (c *Client) InsertDataTableRows(ctx context.Context, tableID string, req InsertRowsRequest) (*InsertRowsResult, error) { +// opts accepts [IdempotencyKey]. +func (c *Client) InsertDataTableRows(ctx context.Context, tableID string, req InsertRowsRequest, opts ...CallOption) (*InsertRowsResult, error) { if err := validateDataTableID(tableID); err != nil { return nil, err } @@ -660,11 +661,13 @@ func (c *Client) InsertDataTableRows(ctx context.Context, tableID string, req In return nil, err } var result InsertRowsResult - if _, err := c.Do(ctx, Request{ + call := Request{ Method: http.MethodPost, Path: PathJoin("data-tables", tableID, "rows"), Body: req, - }, &result); err != nil { + } + applyCallOptions(&call, opts) + if _, err := c.Do(ctx, call, &result); err != nil { return nil, err } return &result, nil @@ -690,7 +693,8 @@ func (c *Client) UpdateDataTableRows(ctx context.Context, tableID string, req Up } // UpsertDataTableRow updates the row matching the filter or inserts a new one. -func (c *Client) UpsertDataTableRow(ctx context.Context, tableID string, req UpsertRowRequest) (*RowMutationResult, error) { +// opts accepts [IdempotencyKey]. +func (c *Client) UpsertDataTableRow(ctx context.Context, tableID string, req UpsertRowRequest, opts ...CallOption) (*RowMutationResult, error) { if err := validateDataTableID(tableID); err != nil { return nil, err } @@ -698,11 +702,13 @@ func (c *Client) UpsertDataTableRow(ctx context.Context, tableID string, req Ups return nil, err } var result RowMutationResult - if _, err := c.Do(ctx, Request{ + call := Request{ Method: http.MethodPost, Path: PathJoin("data-tables", tableID, "rows", "upsert"), Body: req, - }, &result); err != nil { + } + applyCallOptions(&call, opts) + if _, err := c.Do(ctx, call, &result); err != nil { return nil, err } return &result, nil diff --git a/internal/n8n/execution.go b/internal/n8n/execution.go index 6825606..1142f6e 100644 --- a/internal/n8n/execution.go +++ b/internal/n8n/execution.go @@ -328,47 +328,56 @@ func (c *Client) SetExecutionTags(ctx context.Context, id string, tagIDs []strin } // StopManyExecutions cancels every accessible execution matching request. -func (c *Client) StopManyExecutions(ctx context.Context, request StopManyExecutionsRequest) (*StopManyExecutionsResult, error) { +// opts accepts [IdempotencyKey]. +func (c *Client) StopManyExecutions(ctx context.Context, request StopManyExecutionsRequest, opts ...CallOption) (*StopManyExecutionsResult, error) { if err := request.Validate(); err != nil { return nil, err } var result StopManyExecutionsResult - if _, err := c.Do(ctx, Request{ + req := Request{ Method: http.MethodPost, Path: PathJoin("executions", "stop"), Body: request, - }, &result); err != nil { + } + applyCallOptions(&req, opts) + if _, err := c.Do(ctx, req, &result); err != nil { return nil, err } return &result, nil } // StopExecution cancels one queued, running, or waiting execution. -func (c *Client) StopExecution(ctx context.Context, id string) (*ExecutionStopResult, error) { +// opts accepts [IdempotencyKey]. +func (c *Client) StopExecution(ctx context.Context, id string, opts ...CallOption) (*ExecutionStopResult, error) { if err := validateExecutionID(id); err != nil { return nil, err } var result ExecutionStopResult - if _, err := c.Do(ctx, Request{ + req := Request{ Method: http.MethodPost, Path: PathJoin("executions", id, "stop"), - }, &result); err != nil { + } + applyCallOptions(&req, opts) + if _, err := c.Do(ctx, req, &result); err != nil { return nil, err } return &result, nil } // RetryExecution starts a new execution from an existing failed execution. -func (c *Client) RetryExecution(ctx context.Context, id string, opts RetryExecutionOptions) (*Execution, error) { +// callOpts accepts [IdempotencyKey]. +func (c *Client) RetryExecution(ctx context.Context, id string, opts RetryExecutionOptions, callOpts ...CallOption) (*Execution, error) { if err := validateExecutionID(id); err != nil { return nil, err } var execution Execution - if _, err := c.Do(ctx, Request{ + req := Request{ Method: http.MethodPost, Path: PathJoin("executions", id, "retry"), Body: opts, - }, &execution); err != nil { + } + applyCallOptions(&req, callOpts) + if _, err := c.Do(ctx, req, &execution); err != nil { return nil, err } return &execution, nil diff --git a/internal/n8n/idempotency.go b/internal/n8n/idempotency.go new file mode 100644 index 0000000..ec18b18 --- /dev/null +++ b/internal/n8n/idempotency.go @@ -0,0 +1,117 @@ +package n8n + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" +) + +// IdempotencyKeyHeader is the request header n8n reads a retry key from. +const IdempotencyKeyHeader = "Idempotency-Key" + +// MaxIdempotencyKeyLength is the longest key the API accepts. +const MaxIdempotencyKeyLength = 128 + +// CallOption adjusts one API call without changing its body. Only methods that +// take a variadic CallOption accept one. +type CallOption func(*Request) + +// IdempotencyKey makes a POST safe to retry. n8n runs the first request sent +// with key and answers every later request with the same key and the same +// method, path, query and body with the first successful response, without +// running it again. The same key with a different request is refused with 422 +// ([IsIdempotencyMismatch]); a retry while the first request still runs is +// refused with 409 ([IsIdempotencyInProgress]). A failed request releases the +// key, so the same key runs it again. +// +// The client never retries on its own: the caller decides when to send the +// request again, with the same key and the same body. +func IdempotencyKey(key string) CallOption { + return func(r *Request) { r.IdempotencyKey = key } +} + +// ValidateIdempotencyKey checks the format the API accepts: 1 to 128 visible +// ASCII characters, so no spaces, control characters or non-ASCII text. +func ValidateIdempotencyKey(key string) error { + if key == "" { + return errors.New("idempotency key must not be empty") + } + if len(key) > MaxIdempotencyKeyLength { + return fmt.Errorf("idempotency key must contain at most %d characters, got %d", MaxIdempotencyKeyLength, len(key)) + } + for i := 0; i < len(key); i++ { + if c := key[i]; c < 0x21 || c > 0x7e { + return fmt.Errorf("idempotency key must contain only visible ASCII characters (no spaces): invalid byte %q at position %d", c, i+1) + } + } + return nil +} + +// NewIdempotencyKey returns a random version 4 UUID, for callers that have no +// natural key of their own. +func NewIdempotencyKey() string { + var b [16]byte + // crypto/rand.Read never fails and always fills the buffer. + _, _ = rand.Read(b[:]) + b[6] = b[6]&0x0f | 0x40 // version 4 + b[8] = b[8]&0x3f | 0x80 // RFC 9562 variant + h := hex.EncodeToString(b[:]) + return h[0:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:32] +} + +// IsIdempotencyInProgress reports the 409 n8n answers while the first request +// sent with the same Idempotency-Key is still running. Retry later with the +// same key. Other 409s (a resource conflict) are not matched. +func IsIdempotencyInProgress(err error) bool { + return isIdempotencyRefusal(err, http.StatusConflict) +} + +// IsIdempotencyMismatch reports the 422 n8n answers when an Idempotency-Key was +// already used with a different request. Send it with a new key. Other 422s +// (an invalid request) are not matched. +func IsIdempotencyMismatch(err error) bool { + return isIdempotencyRefusal(err, http.StatusUnprocessableEntity) +} + +func isIdempotencyRefusal(err error, status int) bool { + apiErr, ok := errors.AsType[*APIError](err) + return ok && apiErr.StatusCode == status && mentionsIdempotencyKey(apiErr.Message) +} + +// mentionsIdempotencyKey tells the refusals the idempotency layer sends, which +// name the header, from the resource conflicts the same status codes carry. +func mentionsIdempotencyKey(message string) bool { + return strings.Contains(strings.ToLower(message), strings.ToLower(IdempotencyKeyHeader)) +} + +// isIdempotencyRefusalBody reports whether a raw error body is an +// idempotency refusal rather than the endpoint's own error document. +func isIdempotencyRefusalBody(raw []byte) bool { + var body struct { + Message string `json:"message"` + } + return json.Unmarshal(raw, &body) == nil && mentionsIdempotencyKey(body.Message) +} + +// applyCallOptions folds opts into r. +func applyCallOptions(r *Request, opts []CallOption) { + for _, opt := range opts { + if opt != nil { + opt(r) + } + } +} + +// idempotentBoundary derives a multipart boundary from an idempotency key. +// n8n fingerprints the raw body, so a retry has to send the same bytes, and a +// random boundary would turn every retry into a 422. The hash keeps the +// boundary from occurring in the package bytes by chance. +func idempotentBoundary(key string) string { + sum := sha256.Sum256([]byte("n8n-cli multipart boundary\x00" + key)) + return "n8n-cli-" + hex.EncodeToString(sum[:24]) +} diff --git a/internal/n8n/idempotency_test.go b/internal/n8n/idempotency_test.go new file mode 100644 index 0000000..8884cb6 --- /dev/null +++ b/internal/n8n/idempotency_test.go @@ -0,0 +1,292 @@ +package n8n + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "regexp" + "strings" + "testing" +) + +const ( + idempotencyInProgressBody = `{"message":"A request with this Idempotency-Key is already in progress."}` + idempotencyMismatchBody = `{"message":"This Idempotency-Key was already used with a different request."}` +) + +func TestValidateIdempotencyKey(t *testing.T) { + for _, key := range []string{ + "a", + "deploy-2026-10-22", + "!~", + "0b5d4a0e-8f1c-4c2e-9a77-3f7d2f1a9b10", + strings.Repeat("k", MaxIdempotencyKeyLength), + } { + if err := ValidateIdempotencyKey(key); err != nil { + t.Errorf("ValidateIdempotencyKey(%q) = %v, want nil", key, err) + } + } + for name, key := range map[string]string{ + "empty": "", + "too long": strings.Repeat("k", MaxIdempotencyKeyLength+1), + "space": "two words", + "leading": " key", + "tab": "key\t", + "newline": "key\n", + "delete": "key\x7f", + "non-ascii": "clé", + } { + if err := ValidateIdempotencyKey(key); err == nil { + t.Errorf("%s: ValidateIdempotencyKey(%q) = nil, want error", name, key) + } + } +} + +func TestNewIdempotencyKeyIsRandomUUIDv4(t *testing.T) { + uuidV4 := regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) + first, second := NewIdempotencyKey(), NewIdempotencyKey() + for _, key := range []string{first, second} { + if !uuidV4.MatchString(key) { + t.Errorf("NewIdempotencyKey() = %q, want a version 4 UUID", key) + } + if err := ValidateIdempotencyKey(key); err != nil { + t.Errorf("ValidateIdempotencyKey(%q) = %v", key, err) + } + } + if first == second { + t.Errorf("two keys are both %q, want distinct keys", first) + } +} + +// TestIdempotencyKeyHeader sends every call that accepts the option once with +// a key and once without: the header appears only when set, and the body is +// the same either way. +func TestIdempotencyKeyHeader(t *testing.T) { + message := "sync" + source := selectionSource() + filter := RowFilter{Filters: []RowCondition{{ColumnName: "email", Condition: "eq", Value: json.RawMessage(`"a@example.com"`)}}} + applied := `{"status":"applied","counts":{},"warnings":[]}` + cases := []struct { + name, path, response string + call func(context.Context, *Client, ...CallOption) error + }{ + {"execution stop many", "/executions/stop", `{"stopped":1}`, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.StopManyExecutions(ctx, StopManyExecutionsRequest{Status: []string{"running"}, WorkflowID: "wf-1"}, opts...) + return err + }}, + {"execution stop", "/executions/1000/stop", `{"status":"canceled"}`, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.StopExecution(ctx, "1000", opts...) + return err + }}, + {"execution retry", "/executions/1000/retry", executionResponse, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.RetryExecution(ctx, "1000", RetryExecutionOptions{LoadWorkflow: true}, opts...) + return err + }}, + {"workflow create", "/workflows", `{"id":"wf-1","name":"Invoice sync"}`, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.CreateWorkflow(ctx, writeDocument(), opts...) + return err + }}, + {"row insert", "/data-tables/dt-1/rows", `{"success":true,"insertedRows":1}`, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.InsertDataTableRows(ctx, "dt-1", InsertRowsRequest{Data: []DataTableRow{{"age": json.RawMessage(`30`)}}}, opts...) + return err + }}, + {"row upsert", "/data-tables/dt-1/rows/upsert", `true`, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.UpsertDataTableRow(ctx, "dt-1", UpsertRowRequest{Filter: filter, Data: DataTableRow{"age": json.RawMessage(`31`)}}, opts...) + return err + }}, + {"promote", "/promotions/connections/conn-1/promote", promotionPromoteResultBody, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.PromotePackage(ctx, "conn-1", PromotePromotionRequest{CommitMessage: "sync"}, opts...) + return err + }}, + {"apply", "/promotions/connections/conn-1/apply", applied, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.ApplyPackage(ctx, "conn-1", opts...) + return err + }}, + {"apply continue", "/promotions/connections/conn-1/apply/continue", applied, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.ContinueApplyPackage(ctx, "conn-1", ContinueApplyPromotionRequest{ExpectedSource: source}, opts...) + return err + }}, + {"project apply", "/promotions/projects/proj-1/apply", applied, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.ApplyProjectSelection(ctx, "proj-1", ApplyProjectSelectionRequest{WorkflowIDs: []string{"wf"}}, opts...) + return err + }}, + {"project apply continue", "/promotions/projects/proj-1/apply/continue", applied, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.ContinueApplyProjectSelection(ctx, "proj-1", ContinueApplyProjectSelectionRequest{WorkflowIDs: []string{"wf"}, ExpectedSource: source}, opts...) + return err + }}, + {"project promote", "/promotions/projects/proj-1/promote", promotionPromoteResultBody, func(ctx context.Context, c *Client, opts ...CallOption) error { + _, err := c.PromoteProjectSelection(ctx, "proj-1", PromoteProjectSelectionRequest{WorkflowIDs: []string{"wf"}, CommitMessage: &message}, opts...) + return err + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, tc.response)) + client := server.client(t) + + if err := tc.call(context.Background(), client); err != nil { + t.Fatalf("without key: %v", err) + } + req, plainBody := server.last(t) + if values, sent := req.Header[IdempotencyKeyHeader]; sent { + t.Errorf("without key: %s = %q, want no header", IdempotencyKeyHeader, values) + } + + if err := tc.call(context.Background(), client, IdempotencyKey("retry-key-1")); err != nil { + t.Fatalf("with key: %v", err) + } + req, keyedBody := server.last(t) + if req.Method != http.MethodPost || req.URL.EscapedPath() != BasePath+tc.path { + t.Errorf("request = %s %s, want POST %s", req.Method, req.URL.EscapedPath(), BasePath+tc.path) + } + if got := req.Header.Get(IdempotencyKeyHeader); got != "retry-key-1" { + t.Errorf("%s = %q, want retry-key-1", IdempotencyKeyHeader, got) + } + if got := req.Header.Get(HeaderAPIKey); got != "community-secret" { + t.Errorf("%s = %q, want the API key next to the idempotency key", HeaderAPIKey, got) + } + if keyedBody != plainBody { + t.Errorf("body with key = %q, without = %q; the key must not change the body", keyedBody, plainBody) + } + }) + } +} + +func TestIdempotencyKeyValidatedBeforeTransport(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, `{}`)) + client := server.client(t) + for name, call := range map[string]func() error{ + "Do": func() error { + _, err := client.Do(context.Background(), Request{Method: http.MethodPost, Path: "/tags", IdempotencyKey: "has space"}, nil) + return err + }, + "method": func() error { + _, err := client.StopExecution(context.Background(), "1000", IdempotencyKey(strings.Repeat("k", MaxIdempotencyKeyLength+1))) + return err + }, + "package import": func() error { + _, err := client.ImportPackage(context.Background(), ImportPackageRequest{ + WorkflowConflictPolicy: ImportWorkflowConflictFail, WorkflowIDPolicy: ImportWorkflowIDSource, + }, strings.NewReader(packageArchiveBytes), "workflows.n8np", IdempotencyKey("clé")) + return err + }, + } { + if err := call(); err == nil || !strings.Contains(err.Error(), "idempotency key") { + t.Errorf("%s: err = %v, want an idempotency key validation error", name, err) + } + } + if len(server.requests) != 0 { + t.Errorf("%d requests reached the instance, want none", len(server.requests)) + } +} + +func TestIdempotencyRefusals(t *testing.T) { + cases := []struct { + name string + status int + body string + inProgress, mismatch bool + }{ + {"in progress", http.StatusConflict, idempotencyInProgressBody, true, false}, + {"mismatch", http.StatusUnprocessableEntity, idempotencyMismatchBody, false, true}, + {"resource conflict", http.StatusConflict, `{"message":"Execution is not in a stoppable state"}`, false, false}, + {"validation failure", http.StatusUnprocessableEntity, `{"message":"request/body/name must be string"}`, false, false}, + {"key message on another status", http.StatusBadRequest, `{"message":"Idempotency-Key must be 1 to 128 visible ASCII characters."}`, false, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(tc.status, tc.body)) + _, err := server.client(t).StopExecution(context.Background(), "1000", IdempotencyKey("key-1")) + if err == nil { + t.Fatal("err = nil, want an API error") + } + if got := IsIdempotencyInProgress(err); got != tc.inProgress { + t.Errorf("IsIdempotencyInProgress = %t, want %t", got, tc.inProgress) + } + if got := IsIdempotencyMismatch(err); got != tc.mismatch { + t.Errorf("IsIdempotencyMismatch = %t, want %t", got, tc.mismatch) + } + }) + } + if IsIdempotencyInProgress(errors.New("409 A request with this Idempotency-Key is already in progress.")) { + t.Error("IsIdempotencyInProgress matched a plain error, want APIError only") + } +} + +func TestImportPackageIdempotencyKey(t *testing.T) { + request := ImportPackageRequest{WorkflowConflictPolicy: ImportWorkflowConflictFail, WorkflowIDPolicy: ImportWorkflowIDSource} + selection := ImportPackageSelectionRequest{ProjectID: "p1", WorkflowIDs: []string{"wf-1"}, WorkflowIDPolicy: ImportWorkflowIDSource} + calls := map[string]func(*Client, ...CallOption) error{ + "import": func(c *Client, opts ...CallOption) error { + _, err := c.ImportPackage(context.Background(), request, strings.NewReader(packageArchiveBytes), "workflows.n8np", opts...) + return err + }, + "import selection": func(c *Client, opts ...CallOption) error { + _, err := c.ImportPackageSelection(context.Background(), selection, strings.NewReader(packageArchiveBytes), "project.n8np", opts...) + return err + }, + } + for name, call := range calls { + t.Run(name, func(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, packageImportResultJSON)) + client := server.client(t) + + if err := call(client); err != nil { + t.Fatalf("without key: %v", err) + } + req, _ := server.last(t) + if values, sent := req.Header[IdempotencyKeyHeader]; sent { + t.Errorf("without key: %s = %q, want no header", IdempotencyKeyHeader, values) + } + + // A retry must send the same bytes, so the boundary may not be random. + var bodies []string + for range 2 { + if err := call(client, IdempotencyKey("import-1")); err != nil { + t.Fatalf("with key: %v", err) + } + req, body := server.last(t) + if got := req.Header.Get(IdempotencyKeyHeader); got != "import-1" { + t.Errorf("%s = %q, want import-1", IdempotencyKeyHeader, got) + } + fields, fileBytes, _ := parseMultipartImport(t, req, []byte(body)) + if fileBytes != packageArchiveBytes || len(fields) == 0 { + t.Errorf("multipart = %v fields and %q, want the policies and the archive", fields, fileBytes) + } + bodies = append(bodies, req.Header.Get("Content-Type")+"\n"+body) + } + if bodies[0] != bodies[1] { + t.Error("two requests with the same key sent different bytes, want identical retries") + } + if err := call(client, IdempotencyKey("import-2")); err != nil { + t.Fatalf("with second key: %v", err) + } + req, body := server.last(t) + if req.Header.Get("Content-Type")+"\n"+body == bodies[0] { + t.Error("a different key reused the same boundary, want one derived from the key") + } + }) + } +} + +func TestImportPackageIdempotencyRefusalIsNotImportBlocked(t *testing.T) { + for status, body := range map[int]string{ + http.StatusConflict: idempotencyInProgressBody, + http.StatusUnprocessableEntity: idempotencyMismatchBody, + } { + t.Run(fmt.Sprint(status), func(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(status, body)) + _, err := server.client(t).ImportPackage(context.Background(), ImportPackageRequest{ + WorkflowConflictPolicy: ImportWorkflowConflictFail, WorkflowIDPolicy: ImportWorkflowIDSource, + }, strings.NewReader(packageArchiveBytes), "workflows.n8np", IdempotencyKey("import-1")) + if _, blocked := AsImportBlocked(err); blocked { + t.Errorf("err = %v, want an API error, not an import block", err) + } + if !IsIdempotencyInProgress(err) && !IsIdempotencyMismatch(err) { + t.Errorf("err = %v, want an idempotency refusal", err) + } + }) + } +} diff --git a/internal/n8n/n8n_package.go b/internal/n8n/n8n_package.go index fce7afd..d20830c 100644 --- a/internal/n8n/n8n_package.go +++ b/internal/n8n/n8n_package.go @@ -873,19 +873,24 @@ func IsImportUnprocessable(err error) bool { // and is never buffered whole in memory. The caller confirms first: imports // may publish, archive, hard-delete workflows and executions, create // credential stubs, and overwrite folders, tags, variables, or tables. -func (c *Client) ImportPackage(ctx context.Context, request ImportPackageRequest, packageData io.Reader, filename string) (*ImportPackageResult, error) { +// +// opts accepts [IdempotencyKey]. With a key the multipart boundary is derived +// from it, so a retry with the same key, archive and filename sends the same +// bytes, which the server requires to replay the first result. +func (c *Client) ImportPackage(ctx context.Context, request ImportPackageRequest, packageData io.Reader, filename string, opts ...CallOption) (*ImportPackageResult, error) { if err := request.Validate(); err != nil { return nil, err } - return c.postPackageImport(ctx, N8nPackageImportPath, request.fields(), packageData, filename) + return c.postPackageImport(ctx, N8nPackageImportPath, request.fields(), packageData, filename, opts) } // ImportPackageSelection cherry-picks workflows from one source project of a // project package into the instance project with the same ID, created if // missing. It never removes a workflow the selection omits; it deletes only // request.DeletedWorkflowIDs. The archive streams like [Client.ImportPackage] -// and the result has the same shape. The caller confirms first. -func (c *Client) ImportPackageSelection(ctx context.Context, request ImportPackageSelectionRequest, packageData io.Reader, filename string) (*ImportPackageResult, error) { +// and the result has the same shape. The caller confirms first. opts accepts +// [IdempotencyKey], with the same boundary rule as [Client.ImportPackage]. +func (c *Client) ImportPackageSelection(ctx context.Context, request ImportPackageSelectionRequest, packageData io.Reader, filename string, opts ...CallOption) (*ImportPackageResult, error) { if err := request.Validate(); err != nil { return nil, err } @@ -893,16 +898,24 @@ func (c *Client) ImportPackageSelection(ctx context.Context, request ImportPacka if err != nil { return nil, err } - return c.postPackageImport(ctx, N8nPackageImportSelectionPath, fields, packageData, filename) + return c.postPackageImport(ctx, N8nPackageImportSelectionPath, fields, packageData, filename, opts) } // postPackageImport streams fields and the archive to an import endpoint and // decodes the shared import result. A 409 or 422 becomes an -// [*ImportBlockedError] naming path. -func (c *Client) postPackageImport(ctx context.Context, path string, fields map[string]string, packageData io.Reader, filename string) (*ImportPackageResult, error) { +// [*ImportBlockedError] naming path, except an idempotency refusal, which +// stays an [*APIError]. +func (c *Client) postPackageImport(ctx context.Context, path string, fields map[string]string, packageData io.Reader, filename string, opts []CallOption) (*ImportPackageResult, error) { if packageData == nil { return nil, fmt.Errorf("package archive is required: pass the .n8np bytes") } + var call Request + applyCallOptions(&call, opts) + if call.IdempotencyKey != "" { + if err := ValidateIdempotencyKey(call.IdempotencyKey); err != nil { + return nil, err + } + } if strings.TrimSpace(filename) == "" { filename = DefaultImportPackageFilename } @@ -920,12 +933,22 @@ func (c *Client) postPackageImport(ctx context.Context, path string, fields map[ return nil, err } - body, contentType := multipartImportBody(fields, packageData, filename) + boundary := "" + if call.IdempotencyKey != "" { + boundary = idempotentBoundary(call.IdempotencyKey) + } + body, contentType, err := multipartImportBody(fields, packageData, filename, boundary) + if err != nil { + return nil, err + } req, err := http.NewRequestWithContext(ctx, http.MethodPost, importEndpoint.String(), body) if err != nil { return nil, fmt.Errorf("n8n: build request: %w", err) } req.Header.Set("Content-Type", contentType) + if call.IdempotencyKey != "" { + req.Header.Set(IdempotencyKeyHeader, call.IdempotencyKey) + } req.Header.Set("Accept", contentTypeJSON) req.Header.Set("User-Agent", c.userAgent) if c.auth != nil { @@ -962,10 +985,13 @@ func (c *Client) postPackageImport(ctx context.Context, path string, fields map[ ) if resp.StatusCode == http.StatusConflict || resp.StatusCode == http.StatusUnprocessableEntity { - raw, _, err := readLimited(resp.Body, maxErrorBody) + raw, truncated, err := readLimited(resp.Body, maxErrorBody) if err != nil { return nil, fmt.Errorf("n8n: POST %s: read error response: %w", path, err) } + if isIdempotencyRefusalBody(raw) { + return nil, newAPIError(resp, http.MethodPost, path, raw, truncated) + } return nil, newImportBlockedError(resp, path, raw) } if resp.StatusCode < 200 || resp.StatusCode > 299 { @@ -985,16 +1011,23 @@ func (c *Client) postPackageImport(ctx context.Context, path string, fields map[ // multipartImportBody streams the policy fields and the archive through a // pipe: the writer side runs in a goroutine, so the HTTP transport reads -// while the archive streams without an intermediate buffer. -func multipartImportBody(fields map[string]string, packageData io.Reader, filename string) (io.Reader, string) { +// while the archive streams without an intermediate buffer. An empty boundary +// keeps the random one multipart picks. +func multipartImportBody(fields map[string]string, packageData io.Reader, filename, boundary string) (io.Reader, string, error) { reader, writer := io.Pipe() multipartWriter := multipart.NewWriter(writer) + if boundary != "" { + if err := multipartWriter.SetBoundary(boundary); err != nil { + _ = writer.Close() + return nil, "", fmt.Errorf("n8n: multipart boundary: %w", err) + } + } contentType := multipartWriter.FormDataContentType() go func() { err := writeMultipartImport(multipartWriter, fields, packageData, filename) _ = writer.CloseWithError(err) }() - return reader, contentType + return reader, contentType, nil } func writeMultipartImport(multipartWriter *multipart.Writer, fields map[string]string, packageData io.Reader, filename string) error { diff --git a/internal/n8n/promotion.go b/internal/n8n/promotion.go index 4af11c3..5e1450c 100644 --- a/internal/n8n/promotion.go +++ b/internal/n8n/promotion.go @@ -1179,8 +1179,9 @@ func (c *Client) RemoveProjectFromPromotionConnection(ctx context.Context, id, p } // PromotePackage exports all team projects, commits them and pushes to the -// remote. The promote checkout must be cloned first. -func (c *Client) PromotePackage(ctx context.Context, id string, request PromotePromotionRequest) (*PromotePromotionResult, error) { +// remote. The promote checkout must be cloned first. opts accepts +// [IdempotencyKey]. +func (c *Client) PromotePackage(ctx context.Context, id string, request PromotePromotionRequest, opts ...CallOption) (*PromotePromotionResult, error) { if err := validatePromotionID(id, "promotion connection ID"); err != nil { return nil, err } @@ -1188,11 +1189,13 @@ func (c *Client) PromotePackage(ctx context.Context, id string, request PromoteP return nil, err } var result PromotePromotionResult - if _, err := c.Do(ctx, Request{ + req := Request{ Method: http.MethodPost, Path: PathJoin("promotions", "connections", id, "promote"), Body: request, - }, &result); err != nil { + } + applyCallOptions(&req, opts) + if _, err := c.Do(ctx, req, &result); err != nil { return nil, err } return &result, nil @@ -1200,16 +1203,18 @@ func (c *Client) PromotePackage(ctx context.Context, id string, request PromoteP // ApplyPackage resets the apply checkout to the branch tip and imports // projects into the instance, overwriting to match. The apply checkout must be -// cloned first. -func (c *Client) ApplyPackage(ctx context.Context, id string) (*ApplyPromotionResult, error) { +// cloned first. opts accepts [IdempotencyKey]. +func (c *Client) ApplyPackage(ctx context.Context, id string, opts ...CallOption) (*ApplyPromotionResult, error) { if err := validatePromotionID(id, "promotion connection ID"); err != nil { return nil, err } var result ApplyPromotionResult - if _, err := c.Do(ctx, Request{ + req := Request{ Method: http.MethodPost, Path: PathJoin("promotions", "connections", id, "apply"), - }, &result); err != nil { + } + applyCallOptions(&req, opts) + if _, err := c.Do(ctx, req, &result); err != nil { return nil, err } return &result, nil diff --git a/internal/n8n/promotion_selection.go b/internal/n8n/promotion_selection.go index b2d7d1f..fe2c6bf 100644 --- a/internal/n8n/promotion_selection.go +++ b/internal/n8n/promotion_selection.go @@ -262,48 +262,54 @@ func validatePromotionWorkflowIDs(ids []string) error { } // ContinueApplyPackage rechecks bindings and applies the reviewed full package. -func (c *Client) ContinueApplyPackage(ctx context.Context, id string, request ContinueApplyPromotionRequest) (*ApplyPromotionResult, error) { +// opts accepts [IdempotencyKey]. +func (c *Client) ContinueApplyPackage(ctx context.Context, id string, request ContinueApplyPromotionRequest, opts ...CallOption) (*ApplyPromotionResult, error) { if err := validatePromotionID(id, "promotion connection ID"); err != nil { return nil, err } if err := request.Validate(); err != nil { return nil, err } - return c.applyPromotionSelection(ctx, PathJoin("promotions", "connections", id, "apply", "continue"), request) + return c.applyPromotionSelection(ctx, PathJoin("promotions", "connections", id, "apply", "continue"), request, opts) } // ApplyProjectSelection imports or removes selected workflow IDs from the branch. -func (c *Client) ApplyProjectSelection(ctx context.Context, id string, request ApplyProjectSelectionRequest) (*ApplyPromotionResult, error) { +// opts accepts [IdempotencyKey]. +func (c *Client) ApplyProjectSelection(ctx context.Context, id string, request ApplyProjectSelectionRequest, opts ...CallOption) (*ApplyPromotionResult, error) { if err := validatePromotionID(id, "project ID"); err != nil { return nil, err } if err := request.Validate(); err != nil { return nil, err } - return c.applyPromotionSelection(ctx, PathJoin("promotions", "projects", id, "apply"), request) + return c.applyPromotionSelection(ctx, PathJoin("promotions", "projects", id, "apply"), request, opts) } // ContinueApplyProjectSelection rechecks the reviewed source and full selection. -func (c *Client) ContinueApplyProjectSelection(ctx context.Context, id string, request ContinueApplyProjectSelectionRequest) (*ApplyPromotionResult, error) { +// opts accepts [IdempotencyKey]. +func (c *Client) ContinueApplyProjectSelection(ctx context.Context, id string, request ContinueApplyProjectSelectionRequest, opts ...CallOption) (*ApplyPromotionResult, error) { if err := validatePromotionID(id, "project ID"); err != nil { return nil, err } if err := request.Validate(); err != nil { return nil, err } - return c.applyPromotionSelection(ctx, PathJoin("promotions", "projects", id, "apply", "continue"), request) + return c.applyPromotionSelection(ctx, PathJoin("promotions", "projects", id, "apply", "continue"), request, opts) } -func (c *Client) applyPromotionSelection(ctx context.Context, path string, request any) (*ApplyPromotionResult, error) { +func (c *Client) applyPromotionSelection(ctx context.Context, path string, request any, opts []CallOption) (*ApplyPromotionResult, error) { var result ApplyPromotionResult - if _, err := c.Do(ctx, Request{Method: http.MethodPost, Path: path, Body: request}, &result); err != nil { + req := Request{Method: http.MethodPost, Path: path, Body: request} + applyCallOptions(&req, opts) + if _, err := c.Do(ctx, req, &result); err != nil { return nil, err } return &result, nil } // PromoteProjectSelection exports selected workflow states and pushes the branch. -func (c *Client) PromoteProjectSelection(ctx context.Context, id string, request PromoteProjectSelectionRequest) (*PromotePromotionResult, error) { +// opts accepts [IdempotencyKey]. +func (c *Client) PromoteProjectSelection(ctx context.Context, id string, request PromoteProjectSelectionRequest, opts ...CallOption) (*PromotePromotionResult, error) { if err := validatePromotionID(id, "project ID"); err != nil { return nil, err } @@ -311,7 +317,9 @@ func (c *Client) PromoteProjectSelection(ctx context.Context, id string, request return nil, err } var result PromotePromotionResult - if _, err := c.Do(ctx, Request{Method: http.MethodPost, Path: PathJoin("promotions", "projects", id, "promote"), Body: request}, &result); err != nil { + req := Request{Method: http.MethodPost, Path: PathJoin("promotions", "projects", id, "promote"), Body: request} + applyCallOptions(&req, opts) + if _, err := c.Do(ctx, req, &result); err != nil { return nil, err } return &result, nil diff --git a/internal/n8n/workflow.go b/internal/n8n/workflow.go index b43275e..ddbea45 100644 --- a/internal/n8n/workflow.go +++ b/internal/n8n/workflow.go @@ -522,17 +522,19 @@ func (c *Client) ListWorkflows(ctx context.Context, opts ListWorkflowsOptions) ( // CreateWorkflow creates one workflow from a write document. The document must // already be reduced with [WorkflowDocument.ForCreate]: a read-only field in the -// body is a 400, not an ignored field. -func (c *Client) CreateWorkflow(ctx context.Context, doc WorkflowDocument) (*Workflow, error) { +// body is a 400, not an ignored field. opts accepts [IdempotencyKey]. +func (c *Client) CreateWorkflow(ctx context.Context, doc WorkflowDocument, opts ...CallOption) (*Workflow, error) { if err := doc.Validate(); err != nil { return nil, err } var created Workflow - if _, err := c.Do(ctx, Request{ + req := Request{ Method: http.MethodPost, Path: WorkflowsPath, Body: doc, - }, &created); err != nil { + } + applyCallOptions(&req, opts) + if _, err := c.Do(ctx, req, &created); err != nil { return nil, err } return &created, nil