Repository navigation
SCR-652: async requests and webhooks (submit/get/wait/callbackStatus, signature verify) - #96
Merged
Merged
Conversation
… signature verify)
- requests.submit(path, { method, params, body, callbackUrl, wait, idempotencyKey })
sends Prefer: respond-async[, wait=N], X-Callback-URL and Idempotency-Key and
returns an AsyncRequest (running on 202, completed when done within wait).
Without an idempotency key a timed-out or network-failed submit is thrown,
not retried (it could run and bill twice); a replayed error is never retried.
- requests.get(id), requests.wait(id, { timeoutMs }) (honours Retry-After,
throws WaitTimeoutError), requests.callbackStatus(id).
- account.webhookSecret(), rotateWebhookSecret(), webhookDeliveries({ limit }).
- verifyWebhookSignature(secret, rawBody, signature, { sentAt, toleranceS })
(constant-time, stale sentAt rejected; same function as the twitter export)
and parseWebhookEvent(rawBody) with the typed request.completed payload.
- AsyncRequest.status is now "running" | "completed"; the HTTP status is
statusCode; adds headers, body, replayed (data kept as a deprecated alias).
- RequestsClient moves to src/requests/ and the account client gets a
hand-written part, so SDK codegen appends new spec ops instead of
generating a clashing requests module.
- 0.80.0, CHANGELOG, README section with a Perplexity example and an
Express receiver.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… -> PermissionDeniedError
- Without an Idempotency-Key, submit retries only a connection that failed
before anything was sent (ECONNREFUSED, ENOTFOUND, EAI_AGAIN, EHOSTUNREACH,
ENETUNREACH, connect timeout). A timeout, other network faults, 429 and
5xx are thrown: after a lost 202 the call may already be running.
- wait() throws a finished call's error status at once instead of retrying
it (a stored result answers the same every time); network faults while
polling are still retried.
- BaseClient: RequestOptions.retry ("all" | "transport" | "connect")
replaces the boolean idempotent option.
- 403 full_access_required (webhook secret / delivery log) maps to
PermissionDeniedError, a subclass of the AuthenticationError it was.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Node SDK part of SCR-652 (system-wide async API). It follows
research/scr-652-async-api/CONTRACT.md, "SDKs (Node)". The gateway, docs and Python PRs for SCR-652 are separate. This PR matches the Python SDK (scrape-badger/scrapebadger-python#105) on retries, request ids and errors.What it adds
client.requestssubmit(path, { method, params, body, callbackUrl, wait, idempotencyKey })sendsPrefer: respond-async[, wait=N], plusX-Callback-URLandIdempotency-Keywhen given. It returns anAsyncRequest:status: "running"on a 202;status: "completed"when the call finished withinwait.callbackUrlwithout awaitsendswait=0, so the call answers 202 at once.wait + 15 swhen that is above the client timeout./v1. Absolute URLs are refused, so the API key is never sent to another host.idempotencyKey, a submit is retried only when the connection failed before anything was sent:ECONNREFUSED,ENOTFOUND,EAI_AGAIN,EHOSTUNREACH,ENETUNREACH, or a connect timeout.replayed: true.Idempotent-Replayed: trueis never retried, because it would come back the same every time.get(id): one poll, same signature as before.wait(id, { timeoutMs = 600000 })polls until the call completes:Retry-Aftersays (falling back to the body'sretry_after_seconds, then 5 s);WaitTimeoutError(aTimeoutErrorwithrequestId) at the deadline.callbackStatus(id):GET /v1/requests/{id}/callback.client.accountwebhookSecret(),rotateWebhookSecret()andwebhookDeliveries({ limit }), typed.full_access_requirednow throwsPermissionDeniedError. That is a subclass ofAuthenticationError, which it threw before.getTheWebhookSigningSecretandrotateTheWebhookSigningSecretare unchanged.Root exports
verifyWebhookSignature(secret, rawBody, signature, { sentAt, toleranceS = 300 }):node:cryptoHMAC-SHA256 compared withtimingSafeEqual;sha256=+ 64 hex characters;sentAt, and throwsTypeErroron a parsed object instead of the raw body;scrapebadger/twitteralready exported, and the 3-argument form is unchanged.parseWebhookEvent(rawBody): returns a typedWebhookEvent<T>(therequest.completedpayload fromlong-running-requests.mdx).AsyncAccepted,SubmitOptions,WaitOptions,CallbackStatus,WebhookSecret,WebhookDelivery,WebhookDeliveries,WebhookEventandVerifyWebhookSignatureOptions.require()andimportofdist/.One breaking change:
AsyncRequest.statusThe contract names
AsyncRequest.status"running" | "completed"in both SDKs. In Node,statusused to be the HTTP status number.statusCode.runningstill works, anddatastays as a deprecated alias ofbody.status === 202get a compile error. The CHANGELOG says so.status: numberand name the fieldstate. That would deviate from the contract.Codegen safety
On
main, the monorepo facade generator (sdk/codegen/facade/gen_node.py) would break once the OpenAPI document gainsGET /v1/requests/{request_id}/callback:src/requests/module, so it generates one;requestsproperty inclient.ts, andtscfails with TS2300 duplicate identifier.I reproduced that locally. This PR prevents it:
RequestsClientmoves tosrc/requests/client.ts.agent/client.tsre-exports it, so imports don't change.src/account/client.tsbecomes hand-written, with the generated methods inside a BEGIN/END block.With both new paths added to the spec, the generator now appends
getTheCallbackDeliveryStatusandlistWebhookDeliveriesinto those classes, andtscpasses.To avoid those raw duplicates, add these entries to the monorepo's
sdk/codegen/facade/node-v1-surface.json:account.webhookSecretandaccount.rotateWebhookSecretmust keep"path": null. With their real paths, the generator would stop emitting the publishedgetTheWebhookSigningSecretandrotateTheWebhookSigningSecret.requests.getis already listed and its signature is unchanged.Release notes
package.json, lockfile,src/internal/version.ts). The contract says 0.54.0 → 0.55.0, but npm andmainare at 0.79.0.publish.yml, npm trusted publishing). Merging this does not publish.v0.79.0,mainalso carries the generatedrufusclient from Generated v2 SDK from OpenAPI spec #94. It has no CHANGELOG line, and a 0.80.0 release would ship it too.Test plan
npm test: 503 tests pass. New:tests/async-requests.test.tsandtests/webhooks.test.ts. They cover:getof a completed call, andwaitpolling onRetry-Afterand timing out;Idempotent-Replayed→replayed: true), and which failures are retried with and without a key;waitthrowing a stored error without retrying it, and the 403full_access_requiredmapping;parseWebhookEvent.npm run typecheck,npm run lint,npm run build.gen_node.pyagainst this branch with the new paths added to the spec, then prettier, thentsc.🤖 Generated with Claude Code