Skip to content

About

HTTP client'lardan (axios, reverse-client, PHP Guzzle) inspector-api'ye event gönderen SDK

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

@inspector-rest/sdk

Node SDK for inspector.rest. It records the HTTP requests your application makes (request, response, bodies, retries, errors, timings) and ships them to your inspector.rest environment, where you can search and inspect them.

The SDK is built to stay out of the way: the request path only stores references, and serialization, compression and sending happen on a worker thread. Under heavy load it sheds bodies and records instead of slowing your application down.

  • Zero runtime dependencies, TypeScript types included, Node 22 or newer.
  • Adapters for axios and for the @sqaft-reverse/client observer. Any other HTTP client can report through the lifecycle events.
  • One record per request, with all of its attempts.
  • zstd compression (gzip fallback), HTTP keep-alive, several batches in flight.
  • Works on Cloudflare Workers and other runtimes without Node built-ins (see Runtimes).

Install

npm install @inspector-rest/sdk

axios is an optional peer dependency; install it if you use the axios adapter.

Quick start

const axios = require('axios');
const { create_inspector } = require('@inspector-rest/sdk');
const instrument_axios = require('@inspector-rest/sdk/axios');

const inspector = create_inspector({
	server_key: process.env.INSPECTOR_SERVER_KEY, // irk_<org-slug>_<secret>
	service: 'billing',
	labels: { env: 'production' },
});

instrument_axios(axios, inspector);

await axios.get('https://api.example.com/items');

// On shutdown (optional; the SDK also flushes on beforeExit and SIGTERM / SIGINT):
await inspector.close();

ES modules work the same way: import { create_inspector } from '@inspector-rest/sdk' and import instrument_axios from '@inspector-rest/sdk/axios'.

The ingest key

Every environment has its own ingest key, shown once when you create it in the console. It has the form irk_<org-slug>_<secret>. The SDK derives the API address from it: https://<org-slug>.api.inspector.rest. Requests are recorded into the environment the key belongs to.

server_url overrides the address and exists for local development only (for example http://localhost:3200).

Without a usable server_key the SDK warns once and does nothing; your requests are never affected.

Configuration

create_inspector(config) takes these options. Everything except server_key is optional.

Option Default Description
server_key – Ingest key (irk_<org-slug>_<secret>).
server_url derived from the key API origin override, for local development.
service – Service name stored with every batch.
labels {} Labels added to every request (details).
capture_body 'always' 'always', 'on_error' (bodies kept only for failed requests) or 'never'.
max_body_bytes unlimited Cut text bodies at this many UTF-8 bytes (on a character boundary). The record notes the original size and truncated: true.
capture_binary false Upload binary bodies. When off, only metadata (size, content type) is sent.
max_binary_bytes 10485760 Binary bodies above this size are not uploaded (metadata only).
sample_rate 1 Fraction of requests recorded (0 to 1). A request is recorded completely or not at all.
include_hosts / exclude_hosts – Host patterns (* wildcard, case-insensitive, port ignored). With include_hosts, only matching hosts are recorded.
include_paths / exclude_paths – Path patterns (* wildcard) matched against the path without the query string.
redact_headers – Header names whose values are replaced with [redacted].
redact_fields – Field names redacted in JSON and form bodies and in URL query strings.
redact_hook – (record) => void | false called with the wire record before it is serialized; mutate it or return false to drop it.
error_details – (error) => object: adds the error's own fields as details. A throwing hook is ignored.
batch_bytes 1048576 A batch is sent when it reaches this size ...
flush_interval_ms 1000 ... or this age.
max_queue_bytes 67108864 Upper bound of everything the SDK holds in memory (64 MiB). The oldest records are dropped beyond it.
max_in_flight 4 Batches sent concurrently.
timeout_ms 10000 Timeout of one send.
close_timeout_ms 5000 close() and flush() stop waiting after this long.
in_progress_after_ms 2000 A request still running after this long is reported as in progress.
compression 'auto' 'auto' (zstd, else gzip), 'zstd', 'gzip' or 'none'.
failure_threshold / circuit_open_ms 3 / 30000 After this many failed sends in a row the SDK stops trying for circuit_open_ms (requests are unaffected, records keep queueing within the bound).
max_cpu_share 0.1 Load budget: share of the application thread the SDK may spend.
max_bytes_per_second 20971520 Load budget: compressed bytes sent per second.
auto_flush true Flush on beforeExit and on SIGTERM / SIGINT.
worker_thread true Serialize, compress and send on a worker thread. See Runtimes.
fetch global fetch Custom fetch used for sending (forces the main thread).

Methods

Method
flush() Sends everything queued so far and waits (at most close_timeout_ms). Never rejects. Use it with ctx.waitUntil(inspector.flush()) on Workers.
close() Final delivery attempt including batches in flight and requests still running (reported as in progress), then stops the inspector. Bounded by close_timeout_ms.
stats() Counters for diagnostics: state, captured / sent / dropped records, held bytes, shed level, max_block_ms (the longest synchronous stretch the SDK ran on your application thread, wall clock) and max_block_cpu_ms (the longest thread CPU time of those stretches, without time the operating system gave to other threads; equal to max_block_ms where the runtime has no thread CPU clock).

Adapters

axios

const eject = instrument_axios(axios, inspector, {
	labels: { client: 'billing-api' }, // added to every request of this instance
	status_as_error: true,              // default: 4xx/5xx responses are reported as errors
});

axios.get(url, { inspector_labels: { op: 'list' } }); // labels of a single request

eject(); // restores the original adapter

The adapter wraps axios' adapter, so the request headers and body that are recorded are the ones that go on the wire, including headers added by interceptors registered before or after instrument_axios. The body is never serialized a second time and getUri is not called.

  • Works with any axios adapter (http, fetch, xhr) and in every runtime.
  • Pass the default axios export or an instance from axios.create(). For created instances the SDK resolves the adapter through the installed axios package, so keep a single copy of axios.
  • A request that sets its own adapter option is not recorded.
  • 4xx/5xx responses accepted by validateStatus are reported with an error named HttpError (exported from the package); with status_as_error: false they settle as ok.
  • Streaming responses (responseType: 'stream') are recorded without a body.
  • axios has no retry of its own, so every call is one attempt. Retries done by a library that calls axios again are separate records.

@sqaft-reverse/client

const { create_client } = require('@sqaft-reverse/client');
const create_reverse_client_observer = require('@inspector-rest/sdk/reverse-client');

const client = create_client({ observer: create_reverse_client_observer(inspector) });

The observer forwards the engine's six lifecycle events to the inspector. The inspector's lifetime (flush / close) belongs to you; client.dispose() does not close it.

Lifecycle events

Any client can report through the inspector's on_* methods. They are synchronous, never throw and only keep references. Events of one request are matched by request_id and merged into one record.

Method Payload fields
on_request request_id, labels?, attempt? (default 1), method, url, headers?, proxy_url?, body?
on_response request_id, labels?, attempt?, status, headers?, duration_ms?
on_body request_id, labels?, attempt?, bytes?, parse_ok?, read_ms?, raw_body?
on_retry request_id, labels?, attempt?, policy?, stage?, delay_ms?, exhausted?
on_error request_id, labels?, attempt? (omit for a request-level error), phase?, error
on_settled request_id, labels?, method?, url?, attempts?, outcome ('ok' or 'error'), duration_ms?, error?

Bodies are strings, Uint8Array / Buffer / ArrayBuffer, URLSearchParams or plain objects. Headers are plain objects, Headers or axios header objects. A request-level error (attempt omitted, or phase: 'domain') is kept even when it arrives after on_settled (for a short grace period) and makes the outcome error.

Labels

Labels are string key-value pairs you can filter by in the app. They merge per key; later sources win:

  1. Automatic labels (below)
  2. labels of create_inspector
  3. The context set by with_labels(labels, fn)
  4. Labels of the request (adapter options, inspector_labels)

Values are converted to strings; empty values are dropped.

const { with_labels } = require('@inspector-rest/sdk');

await with_labels({ tenant: 'acme', job: 'sync' }, async () => {
  await axios.get(url); // carries tenant=acme, job=sync
});

with_labels uses AsyncLocalStorage (Node, and Workers with nodejs_compat): the labels follow the async call tree and concurrent flows never see each other's labels. Where it is unavailable, with_labels applies to the synchronous part of the callback only.

Automatic label Value
server_host os.hostname()
app_package Name from the nearest package.json above the code that called create_inspector (also inside node_modules).
app_commit 12-character commit of the same package: the repository's HEAD (found in parent directories too, worktrees included), else the commit npm locked for a git dependency, else GIT_COMMIT / COMMIT_SHA / SOURCE_VERSION.

They are resolved asynchronously once at startup; nothing is read in the request path. Runtimes without a file system add none.

Behavior under load

  • Hot path. The request path stores references only: no copying, no JSON.stringify, no encoding. Sizes are estimated with string.length. Labels are resolved once per request.
  • One record per request. Request, response, body, retries, errors and the final outcome are merged in memory and sent as one record with all attempts. A request that is still running after 2 s is sent as an "in progress" record that the finished record replaces.
  • Serialization and compression are off the request path. By default on a worker thread (the main thread only copies finished records, in slices of at most about half a millisecond; when the event loop is too busy for that to keep up, a finishing request triggers the next slice right after its callback). Without a worker, serialization runs in short slices that yield to the event loop and compression runs in the libuv thread pool.
  • Sending. fetch with keep-alive, up to max_in_flight batches at once, a batch per 1 MiB or per second.
  • Bounded memory. Everything the SDK holds is bounded by max_queue_bytes. When the bound is hit the oldest records are dropped; the number is reported in the next batch (dropped.records).
  • Load budget. When serialization would use more than max_cpu_share of the application thread, more than max_bytes_per_second would be sent, or the queue fills up, the SDK sheds work in this order: binary bodies, then text bodies, then whole records (records are shed only for CPU or bandwidth pressure; a full queue drops its oldest records). Shed bodies are replaced by a descriptor with omitted: 'load', and the counts (dropped.text_bodies, dropped.binary_bodies) show up in the app as "N bodies skipped because of load".
  • Failures never reach your requests. Errors inside the SDK are swallowed.
Ingest answers The SDK
2xx Done. rejected records ({ accepted, rejected: [{ index, reason }] }) are counted in stats().rejected_records.
413 Splits the batch in halves and resends them (and lowers the batch size). A single record that is still too large is dropped and counted.
415 Switches from zstd to gzip.
429 with error.code: "quota_exceeded", 403 with error.code: "organization_suspended" Monthly request limit reached or organization suspended: stops capturing (no records are kept, nothing is serialized) and probes with an empty batch after Retry-After (default 60 s). Capturing resumes when the probe succeeds.
other 429, 408, 5xx (including 503 with Retry-After), network errors, timeouts Keeps the batch and retries with exponential backoff (honoring Retry-After) within the queue bound. After failure_threshold failures in a row the circuit stays open for circuit_open_ms.
401 Invalid or revoked key: disables itself and warns once.
other 4xx (including other 403) The batch cannot be fixed by retrying: it is dropped, counted and reported once.

Runtimes

Runtime
Node 22+ Everything described above. zstd needs Node 22.15+ (older 22.x use gzip).
Cloudflare Workers, edge runtimes, browsers No worker thread: serialization runs in the same isolate in short slices; compression uses CompressionStream('gzip'); no automatic labels. Call ctx.waitUntil(inspector.flush()) at the end of a request, because timers do not run after the response is sent. With nodejs_compat with_labels uses AsyncLocalStorage.
Main thread on Node Set worker_thread: false, or use redact_hook, error_details or fetch (functions cannot move to another thread).

Shutdown: the SDK flushes on beforeExit and on SIGTERM / SIGINT (the signal is re-raised afterwards unless your application has its own handler). Call await inspector.close() yourself when you manage shutdown.

Wire format

The SDK posts batches to POST {origin}/api/ingest. The format is defined in schema/ingest.schema.json (JSON Schema draft 07). The same schema, TypeScript types and protocol constants are exported for servers:

import { ingest_schema, INGEST_PATH, KEY_HEADER, QUOTA_EXCEEDED_CODE, ORGANIZATION_SUSPENDED_CODE } from '@inspector-rest/sdk/schema';
import type { IngestEnvelope, IngestRecord } from '@inspector-rest/sdk/schema';

@inspector-rest/sdk/schema loads nothing but the schema. schema/fixtures/valid and schema/fixtures/invalid hold example batches that other implementations can test against.

Request

Method and path POST /api/ingest on https://<org-slug>.api.inspector.rest
x-inspector-key The ingest key
content-type application/json, or multipart/form-data when binary parts are attached
content-encoding zstd or gzip (absent when compression: 'none'). Applies to the whole body. Large bodies are compressed as several independent frames / members that are concatenated; a standard decoder reads them as one stream.
accept application/json

Multipart: the first part is named batch (application/json, the envelope below); every further part holds the raw bytes of one binary body and is named by the part field of its body descriptor (b1, b2, ...). Part names are unique within a batch and keep their names when a batch is split or re-sent.

Envelope

{
  "v": 1,
  "sdk": { "name": "inspector-rest-sdk-node", "version": "0.0.1", "runtime": "node/24.1.0" },
  "sent_at": 1790000005000,
  "service": "billing",
  "instance_id": "0b7f4c1e-52c1-4a7e-9f4f-1d9f5a0c2c11",
  "seq": 12,
  "batch_id": "0b7f4c1e-52c1-4a7e-9f4f-1d9f5a0c2c11:12",
  "dropped": { "records": 0, "text_bodies": 0, "binary_bodies": 0 },
  "records": []
}
Field
v Wire format version (1). A breaking change bumps it.
sdk SDK name, version and runtime.
sent_at Client wall clock (epoch ms) when this send attempt was assembled. The server compares it with its own receive time to correct the clock skew of started_at. A re-sent batch carries a fresh value.
service The service option, or null.
instance_id, seq, batch_id Random id of the SDK instance, batch sequence number (from 1) and <instance_id>:<seq>. A re-sent batch (after a timeout, 5xx, 503) keeps its batch_id, so the server can discard a duplicate inside a short window. Halves of a batch that was answered with 413 get new ids.
dropped What was discarded since the previous batch that carried counts: whole records (queue overflow, load budget, permanently rejected batches), text_bodies omitted because of the load budget, binary_bodies not uploaded because of the load budget or max_binary_bytes. The counts travel with one batch (the same one when it is re-sent).
records One record per request. Empty for the quota probe.

Record

{
  "request_id": "5a1d2a54-7a9e-4b4e-8d0d-0d5c7f6a2001",
  "started_at": 1789999990123.456,
  "in_progress": false,
  "method": "POST",
  "url": "https://api.example.com/v1/charges",
  "labels": { "env": "production", "server_host": "web-1" },
  "outcome": "ok",
  "duration_ms": 1530.25,
  "error": null,
  "attempts": []
}
Field
request_id Identifies the request. A record with the same id replaces the previous one, except that an in_progress record never replaces a complete one (batches may arrive out of order).
started_at Request start, epoch ms on the client clock (fraction allowed). Sorting uses it; retention and paging should use the server's receive time.
in_progress true when the record was sent while the request was still running (after in_progress_after_ms, or at close()). Then outcome and duration_ms are null.
method, url As sent (url includes the query string).
labels Fully resolved labels (all values are strings).
outcome "ok", "error" or null. error also when a request-level error was reported although the request settled ok.
duration_ms Total duration, measured with a monotonic clock.
error Request-level error (for example a domain error that belongs to no attempt, or the final error passed at settle time). Absent or null otherwise.
attempts Ascending by attempt number. The server derives status, outcome and error phase from the highest numbered attempt.

Attempt

Field
attempt Attempt number, from 1.
offset_ms Start of the attempt relative to the record's started_at (monotonic).
method, url Only when different from the record's.
request { headers, proxy_url, body } or null.
response { status, headers, duration_ms, read_ms, parse_ok, body } or null (no response was received). duration_ms is the time to the response headers. parse_ok: false means the engine could not parse the body; the raw body is kept.
retry { policy, stage, delay_ms, exhausted } when a retry was decided after this attempt.
error Error of this attempt (see below) or null.

Header names are lower-case; repeated headers (set-cookie) are arrays.

Error

{ phase, name, message, code?, stack?, request_id?, status?, details?, cause?, errors? }

  • phase: network, http, parse, domain or an engine-specific phase.
  • name: the error class name. HTTP status errors are named HttpError and carry status.
  • cause: the error.cause chain (nested, depth-limited). errors: members of an AggregateError.
  • details: whatever the error_details hook returned.

Body descriptor

{ "encoding": "utf8", "size": 11, "content_type": "application/json", "text": "{\"ok\":true}" }
encoding
utf8 The body text is inline in text. size is the original size in bytes; truncated: true when text was cut at max_body_bytes.
part Raw bytes travel in the multipart part named by part. binary: true.
none Metadata only. omitted says why: binary (binary capture is off), load (dropped by the load budget), too_large (above max_binary_bytes), stream (not readable: streams, FormData). Binary bodies have binary: true.

A body is binary when its content type says so (images, audio, video, archives, application/octet-stream, ...) or, when the type does not decide, when its bytes are not valid UTF-8.

Response

{ "accepted": 2, "rejected": [ { "index": 1, "reason": "invalid record" } ] }

Every record is validated on its own. See behavior under load for how the SDK reacts to status codes.

Benchmark

bench/ holds a benchmark that compares an axios client with and without the SDK against a local target and a fake ingest server (separate processes): requests per second, p99 latency, main-thread CPU, the longest stretch the SDK ran synchronously on the event loop (max_block_ms, wall clock; the gate uses it), memory and record loss.

npm run bench        # reduced set, repeated 3 times, then the gate (bench/thresholds.json)
npm run bench:full   # every scenario; writes bench/results/full.md
npm run bench:micro  # per-request cost without a network

bench/check.js fails when a limit is exceeded. bench/thresholds.json lists the targets (spec) and the limits that are enforced (limit); node bench/check.js <name> --strict enforces the targets. The benchmark runs locally; on GitHub Actions the Benchmark workflow (.github/workflows/bench.yml) runs the same reduced set when it is started by hand.

Results of the latest full run on an Apple M1 Pro (Node 24, loopback, 3 repetitions, medians): bench/results/full.md.

License

MIT

About

HTTP client'lardan (axios, reverse-client, PHP Guzzle) inspector-api'ye event gönderen SDK

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages