diff --git a/.github/workflows/reconcile-openapi.yml b/.github/workflows/reconcile-openapi.yml index 3f572dd..ca3c7ce 100644 --- a/.github/workflows/reconcile-openapi.yml +++ b/.github/workflows/reconcile-openapi.yml @@ -166,7 +166,7 @@ jobs: - name: Create pull-request token if: steps.changes.outputs.changed == 'true' id: app-token - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 with: app-id: ${{ secrets.CB_SDK_BOT_APP_ID }} private-key: ${{ secrets.CB_SDK_BOT_PEM_KEY }} @@ -177,7 +177,7 @@ jobs: - name: Create or update reconciliation PR if: steps.changes.outputs.changed == 'true' - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8 + uses: peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8 with: token: ${{ steps.app-token.outputs.token }} base: main diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index 06b9648..dd548b4 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -69,7 +69,7 @@ jobs: - name: Create release PR approval token if: steps.rp.outputs.release_created != 'true' id: release-approval-token - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 with: app-id: ${{ secrets.CB_SDK_BOT_APP_ID }} private-key: ${{ secrets.CB_SDK_BOT_PEM_KEY }} diff --git a/TELEMETRY.md b/TELEMETRY.md index e1b5a0b..cb336e7 100644 --- a/TELEMETRY.md +++ b/TELEMETRY.md @@ -84,7 +84,7 @@ A telemetry request has the following structure: | `pcv` | When available | Product Catalog version (`v1` or `v2`) of the configured site. | | `code_lang` | Code generation | Generated code language, such as `go` or `js`. | | `agent` | When detected | Supported agent runtime: `claude-code`, `cursor`, `codex` (sandboxed runs) or `gemini-cli`, detected from environment variables those tools set. | -| `listen_phase` | `chargebee listen` | Tunnel lifecycle state: `established`, `closed`, or `error`. | +| `listen_phase` | `chargebee listen` | Tunnel lifecycle state: `established` (first connection), `reconnected` (connected again after a drop), `closed`, or `error` (a connection attempt failed, or the tunnel was refused and listen stopped). | | `first_run` | First recorded event only | Date (`YYYY-MM-DD`) the first-run notice was shown. | ## What is Never Collected diff --git a/THIRD_PARTY_NOTICES.txt b/THIRD_PARTY_NOTICES.txt index 7eaff43..bef4dac 100644 --- a/THIRD_PARTY_NOTICES.txt +++ b/THIRD_PARTY_NOTICES.txt @@ -7,12 +7,12 @@ in dist/index.js). This file reproduces each package's license so the notice travels with the code it applies to. It is generated by `bun run src/tools/third-party-notices.ts`; do not edit it by hand. -@chargebee/code-sample-generator@1.1.1 (SEE LICENSE IN LICENSE) +@chargebee/code-sample-generator@1.1.2 (SEE LICENSE IN LICENSE) --------------------------------------------------------------- Licensed under Chargebee's generator EULA. The full text is shipped once, at licenses/code-sample-generator.txt, and is not repeated here. -@clack/core@1.5.1 (MIT) +@clack/core@1.6.0 (MIT) ----------------------- MIT License @@ -24,7 +24,7 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -@clack/prompts@1.8.1 (MIT) +@clack/prompts@1.9.0 (MIT) -------------------------- MIT License @@ -41,7 +41,7 @@ change-case@5.4.4 (MIT) This package ships no LICENSE, LICENCE, or COPYING file. Its package.json declares the SPDX license identifier "MIT". -chargebee@3.35.0 (MIT) +chargebee@3.37.0 (MIT) ---------------------- The MIT License @@ -68,7 +68,7 @@ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -commander@15.0.0 (MIT) +commander@15.1.0 (MIT) ---------------------- (The MIT License) @@ -203,7 +203,7 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -sisteransi@1.0.5 (MIT) +sisteransi@2.0.0 (MIT) ---------------------- MIT License diff --git a/bun.lock b/bun.lock index 28c7975..d076089 100644 --- a/bun.lock +++ b/bun.lock @@ -5,9 +5,9 @@ "": { "name": "chargebee-cli", "devDependencies": { - "@chargebee/code-sample-generator": "1.1.1", + "@chargebee/code-sample-generator": "1.1.2", "@clack/prompts": "^1.8.1", - "@types/bun": "1.4.4", + "@types/bun": "1.4.5", "chargebee": "^3.34.0", "commander": "^15.0.0", "typescript": "^7.0.2", @@ -15,11 +15,11 @@ }, }, "packages": { - "@chargebee/code-sample-generator": ["@chargebee/code-sample-generator@1.1.1", "", { "dependencies": { "change-case": "^5.4.4", "dedent": "^1.7.0", "pluralize": "^8.0.0", "reserved-identifiers": "^1.0.0", "shiki": "^1.23.1" }, "peerDependencies": { "lucide-react": "^0.468.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0" }, "optionalPeers": ["lucide-react", "react", "react-dom"] }, "sha512-0alInhNzO1rmuXMsz6j5kCXKn8l99q3HV3oYmufzr0YrBtFp3yvEtWGwUZYNhmtxXauOJsjsVOTZJv9Hswctrw=="], + "@chargebee/code-sample-generator": ["@chargebee/code-sample-generator@1.1.2", "", { "dependencies": { "change-case": "^5.4.4", "dedent": "^1.7.0", "pluralize": "^8.0.0", "reserved-identifiers": "^1.0.0", "shiki": "^1.23.1" }, "peerDependencies": { "lucide-react": "^0.468.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0" }, "optionalPeers": ["lucide-react", "react", "react-dom"] }, "sha512-rfOpzS43o0Zreh6g+aBzFdc/0azom8+unakKelqd1DdosLwpfxicdhXi0iT/UfwUjRggCEAaaUXkfk6ENG2jCA=="], - "@clack/core": ["@clack/core@1.5.1", "", { "dependencies": { "fast-wrap-ansi": "^0.2.0", "sisteransi": "^1.0.5" } }, "sha512-iHTrHA8MtVuLl2TfZySmcKv1qO2PoyC9Z7pfSDozEuV5vtY3/wcOPKJXlqJ5Oq2Cx5DDGQGAMVx6HZfRRoVEbQ=="], + "@clack/core": ["@clack/core@1.6.0", "", { "dependencies": { "fast-string-width": "^3.0.2", "fast-wrap-ansi": "^0.2.0", "sisteransi": "^2.0.0" } }, "sha512-4GZynIB2IIe431odxesswvWTCP6orvqd6e2b07b3VFWBQRqUqIHc/EPIZwFoKS692QBp+ooPuXKaJV8g4kXuYA=="], - "@clack/prompts": ["@clack/prompts@1.8.1", "", { "dependencies": { "@clack/core": "1.5.1", "fast-string-width": "^3.0.2", "fast-wrap-ansi": "^0.2.0", "sisteransi": "^1.0.5" } }, "sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ=="], + "@clack/prompts": ["@clack/prompts@1.9.0", "", { "dependencies": { "@clack/core": "1.6.0", "fast-string-width": "^3.0.2", "fast-wrap-ansi": "^0.2.0", "sisteransi": "^2.0.0" } }, "sha512-tEj8X2No2A1c9NDnZECxiiJ8TP3vmFlN9tLlLeSaMqVW4tUmVG2R4qpv/eP4zymWxnymYLkLcIYVV0VcWj3RCQ=="], "@shikijs/core": ["@shikijs/core@1.29.2", "", { "dependencies": { "@shikijs/engine-javascript": "1.29.2", "@shikijs/engine-oniguruma": "1.29.2", "@shikijs/types": "1.29.2", "@shikijs/vscode-textmate": "^10.0.1", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.4" } }, "sha512-vju0lY9r27jJfOY4Z7+Rt/nIOjzJpZ3y+nYpqtUZInVoXQ/TJZcfGnNOGnKjFdVZb8qexiCuSlZRKcGfhhTTZQ=="], @@ -35,7 +35,7 @@ "@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.0.2", "", {}, "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg=="], - "@types/bun": ["@types/bun@1.4.4", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="], + "@types/bun": ["@types/bun@1.4.5", "", { "dependencies": { "bun-types": "1.4.5" } }, "sha512-DpgwNI9z0L1S0gtb45QLCWgwCUcMLnsHYMJHQvpNj7erGiCGBvpggltAIeARrtobNMKMuy0UP7i56tKKgwFs/Q=="], "@types/hast": ["@types/hast@3.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ=="], @@ -87,7 +87,7 @@ "@ungap/structured-clone": ["@ungap/structured-clone@1.3.0", "", {}, "sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g=="], - "bun-types": ["bun-types@1.4.4", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="], + "bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], "ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="], @@ -97,11 +97,11 @@ "character-entities-legacy": ["character-entities-legacy@3.0.0", "", {}, "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ=="], - "chargebee": ["chargebee@3.35.0", "", { "dependencies": { "zod": "^4.3.6" }, "peerDependencies": { "@opentelemetry/api": "^1.9.0" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-ioa/XVCOlczBvNDi6wdle6qpdqwuZj39f2SPZIF3op3GiElbO2HcCH1SD6aZ8k+/2U9avpHqw8SW3TJiLwYvSQ=="], + "chargebee": ["chargebee@3.37.0", "", { "dependencies": { "zod": "^4.3.6" }, "peerDependencies": { "@opentelemetry/api": "^1.9.0" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-Er/h1OgwtDkKHWUy79aFFntT1+az8SPz45Hb6czYhk2Cehqag/1v7yuzUoVEr6PvdCOhpTje3JwVwMub8oaBAw=="], "comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="], - "commander": ["commander@15.0.0", "", {}, "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg=="], + "commander": ["commander@15.1.0", "", {}, "sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ=="], "dedent": ["dedent@1.7.2", "", { "peerDependencies": { "babel-plugin-macros": "^3.1.0" }, "optionalPeers": ["babel-plugin-macros"] }, "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA=="], @@ -151,7 +151,7 @@ "shiki": ["shiki@1.29.2", "", { "dependencies": { "@shikijs/core": "1.29.2", "@shikijs/engine-javascript": "1.29.2", "@shikijs/engine-oniguruma": "1.29.2", "@shikijs/langs": "1.29.2", "@shikijs/themes": "1.29.2", "@shikijs/types": "1.29.2", "@shikijs/vscode-textmate": "^10.0.1", "@types/hast": "^3.0.4" } }, "sha512-njXuliz/cP+67jU2hukkxCNuH1yUi4QfdZZY+sMr5PPrIyXSu5iTb/qYC4BiWWB0vZ+7TbdvYUCeL23zpwCfbg=="], - "sisteransi": ["sisteransi@1.0.5", "", {}, "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg=="], + "sisteransi": ["sisteransi@2.0.0", "", {}, "sha512-2WCqLdt12eN6ehLI50S2/ZxoowXU3DD1KVPRyVP0WEsFahrGZZmCdq1K59qjJljMRIDTwx1D9YaRK+hDneBUMg=="], "space-separated-tokens": ["space-separated-tokens@2.0.2", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="], diff --git a/package.json b/package.json index 9502abe..b8ff724 100644 --- a/package.json +++ b/package.json @@ -62,9 +62,9 @@ "postinstall": "node scripts/postinstall.mjs" }, "devDependencies": { - "@chargebee/code-sample-generator": "1.1.1", + "@chargebee/code-sample-generator": "1.1.2", "@clack/prompts": "^1.8.1", - "@types/bun": "1.4.4", + "@types/bun": "1.4.5", "chargebee": "^3.34.0", "commander": "^15.0.0", "typescript": "^7.0.2" diff --git a/src/commands/generated/docs-operations.ts b/src/commands/generated/docs-operations.ts index 8e2123c..0681227 100644 --- a/src/commands/generated/docs-operations.ts +++ b/src/commands/generated/docs-operations.ts @@ -882,6 +882,26 @@ export const docsOperationIds: Record", "Parameters as key=value. List filters require an operator suffix (id[is]=…). Bare keys: limit, offset, include_deleted.") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .addHelpText("after", "\n\u001b[1mLIST FILTERS\u001b[0m\n Filter fields need an operator suffix: [is], [in], [starts_with], [between], [gt], [lt], ...\n Pagination uses bare keys: -d limit=10\n See https://apidocs.chargebee.com/docs/api/list-ops\n Per-resource Filter Params: chargebee docs gateway-request-log list") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs gateway-request-log list\n") + .action(async (json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string }, command: Command) => { + const fromStdin = readJsonMarker(json, command); + const params = await loadOperationParams(opts.data ?? [], fromStdin, command, { method: "GET", jsonInput: false, opIdV2: "list_gateway_request_logs", opIdV1: "list_gateway_request_logs", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "list_gateway_request_logs", opIdV1: "list_gateway_request_logs", method: "GET", uri: "/gateway_request_logs", dataFlags: opts.data ?? [], params, pcVersionFlag: opts.pcVersion }); + if (fromStdin) warnBareJsonFilters(params, "gateway-request-log"); + else warnBareListFilters(opts.data ?? [], "gateway-request-log"); + try { + const client = await getClient(); + const result = await (client as any).gatewayRequestLog.list(toSdkParams(params, "GET", true)); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("retrieve") + .argument("[gateway-request-log-log-id]", "Gateway request log log identifier.") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Retrieve a gateway request log") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs gateway-request-log retrieve\n") + .action(async (id: string | undefined, json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string }, command: Command) => { + const resource = takeResourceId(id, json, command); + const params = await loadOperationParams(opts.data ?? [], resource.fromStdin, command, { method: "GET", jsonInput: false, opIdV2: "retrieve_a_gateway_request_log", opIdV1: "retrieve_a_gateway_request_log", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "retrieve_a_gateway_request_log", opIdV1: "retrieve_a_gateway_request_log", method: "GET", uri: "/gateway_request_logs/{id}", dataFlags: opts.data ?? [], params, resourceId: resource.id, pathParamName: "gateway-request-log-log-id", pcVersionFlag: opts.pcVersion }); + if (!resource.id) command.error("error: missing required argument 'gateway-request-log-log-id'"); + assertResourceId(resource.id, command); + try { + const client = await getClient(); + const result = await (client as any).gatewayRequestLog.retrieve(resource.id, toSdkParams(params, "GET", false)); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + +} \ No newline at end of file diff --git a/src/commands/generated/gateway_webhook_log.ts b/src/commands/generated/gateway_webhook_log.ts new file mode 100644 index 0000000..ac99f0d --- /dev/null +++ b/src/commands/generated/gateway_webhook_log.ts @@ -0,0 +1,64 @@ +// Code generated by src/tools/generate.ts from Chargebee SDK endpoints. DO NOT EDIT. +// Regenerate with: bun run generate + +import { Option, type Command } from "commander"; + +import { getClient, ensureWriteAllowed } from "../../lib/api/sdk.js"; +import { handleSdkError, printResult } from "../../lib/api/print.js"; +import { assertResourceId, handleCodeSample } from "../../lib/api/generated-command.js"; +import { warnBareListFilters } from "../../lib/codesample/index.js"; +import { loadOperationParams, takeResourceId, readJsonMarker, warnBareJsonFilters } from "../../lib/api/stdin-params.js"; + +import { toSdkParams } from "../../lib/api/params.js"; + +export function registerGatewayWebhookLog(parent: Command): void { + const cmd = parent + .command("gateway-webhook-log") + .alias("gateway_webhook_log") + .description("API operations for gateway webhook logs"); + + cmd + .command("list") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("List gateway webhook logs") + .option("-d, --data ", "Parameters as key=value. List filters require an operator suffix (id[is]=…). Bare keys: limit, offset, include_deleted.") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .addHelpText("after", "\n\u001b[1mLIST FILTERS\u001b[0m\n Filter fields need an operator suffix: [is], [in], [starts_with], [between], [gt], [lt], ...\n Pagination uses bare keys: -d limit=10\n See https://apidocs.chargebee.com/docs/api/list-ops\n Per-resource Filter Params: chargebee docs gateway-webhook-log list") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs gateway-webhook-log list\n") + .action(async (json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string }, command: Command) => { + const fromStdin = readJsonMarker(json, command); + const params = await loadOperationParams(opts.data ?? [], fromStdin, command, { method: "GET", jsonInput: false, opIdV2: "list_gateway_webhook_logs", opIdV1: "list_gateway_webhook_logs", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "list_gateway_webhook_logs", opIdV1: "list_gateway_webhook_logs", method: "GET", uri: "/gateway_webhook_logs", dataFlags: opts.data ?? [], params, pcVersionFlag: opts.pcVersion }); + if (fromStdin) warnBareJsonFilters(params, "gateway-webhook-log"); + else warnBareListFilters(opts.data ?? [], "gateway-webhook-log"); + try { + const client = await getClient(); + const result = await (client as any).gatewayWebhookLog.list(toSdkParams(params, "GET", true)); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("retrieve") + .argument("[gateway-webhook-log-webhook-id]", "Gateway webhook log webhook identifier.") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Retrieve a gateway webhook log") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs gateway-webhook-log retrieve\n") + .action(async (id: string | undefined, json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string }, command: Command) => { + const resource = takeResourceId(id, json, command); + const params = await loadOperationParams(opts.data ?? [], resource.fromStdin, command, { method: "GET", jsonInput: false, opIdV2: "retrieve_a_gateway_webhook_log", opIdV1: "retrieve_a_gateway_webhook_log", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "retrieve_a_gateway_webhook_log", opIdV1: "retrieve_a_gateway_webhook_log", method: "GET", uri: "/gateway_webhook_logs/{id}", dataFlags: opts.data ?? [], params, resourceId: resource.id, pathParamName: "gateway-webhook-log-webhook-id", pcVersionFlag: opts.pcVersion }); + if (!resource.id) command.error("error: missing required argument 'gateway-webhook-log-webhook-id'"); + assertResourceId(resource.id, command); + try { + const client = await getClient(); + const result = await (client as any).gatewayWebhookLog.retrieve(resource.id, toSdkParams(params, "GET", false)); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + +} \ No newline at end of file diff --git a/src/commands/generated/organization_detail.ts b/src/commands/generated/organization_detail.ts new file mode 100644 index 0000000..20f72e5 --- /dev/null +++ b/src/commands/generated/organization_detail.ts @@ -0,0 +1,86 @@ +// Code generated by src/tools/generate.ts from Chargebee SDK endpoints. DO NOT EDIT. +// Regenerate with: bun run generate + +import { Option, type Command } from "commander"; + +import { getClient, ensureWriteAllowed } from "../../lib/api/sdk.js"; +import { handleSdkError, printResult } from "../../lib/api/print.js"; +import { assertResourceId, handleCodeSample } from "../../lib/api/generated-command.js"; +import { warnBareListFilters } from "../../lib/codesample/index.js"; +import { loadOperationParams, takeResourceId, readJsonMarker, warnBareJsonFilters } from "../../lib/api/stdin-params.js"; + +import { toSdkParams } from "../../lib/api/params.js"; + +export function registerOrganizationDetail(parent: Command): void { + const cmd = parent + .command("organization-detail") + .alias("organization_detail") + .description("API operations for organization details"); + + cmd + .command("create") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Update organization details") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .option("--allow-write", "Allow this write on a live site without a confirmation prompt") + .addOption(new Option("-y, --yes", "Deprecated alias for --allow-write").hideHelp()) + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs organization-detail create\n") + .action(async (json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string; allowWrite?: boolean; yes?: boolean }, command: Command) => { + const fromStdin = readJsonMarker(json, command); + const params = await loadOperationParams(opts.data ?? [], fromStdin, command, { method: "POST", jsonInput: false, opIdV2: "update_organization_details", opIdV1: "update_organization_details", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "update_organization_details", opIdV1: "update_organization_details", method: "POST", uri: "/organization_details", dataFlags: opts.data ?? [], params, pcVersionFlag: opts.pcVersion }); + await ensureWriteAllowed("POST", "organization-detail create", opts); + try { + const client = await getClient(); + const result = await (client as any).organizationDetail.create(params); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("list") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("List organization details") + .option("-d, --data ", "Parameters as key=value. List filters require an operator suffix (id[is]=…). Bare keys: limit, offset, include_deleted.") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .addHelpText("after", "\n\u001b[1mLIST FILTERS\u001b[0m\n Filter fields need an operator suffix: [is], [in], [starts_with], [between], [gt], [lt], ...\n Pagination uses bare keys: -d limit=10\n See https://apidocs.chargebee.com/docs/api/list-ops\n Per-resource Filter Params: chargebee docs organization-detail list") + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs organization-detail list\n") + .action(async (json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string }, command: Command) => { + const fromStdin = readJsonMarker(json, command); + const params = await loadOperationParams(opts.data ?? [], fromStdin, command, { method: "GET", jsonInput: false, opIdV2: "list_organization_details", opIdV1: "list_organization_details", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "list_organization_details", opIdV1: "list_organization_details", method: "GET", uri: "/organization_details", dataFlags: opts.data ?? [], params, pcVersionFlag: opts.pcVersion }); + if (fromStdin) warnBareJsonFilters(params, "organization-detail"); + else warnBareListFilters(opts.data ?? [], "organization-detail"); + try { + const client = await getClient(); + const result = await (client as any).organizationDetail.list(toSdkParams(params, "GET", true)); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + + cmd + .command("retrieve") + .argument("[organization-detail-id]", "Organization detail identifier.") + .argument("[json]", "'-' reads a JSON object from stdin.") + .description("Retrieve organization details") + .option("-d, --data ", "Request parameters in key=value format; repeat for multiple fields") + .option("-s, --code-sample ", "Generate code sample (curl, python, nodejs, go, ruby, java, php, dotnet, list)") + .addOption(new Option("--pc-version ", "Product catalog version for the code sample (v1 or v2)").hideHelp()) + .addHelpText("after", "\n\u001b[1mDOCUMENTATION\u001b[0m\n chargebee docs organization-detail retrieve\n") + .action(async (id: string | undefined, json: string | undefined, opts: { data?: string[]; codeSample?: string; pcVersion?: string }, command: Command) => { + const resource = takeResourceId(id, json, command); + const params = await loadOperationParams(opts.data ?? [], resource.fromStdin, command, { method: "GET", jsonInput: false, opIdV2: "retrieve_organization_details", opIdV1: "retrieve_organization_details", pcVersionFlag: opts.pcVersion }); + if (opts.codeSample) return handleCodeSample({ lang: opts.codeSample, opIdV2: "retrieve_organization_details", opIdV1: "retrieve_organization_details", method: "GET", uri: "/organization_details/{id}", dataFlags: opts.data ?? [], params, resourceId: resource.id, pathParamName: "organization-detail-id", pcVersionFlag: opts.pcVersion }); + if (!resource.id) command.error("error: missing required argument 'organization-detail-id'"); + assertResourceId(resource.id, command); + try { + const client = await getClient(); + const result = await (client as any).organizationDetail.retrieve(resource.id, toSdkParams(params, "GET", false)); + printResult(result); + } catch (e) { handleSdkError(e); } + }); + +} \ No newline at end of file diff --git a/src/commands/generated/registry.ts b/src/commands/generated/registry.ts index 2417ac2..fde2184 100644 --- a/src/commands/generated/registry.ts +++ b/src/commands/generated/registry.ts @@ -33,6 +33,8 @@ import { registerEstimate } from "./estimate.js"; import { registerEvent } from "./event.js"; import { registerExport } from "./export.js"; import { registerFeature } from "./feature.js"; +import { registerGatewayRequestLog } from "./gateway_request_log.js"; +import { registerGatewayWebhookLog } from "./gateway_webhook_log.js"; import { registerGift } from "./gift.js"; import { registerGrantBlock } from "./grant_block.js"; import { registerHostedPage } from "./hosted_page.js"; @@ -53,6 +55,7 @@ import { registerOmnichannelOneTimeOrder } from "./omnichannel_one_time_order.js import { registerOmnichannelSubscription } from "./omnichannel_subscription.js"; import { registerOmnichannelSubscriptionItem } from "./omnichannel_subscription_item.js"; import { registerOrder } from "./order.js"; +import { registerOrganizationDetail } from "./organization_detail.js"; import { registerPaymentIntent } from "./payment_intent.js"; import { registerPaymentSchedule } from "./payment_schedule.js"; import { registerPaymentScheduleScheme } from "./payment_schedule_scheme.js"; @@ -154,6 +157,10 @@ export function registerAll(rootCmd: Command): void { { const cmd = rootCmd.commands.find(c => c.name() === "export"); if (cmd) setCommandGroup(cmd, "resource"); } registerFeature(rootCmd); { const cmd = rootCmd.commands.find(c => c.name() === "feature"); if (cmd) setCommandGroup(cmd, "resource"); } + registerGatewayRequestLog(rootCmd); + { const cmd = rootCmd.commands.find(c => c.name() === "gateway-request-log"); if (cmd) setCommandGroup(cmd, "resource"); } + registerGatewayWebhookLog(rootCmd); + { const cmd = rootCmd.commands.find(c => c.name() === "gateway-webhook-log"); if (cmd) setCommandGroup(cmd, "resource"); } registerGift(rootCmd); { const cmd = rootCmd.commands.find(c => c.name() === "gift"); if (cmd) setCommandGroup(cmd, "resource"); } registerGrantBlock(rootCmd); @@ -194,6 +201,8 @@ export function registerAll(rootCmd: Command): void { { const cmd = rootCmd.commands.find(c => c.name() === "omnichannel-subscription-item"); if (cmd) setCommandGroup(cmd, "resource"); } registerOrder(rootCmd); { const cmd = rootCmd.commands.find(c => c.name() === "order"); if (cmd) setCommandGroup(cmd, "resource"); } + registerOrganizationDetail(rootCmd); + { const cmd = rootCmd.commands.find(c => c.name() === "organization-detail"); if (cmd) setCommandGroup(cmd, "resource"); } registerPaymentIntent(rootCmd); { const cmd = rootCmd.commands.find(c => c.name() === "payment-intent"); if (cmd) setCommandGroup(cmd, "resource"); } registerPaymentSchedule(rootCmd); diff --git a/src/lib/telemetry/index.ts b/src/lib/telemetry/index.ts index 8659b39..61f222a 100644 --- a/src/lib/telemetry/index.ts +++ b/src/lib/telemetry/index.ts @@ -28,7 +28,7 @@ import { detectInstallMethod } from "../update/index.js"; import { knownCommandPath } from "./command-path.js"; import type { SpoolRecord } from "./types.js"; -export type ListenPhase = "established" | "closed" | "error"; +export type ListenPhase = "established" | "reconnected" | "closed" | "error"; /** Process start — duration is measured from here so it covers parse + action. */ const PROCESS_START = Date.now(); diff --git a/src/lib/telemetry/metadata.ts b/src/lib/telemetry/metadata.ts index f21121d..87d29ac 100644 --- a/src/lib/telemetry/metadata.ts +++ b/src/lib/telemetry/metadata.ts @@ -14,7 +14,7 @@ export interface MetadataInput { errorType?: string; productCatalogVersion?: string; generatedResource?: string; - listenPhase?: "established" | "closed" | "error"; + listenPhase?: "established" | "reconnected" | "closed" | "error"; /** How this copy was installed (npm, github, pnpm, ...), from the update module. */ installMethod?: string; /** Date (YYYY-MM-DD) the first-run notice was shown; set only on an install's first event. */ diff --git a/src/lib/tunnel/appsync-errors.ts b/src/lib/tunnel/appsync-errors.ts index 010bd66..d69a6cf 100644 --- a/src/lib/tunnel/appsync-errors.ts +++ b/src/lib/tunnel/appsync-errors.ts @@ -137,6 +137,16 @@ export function classifyAppSyncFailure(msg: AppSyncErrorMessage): AppSyncFailure }; } +/** + * True when a heartbeat was refused because Chargebee no longer holds the + * session (`CONTROL_FAILED::404`). Sessions expire 90 s after the last + * accepted heartbeat, and a heartbeat cannot revive one; only a new subscribe + * registers it again. + */ +export function isSessionExpired(failure: AppSyncFailure): boolean { + return failure.code === AppSyncErrorCode.CONTROL_FAILED && httpStatus(failure.detail) === 404; +} + /** * User-facing copy. No vendor or pipeline names (AppSync, Lambda, authorizer). */ diff --git a/src/lib/tunnel/appsync.ts b/src/lib/tunnel/appsync.ts index 819e4d1..ff4a9ba 100644 --- a/src/lib/tunnel/appsync.ts +++ b/src/lib/tunnel/appsync.ts @@ -3,7 +3,12 @@ import { randomUUID } from "node:crypto"; import type { WebhookMsg } from "../protocol/types.js"; import { emitListenPhase } from "../telemetry/index.js"; -import { AppSyncErrorCode, classifyAppSyncFailure, listenUserMessage } from "./appsync-errors.js"; +import { + AppSyncErrorCode, + classifyAppSyncFailure, + isSessionExpired, + listenUserMessage, +} from "./appsync-errors.js"; import { forward } from "./forwarder.js"; import * as display from "./display.js"; @@ -347,13 +352,19 @@ export async function runAppSync(opts: AppSyncOptions): Promise { +/** Disconnect reason after a heartbeat finds the session gone on Chargebee's side. */ +const SESSION_EXPIRED_REASON = "The listen session expired"; + +function connectAppSync( + opts: AppSyncOptions, + forwardQueue: ForwardQueue, + subscribedPhase: "established" | "reconnected", +): Promise { const { httpDomain, realtimeDomain, @@ -498,6 +520,32 @@ function connectAppSync(opts: AppSyncOptions, forwardQueue: ForwardQueue): Promi closeSocket(); }, connectTimeoutMs); + /** True from the first refused heartbeat until one is accepted again. */ + let keepaliveFailing = false; + + /** + * A refused heartbeat. The session gone (404) → reconnect, which registers + * it again. The key or site denied (401/403) → stop, as on connect. + * Anything else → keep the socket; the next heartbeat retries. Warn once + * per run of failures, not on every heartbeat. + */ + const onKeepaliveFailure = (msg: ServerMessage) => { + const failure = classifyAppSyncFailure(msg); + if (failure.code === AppSyncErrorCode.APPSYNC_UNAUTHORIZED) { + finish({ kind: "permanent", reason: failure.reason, code: failure.code }); + closeSocket(); + return; + } + if (isSessionExpired(failure)) { + finish({ kind: "transient", reason: SESSION_EXPIRED_REASON, subscribedMs: subscribedMs() }); + closeSocket(); + return; + } + if (keepaliveFailing) return; + keepaliveFailing = true; + display.warn("Session keepalive failed; retrying"); + }; + const armIdleTimer = () => { if (finished || idleThresholdMs <= 0) return; if (idleTimer !== undefined) clearTimeout(idleTimer); @@ -546,7 +594,7 @@ function connectAppSync(opts: AppSyncOptions, forwardQueue: ForwardQueue): Promi connectDeadline = undefined; subscribedAt = Date.now(); display.ready(forwardTo); - emitListenPhase("established"); + emitListenPhase(subscribedPhase); publishControl("heartbeat"); heartbeat = setInterval(() => publishControl("heartbeat"), heartbeatMs); armIdleTimer(); @@ -569,11 +617,17 @@ function connectAppSync(opts: AppSyncOptions, forwardQueue: ForwardQueue): Promi break; } case "publish_error": - display.warn("Session keepalive failed"); + // After abort the only publish in flight is `disable`; its reply says nothing about heartbeats. + if (signal.aborted) break; + onKeepaliveFailure(msg); break; case "publish_success": + if (signal.aborted) break; if (Array.isArray(msg.failed) && msg.failed.length > 0) { - display.warn("Session keepalive failed"); + onKeepaliveFailure({ errors: msg.failed }); + } else if (keepaliveFailing) { + keepaliveFailing = false; + display.warn("Session keepalive restored"); } break; case "broadcast_error": diff --git a/src/tests/integration/listen-telemetry.test.ts b/src/tests/integration/listen-telemetry.test.ts new file mode 100644 index 0000000..ff2d87e --- /dev/null +++ b/src/tests/integration/listen-telemetry.test.ts @@ -0,0 +1,157 @@ +/** + * Telemetry lifecycle events spooled by `chargebee listen` across failed + * attempts, drops and reconnects. Runs the real program with an in-process + * fake WebSocket and a stubbed flush — never AppSync, never the network. + */ +import { afterEach, beforeEach, describe, expect, it } from "bun:test"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { __resetRuntimeState } from "../../lib/api/sdk.js"; +import { __setAppsyncTableForTest } from "../../lib/config/urls.js"; +import { spoolPath } from "../../lib/telemetry/constants.js"; +import { + __resetTelemetryRecorderForTest, + __setSpawnForTest, + installTelemetry, +} from "../../lib/telemetry/index.js"; +import { writeState } from "../../lib/telemetry/state.js"; +import type { SpoolRecord } from "../../lib/telemetry/types.js"; +import { + __setTunnelTimingForTest, + __setWebSocketForTest, +} from "../../lib/tunnel/appsync.js"; +import { __setFetchForTest } from "../../lib/tunnel/forwarder.js"; +import { FakeWebSocket, waitUntil } from "../../lib/test-support/fake-websocket.js"; +import { + clearCiEnv, + createEnvPatcher, + installFakeClient, + runCli, + setStderrIsTTY, + uninstallFakeClient, +} from "../../lib/test-support/_helpers.js"; + +const env = createEnvPatcher(); +let configDir: string; +let restoreCiEnv: () => void = () => undefined; +let restoreStderrTty: (() => void) | undefined; + +beforeEach(() => { + // The recorder is disabled on CI runners; this file reads the spool it writes. + restoreCiEnv = clearCiEnv(); + configDir = mkdtempSync(join(tmpdir(), "cb-listen-telemetry-")); + env.set("CHARGEBEE_CONFIG_DIR", configDir); + env.set("CHARGEBEE_SITE", "acme-test"); + env.set("CHARGEBEE_API_KEY", "test_xxx"); + env.set("CHARGEBEE_HOST", undefined); + env.set("CHARGEBEE_REGION", undefined); + env.set("DO_NOT_TRACK", undefined); + env.set("CHARGEBEE_CLI_TELEMETRY", undefined); + // A later run: the first-run notice has been shown, so events are recorded. + writeState({ notice_shown: true }); + restoreStderrTty = setStderrIsTTY(false); + __resetRuntimeState(); + __resetTelemetryRecorderForTest(); + __setSpawnForTest(() => ({ unref() {} })); + __setAppsyncTableForTest({ + ".chargebee.com": { us: { dnsPrefix: "testapiid", region: "us-east-2" } }, + }); + installFakeClient({ constructions: [] }); + FakeWebSocket.instances = []; + __setWebSocketForTest(FakeWebSocket); + __setTunnelTimingForTest({ backoffMs: 5, maxBackoffMs: 5, closeFlushMs: 0, idleTimeoutMs: 5000 }); + __setFetchForTest(async () => new Response("ok", { status: 200 })); +}); + +afterEach(() => { + __resetTelemetryRecorderForTest(); + __setSpawnForTest(null); + __setAppsyncTableForTest(null); + __setWebSocketForTest(null); + __setTunnelTimingForTest(null); + __setFetchForTest(null); + uninstallFakeClient(); + __resetRuntimeState(); + restoreStderrTty?.(); + restoreStderrTty = undefined; + env.restore(); + restoreCiEnv(); + rmSync(configDir, { recursive: true, force: true }); +}); + +/** The `index`-th socket the run opens, once it has sent its first frame. */ +async function socket(index: number): Promise { + await waitUntil(() => FakeWebSocket.instances.length > index); + const ws = FakeWebSocket.instances[index]!; + await waitUntil(() => ws.sent.length > 0); + return ws; +} + +/** Close the socket before the handshake completes: a failed attempt. */ +async function failAttempt(index: number): Promise { + (await socket(index)).serverClose(); +} + +/** Complete the handshake: a working session. */ +async function subscribe(index: number): Promise { + const ws = await socket(index); + ws.emit({ type: "connection_ack" }); + await waitUntil(() => ws.parsed().some((m) => m.type === "subscribe")); + ws.emit({ type: "subscribe_success" }); + await waitUntil(() => ws.parsed().some((m) => m.type === "publish")); + return ws; +} + +function spooledListenEvents(): SpoolRecord["event"]["metadata"][] { + return readFileSync(spoolPath(), "utf-8") + .trim() + .split("\n") + .map((line) => (JSON.parse(line) as SpoolRecord).event.metadata) + .filter((metadata) => metadata.listen_phase !== undefined); +} + +describe("chargebee listen telemetry", () => { + it("reports failed attempts once per outage, and a recovered drop as reconnected, not an error", async () => { + const pending = runCli(["listen", "--forward-to", "http://localhost:4000/hook"], { + configure: (program) => installTelemetry(program, "0.0.0-test"), + }); + + try { + // Outage 1: three attempts close before the handshake completes. + await failAttempt(0); + await failAttempt(1); + await failAttempt(2); + // Recovery: the first working session of the run. + (await subscribe(3)).serverClose(); + // Outage 2: one attempt after the drop fails, then the next one subscribes. + await failAttempt(4); + // A drop straight back into a working session records only `reconnected`. + (await subscribe(5)).serverClose(); + await subscribe(6); + } finally { + process.emit("SIGINT"); + } + const { exitCode } = await pending; + expect(exitCode).toBe(0); + + const events = spooledListenEvents(); + expect(events.map((m) => m.listen_phase)).toEqual([ + "error", + "established", + "error", + "reconnected", + "reconnected", + "closed", + ]); + expect(events.filter((m) => m.listen_phase === "error").map((m) => m.err_type)).toEqual([ + "listen_connect_error", + "listen_connect_error", + ]); + expect(events.filter((m) => m.listen_phase === "reconnected").map((m) => m.status)).toEqual([ + "ok", + "ok", + ]); + }); +}); diff --git a/src/tests/unit/lib/tunnel/appsync-errors.test.ts b/src/tests/unit/lib/tunnel/appsync-errors.test.ts index 19430d9..0a4d6e8 100644 --- a/src/tests/unit/lib/tunnel/appsync-errors.test.ts +++ b/src/tests/unit/lib/tunnel/appsync-errors.test.ts @@ -4,6 +4,7 @@ import { AppSyncErrorCode, classifyAppSyncFailure, handlerError, + isSessionExpired, listenUserMessage, parseHandlerError, } from "../../../../lib/tunnel/appsync-errors.js"; @@ -103,6 +104,20 @@ describe("classifyAppSyncFailure", () => { }); }); +describe("isSessionExpired", () => { + const classify = (message: string) => classifyAppSyncFailure({ errors: [{ message }] }); + + it("is true only for a CONTROL_FAILED heartbeat that ended in 404", () => { + expect(isSessionExpired(classify("CONTROL_FAILED:heartbeat:404"))).toBe(true); + expect(isSessionExpired(classify("CONTROL_FAILED:heartbeat:503"))).toBe(false); + expect(isSessionExpired(classify("CONTROL_FAILED:heartbeat"))).toBe(false); + expect(isSessionExpired(classify("ENABLE_FAILED:404"))).toBe(false); + expect(isSessionExpired(classifyAppSyncFailure({ errors: [{ errorType: "UnauthorizedException" }] }))).toBe( + false, + ); + }); +}); + describe("listenUserMessage", () => { it("does not name the pipeline or blame the API key for a 401", () => { const message = listenUserMessage(AppSyncErrorCode.APPSYNC_UNAUTHORIZED); diff --git a/src/tests/unit/lib/tunnel/appsync.test.ts b/src/tests/unit/lib/tunnel/appsync.test.ts index 9b8b62c..ba1394d 100644 --- a/src/tests/unit/lib/tunnel/appsync.test.ts +++ b/src/tests/unit/lib/tunnel/appsync.test.ts @@ -1,19 +1,6 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { Command } from "commander"; +import { afterEach, describe, expect, test } from "bun:test"; import { getEventListeners } from "node:events"; -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { spoolPath } from "../../../../lib/telemetry/constants.js"; -import { clearCiEnv } from "../../../../lib/test-support/_helpers.js"; -import { - __resetTelemetryRecorderForTest, - __setSpawnForTest, - installTelemetry, -} from "../../../../lib/telemetry/index.js"; -import { writeState } from "../../../../lib/telemetry/state.js"; -import type { SpoolRecord } from "../../../../lib/telemetry/types.js"; import { __setFetchForTest } from "../../../../lib/tunnel/forwarder.js"; import { __setTunnelTimingForTest, @@ -34,14 +21,7 @@ import { waitUntil, } from "../../../../lib/test-support/fake-websocket.js"; -// The telemetry recorder is disabled on CI runners; the reliability tests read -// the spool it writes, so CI detection is cleared for this file. -let restoreCiEnv: () => void = () => undefined; -beforeEach(() => { - restoreCiEnv = clearCiEnv(); -}); afterEach(() => { - restoreCiEnv(); stopProgress(); }); @@ -202,13 +182,18 @@ function baseOpts(over: Partial = {}): { }; } -async function handshake(): Promise<{ +/** + * Start a run and complete its handshake. Pass `controller` to own the abort + * before the run starts, so `finally` can stop it even if a wait here fails. + */ +async function handshake(controller?: AbortController): Promise<{ ws: FakeWebSocket; ac: AbortController; done: Promise; }> { FakeWebSocket.instances = []; - const { opts, ac } = baseOpts(); + const { opts, ac: own } = baseOpts(controller ? { signal: controller.signal } : {}); + const ac = controller ?? own; const done = runAppSync(opts); await waitUntil(() => (FakeWebSocket.instances[0]?.sent.length ?? 0) > 0); const ws = FakeWebSocket.instances[0]!; @@ -381,7 +366,7 @@ describe("runAppSync (fake WebSocket)", () => { ws.emit({ type: "publish_error", errors: [{ message: "throttled" }] }); ws.emit({ type: "data", event: { event_type: "subscription_created" } }); await waitUntil(() => logs.some((l) => l.includes("failed:"))); - expect(logs).toContain("> Session keepalive failed"); + expect(logs).toContain("> Session keepalive failed; retrying"); expect( logs.some((l) => l.includes("subscription_created \u2192 failed:") && @@ -436,7 +421,8 @@ describe("runAppSync (fake WebSocket)", () => { ws.emit({ type: "publish_success", failed: [{ index: 0 }] }); ws.emit({ type: "publish_success", failed: [] }); expect(logs).toContain("> A webhook event could not be delivered"); - expect(logs.filter((l) => l === "> Session keepalive failed")).toHaveLength(1); + expect(logs.filter((l) => l === "> Session keepalive failed; retrying")).toHaveLength(1); + expect(logs.filter((l) => l === "> Session keepalive restored")).toHaveLength(1); ws.emit({ type: "data", @@ -634,7 +620,7 @@ describe("runAppSync reliability (fake WebSocket)", () => { FakeWebSocket.instances = []; const { opts, ac } = baseOpts(); const done = runAppSync(opts); - // Never emit connection_ack � the deadline must fire on its own. + // Never emit connection_ack — the deadline must fire on its own. await waitUntil(() => FakeWebSocket.instances.length >= 2, 2000); expect( logs.some((l) => @@ -664,7 +650,7 @@ describe("runAppSync reliability (fake WebSocket)", () => { const { ws, ac, done } = await handshake(); expect(ws.readyState).toBe(1); - // No "ka" or any other frame arrives � the socket goes idle after subscribing. + // No "ka" or any other frame arrives — the socket goes idle after subscribing. await waitUntil(() => FakeWebSocket.instances.length >= 2, 2000); expect(ws.readyState).toBe(3); expect( @@ -814,66 +800,154 @@ describe("runAppSync reliability (fake WebSocket)", () => { } }); - test("emits one telemetry error phase per outage, not one per failed attempt", async () => { - __setWebSocketForTest(FakeWebSocket); - __setTunnelTimingForTest({ - backoffMs: 5, - closeFlushMs: 0, - idleTimeoutMs: 5000, - maxBackoffMs: 5, + /** Resolve with `"pending"` if `p` hasn't settled in `ms`, so a hung run still reaches cleanup. */ + function within(p: Promise, ms = 2000): Promise { + return Promise.race([p, new Promise<"pending">((r) => setTimeout(() => r("pending"), ms))]); + } + + for (const [label, frame] of [ + ["publish_error", { type: "publish_error", errors: [{ message: "CONTROL_FAILED:heartbeat:404" }] }], + ["publish_success with failed", { type: "publish_success", failed: [{ message: "CONTROL_FAILED:heartbeat:404" }] }], + ] as const) { + test(`reconnects when a heartbeat finds the session expired (${label})`, async () => { + __setWebSocketForTest(FakeWebSocket); + __setTunnelTimingForTest({ backoffMs: 10, closeFlushMs: 0, idleTimeoutMs: 5000 }); + const { logs, restore } = captureLogs(); + const ac = new AbortController(); + let done: Promise | undefined; + + try { + const run = await handshake(ac); + done = run.done; + run.ws.emit(frame); + + await waitUntil(() => FakeWebSocket.instances.length >= 2, 2000); + expect(run.ws.readyState).toBe(3); + expect( + logs.some((l) => l.startsWith("> Disconnected: The listen session expired. Reconnecting in")), + ).toBe(true); + expect(logs).not.toContain("> Session keepalive failed; retrying"); + + // The new socket subscribes again, which registers a fresh session. + const next = FakeWebSocket.instances[1]!; + await waitUntil(() => next.sent.length > 0); + next.emit({ type: "connection_ack" }); + await waitUntil(() => next.parsed().some((m) => m.type === "subscribe")); + expect(next.parsed().find((m) => m.type === "subscribe")?.channel).toBe( + "/webhooks/550e8400-e29b-41d4-a716-446655440000", + ); + } finally { + ac.abort(); + if (done) await within(done); + restore(); + } }); - const dir = mkdtempSync(join(tmpdir(), "cb-appsync-telemetry-")); - const prevDir = process.env.CHARGEBEE_CONFIG_DIR; - process.env.CHARGEBEE_CONFIG_DIR = dir; - writeState({ notice_shown: true }); - __resetTelemetryRecorderForTest(); - __setSpawnForTest(() => ({ unref() {} })); - const { restore } = captureLogs(); + } + + test("stops with a permanent outcome when a heartbeat is unauthorized", async () => { + __setWebSocketForTest(FakeWebSocket); + __setTunnelTimingForTest({ backoffMs: 10, closeFlushMs: 0, idleTimeoutMs: 5000 }); + const { logs, restore } = captureLogs(); + const ac = new AbortController(); + let done: Promise | undefined; try { - FakeWebSocket.instances = []; - const { opts, ac } = baseOpts(); - const program = new Command(); - program.exitOverride(); - program.command("listen").action(async () => { - await runAppSync(opts); + const run = await handshake(ac); + done = run.done; + run.ws.emit({ + type: "publish_error", + errors: [{ errorType: "UnauthorizedException", message: "denied" }], }); - installTelemetry(program, "1.0.0-test"); - const run = program.parseAsync(["listen"], { from: "user" }); - - // Outage 1: three attempts close before the handshake completes. - for (let i = 0; i < 3; i++) { - await waitUntil(() => FakeWebSocket.instances.length >= i + 1); - const ws = FakeWebSocket.instances[i]!; - await waitUntil(() => ws.sent.length > 0); - ws.serverClose(); + + expect(await within(done)).toEqual({ + kind: "permanent", + reason: "Could not authorize the listen session.", + code: "APPSYNC_UNAUTHORIZED", + }); + expect(run.ws.readyState).toBe(3); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(logs.some((l) => l.includes("Reconnecting"))).toBe(false); + } finally { + ac.abort(); + if (done) await within(done); + restore(); + } + }); + + test("only warns on other heartbeat failures and keeps the socket", async () => { + __setWebSocketForTest(FakeWebSocket); + __setTunnelTimingForTest({ backoffMs: 10, closeFlushMs: 0, idleTimeoutMs: 5000 }); + const { logs, restore } = captureLogs(); + const ac = new AbortController(); + let done: Promise | undefined; + + try { + const run = await handshake(ac); + done = run.done; + const { ws } = run; + // ESS down, its key misconfigured, or unreachable (no status): none end the session. + for (const message of [ + "CONTROL_FAILED:heartbeat:503", + "CONTROL_FAILED:heartbeat:403", + "CONTROL_FAILED:heartbeat", + ]) { + ws.emit({ type: "publish_error", errors: [{ message }] }); } - // Recovery: a full handshake reaches Ready. - await waitUntil(() => FakeWebSocket.instances.length >= 4); - const healthy = FakeWebSocket.instances[3]!; - await waitUntil(() => healthy.sent.length > 0); - healthy.emit({ type: "connection_ack" }); - await waitUntil(() => healthy.parsed().some((m) => m.type === "subscribe")); - healthy.emit({ type: "subscribe_success" }); - // Outage 2. - healthy.serverClose(); - await waitUntil(() => FakeWebSocket.instances.length >= 5); + await new Promise((r) => setTimeout(r, 30)); + + // One warning for the whole run of failures, not one per heartbeat. + const failing = () => logs.filter((l) => l === "> Session keepalive failed; retrying"); + const restored = () => logs.filter((l) => l === "> Session keepalive restored"); + expect(failing()).toHaveLength(1); + expect(restored()).toHaveLength(0); + expect(ws.readyState).toBe(1); + expect(FakeWebSocket.instances).toHaveLength(1); + + // An accepted heartbeat ends the run; a later failure warns again. + ws.emit({ type: "publish_success" }); + ws.emit({ type: "publish_success" }); + expect(restored()).toHaveLength(1); + ws.emit({ type: "publish_error", errors: [{ message: "CONTROL_FAILED:heartbeat:503" }] }); + expect(failing()).toHaveLength(2); + expect(ws.readyState).toBe(1); + } finally { + ac.abort(); + if (done) await within(done); + restore(); + } + }); + + test("ignores publish replies after shutdown starts (the reply to disable)", async () => { + __setWebSocketForTest(FakeWebSocket); + // Keep the socket open briefly after abort, as in production, so replies can still arrive. + __setTunnelTimingForTest({ backoffMs: 10, closeFlushMs: 50, idleTimeoutMs: 5000 }); + const { logs, restore } = captureLogs(); + const ac = new AbortController(); + let done: Promise | undefined; + + try { + const run = await handshake(ac); + done = run.done; + const { ws } = run; + ws.emit({ type: "publish_error", errors: [{ message: "CONTROL_FAILED:heartbeat:503" }] }); + expect(logs.filter((l) => l === "> Session keepalive failed; retrying")).toHaveLength(1); ac.abort(); - await run; + expect(ws.parsed().some((m) => (m.events as string[] | undefined)?.[0] === '{"op":"disable"}')).toBe(true); + // Replies to `disable` while the socket drains: none may report on heartbeats. + ws.emit({ type: "publish_success" }); + ws.emit({ type: "publish_error", errors: [{ message: "CONTROL_FAILED:disable:404" }] }); + ws.emit({ type: "publish_error", errors: [{ errorType: "UnauthorizedException" }] }); - const phases = readFileSync(spoolPath(), "utf-8") - .trim() - .split("\n") - .map((line) => (JSON.parse(line) as SpoolRecord).event.metadata.listen_phase); - expect(phases).toEqual(["error", "established", "error", "closed"]); + expect(await within(done)).toEqual({ kind: "aborted" }); + expect(logs).not.toContain("> Session keepalive restored"); + expect(logs.filter((l) => l === "> Session keepalive failed; retrying")).toHaveLength(1); + expect(logs.some((l) => l.includes("Reconnecting"))).toBe(false); + expect(FakeWebSocket.instances).toHaveLength(1); } finally { + ac.abort(); + if (done) await within(done); restore(); - __resetTelemetryRecorderForTest(); - __setSpawnForTest(null); - if (prevDir === undefined) delete process.env.CHARGEBEE_CONFIG_DIR; - else process.env.CHARGEBEE_CONFIG_DIR = prevDir; - rmSync(dir, { recursive: true, force: true }); } });