inspector-rest / sdk
PHP SDK for inspector.rest: records the HTTP requests your application makes (Guzzle) without slowing it down.
Requires
- php: >=8.1
- ext-curl: *
- ext-json: *
- psr/http-message: ^1.1 || ^2.0
Requires (Dev)
- guzzlehttp/guzzle: ^7.8
- opis/json-schema: ^2.3
- phpunit/phpunit: ^10.5
Suggests
- ext-apcu: Shares the circuit breaker, the quota pause and the dropped counters between PHP-FPM workers
- ext-zlib: gzip compression of batches
- ext-zstd: zstd compression of batches (preferred over gzip when present)
- guzzlehttp/guzzle: Needed for the GuzzleMiddleware adapter
Provides
None
Conflicts
None
Replaces
None
README
PHP SDK for inspector.rest. It records the HTTP requests your application makes (request, response, bodies, 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: nothing is sent while your code runs. Under PHP-FPM the records leave in one compressed batch after the response has been flushed to the client; if inspector.rest is unreachable your requests never wait longer than a 200 ms connect attempt, and only once.
- PHP 8.1 or newer,
ext-curl,ext-jsonandpsr/http-message; no other runtime dependencies. - Guzzle middleware and lifecycle hooks for any other HTTP client.
- One record per request, with all of its attempts.
- gzip compression (zstd when
ext-zstdis installed), bounded memory, errors inside the SDK never reach your code. - Optional APCu shares the circuit breaker and the quota pause between all PHP-FPM workers.
Full documentation: https://docs.inspector.rest
Install
composer require inspector-rest/sdk
The Guzzle middleware needs guzzlehttp/guzzle (^7.8) in your project. ext-apcu, ext-zlib and ext-zstd are optional.
Quick start
use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use InspectorRest\GuzzleMiddleware; use InspectorRest\Inspector; $inspector = new Inspector([ 'server_key' => getenv('INSPECTOR_SERVER_KEY'), // irk_<org-slug>_<secret> 'service' => 'billing', 'labels' => ['env' => 'production'], ]); $stack = HandlerStack::create(); $stack->push(GuzzleMiddleware::create($inspector)); $client = new Client(['handler' => $stack]); $client->get('https://api.example.com/items');
That is all. Under PHP-FPM the SDK registers a shutdown function that calls fastcgi_finish_request() and then sends. In a CLI script the batch goes out when the script ends. Long-running CLI workers: see Workers.
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 logs one line to the PHP error log and does nothing; your requests are never affected.
Configuration
new 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'. Body streams are not read unless the body is going to be recorded. |
max_body_bytes |
unlimited | Cut text bodies at this many bytes (on a UTF-8 character boundary). The record keeps the original size and truncated: true. |
capture_binary |
false |
Upload binary bodies. When off, only metadata (size, content type) is sent and the bytes are never read. |
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 |
– | function (array &$record): mixed called with the wire record before it is serialized; mutate it or return false to drop it. |
error_details |
– | function (mixed $error): mixed returning extra data stored as the error's details. A throwing hook is ignored. |
batch_bytes |
1048576 |
A batch is cut at about this size. |
flush_interval_ms |
1000 |
Long-running workers send at least this often. |
max_queue_bytes |
16777216 |
Upper bound of the records held in memory (also limited to a quarter of the free memory_limit). The oldest records are dropped beyond it. |
timeout_ms |
3000 |
Timeout of one send. |
connect_timeout_ms |
200 |
Connect timeout of one send. |
close_timeout_ms |
5000 |
flush() and close() stop after this long. |
in_progress_after_ms |
2000 |
A request still running at flush time and older than this is reported as in progress. |
compression |
'auto' |
'auto' (zstd if ext-zstd exists, else gzip), 'zstd', 'gzip' or 'none'. |
failure_threshold / circuit_open_ms |
3 / 30000 |
After this many failed sends in a row nobody tries for circuit_open_ms. |
auto_flush |
true |
Register the shutdown flush and, in CLI workers, flush by time and size. With false only flush() and close() send. |
long_running |
detected | true for CLI workers (default for the cli SAPI), false for request-bound processes. |
sender |
curl | An InspectorRest\Sender replacing the built-in curl transport. |
store |
APCu if available, else in-process | An InspectorRest\Store holding the state that outlives one request: circuit breaker, quota / suspension pause, invalid key, dropped counters. The SDK ships ApcuStore (shared by the workers of a pool) and MemoryStore (current process only). |
finish_request |
fastcgi_finish_request() |
For testing: function (): void called instead of fastcgi_finish_request() / litespeed_finish_request() before the shutdown send. |
clock |
microtime(true) |
For testing: function (): float returning the current time in seconds, used for the flush interval, back-off, circuit breaker and quota pause. |
Methods
| Method | |
|---|---|
flush() |
Sends everything recorded so far now. Bounded by close_timeout_ms; never throws. |
close() |
Final delivery attempt (requests still running are reported as in progress), then stops the inspector. |
tick() |
For loops that wait long between requests: sends when a time or size threshold is due. |
stats() |
Counters for diagnostics: state, captured / sent records, queued records, held bytes, send failures. |
Guzzle
$stack->push(GuzzleMiddleware::create($inspector, [ 'labels' => ['client' => 'billing-api'], // added to every request of this client ])); $client->get($url, ['inspector_labels' => ['op' => 'list']]); // labels of a single request
- Added with
$stack->push(...)the middleware sees the request as it goes on the wire (Content-Length, cookies included) and every redirect step is its own record. Added with$stack->unshift(...)it records the logical request after redirects. - 4xx/5xx responses are recorded with an error named
HttpError(also available asInspectorRest\HttpError), whether Guzzle throws orhttp_errorsis off. - Retries are not tracked: every request is one attempt.
- Request and response bodies are read from the PSR-7 streams after the response is there, and the streams are left as they were. Streams that cannot be rewound are recorded without a body (
omitted: "stream").
Lifecycle hooks
Any client can report through the inspector's methods. Events of one request are matched by request_id and merged into one record. They never throw.
| Method | Payload fields |
|---|---|
onRequest |
request_id, labels?, attempt? (default 1), method, url, headers?, proxy_url?, body? |
onResponse |
request_id, labels?, attempt?, status, headers?, duration_ms? |
onBody |
request_id, labels?, attempt?, bytes?, parse_ok?, read_ms?, raw_body? |
onRetry |
request_id, labels?, attempt?, policy?, stage?, delay_ms?, exhausted? |
onError |
request_id, labels?, attempt? (omit for a request-level error), phase?, error |
onSettled |
request_id, labels?, method?, url?, attempts?, outcome ('ok' or 'error'), duration_ms?, error? |
Bodies are strings, PSR-7 streams, InspectorRest\BodySource objects (an unread stream) or arrays (encoded as JSON). Use InspectorRest\Transport::newRequestId() for request ids. A request-level error (attempt omitted, or phase: 'domain') is kept even when it arrives after onSettled, as long as the batch has not been built, and makes the outcome error. Errors are recorded with their getPrevious() chain as cause.
Labels
Labels are string key-value pairs you can filter by in the app. They merge per key; later sources win:
- Automatic labels (below)
labelsof theInspector- The context set by
Labels::with($labels, $fn) - Labels of the request (middleware options,
inspector_labels)
Values are converted to strings; empty values and values that cannot be converted are dropped.
use InspectorRest\Labels; Labels::with(['tenant' => 'acme', 'job' => 'sync'], function () use ($client) { $client->get($url); // carries tenant=acme, job=sync });
The context is captured when a request starts, so it also applies to requests whose promises settle later.
| Automatic label | Value |
|---|---|
server_host |
gethostname() |
app_package |
Name from the nearest composer.json above the code that created the Inspector (also inside vendor). |
app_commit |
12-character commit of the same package: the repository's HEAD (found in parent directories too, worktrees included), else the commit Composer locked, else GIT_COMMIT / COMMIT_SHA / SOURCE_VERSION. |
They are resolved after the response has gone out, together with the first batch, and cached per calling file (in APCu when available).
How delivery works
- PHP-FPM and other request-bound processes. Records wait in memory. When the script ends the SDK calls
fastcgi_finish_request()(orlitespeed_finish_request()) so the client has its response, then sends one batch.fastcgi_finish_request()is only called when there is something to send. Sending does not release a session lock; if your application holds a session open until the end of the request, close it first (session_write_close()). - Long-running workers (the
cliSAPI): batches go out from inside the SDK calls oncebatch_bytesis queued orflush_interval_mshas passed, and when the script ends. Call$inspector->close()from your worker's shutdown handler (PHP does not run shutdown functions on SIGTERM unless you handle the signal). A failed batch is kept and re-sent with the samebatch_idand exponential back-off, withinmax_queue_bytes. - Ingest unreachable. One connect attempt of at most
connect_timeout_ms(200 ms), after the response. Afterfailure_thresholdfailures the circuit opens forcircuit_open_ms: no process of the pool tries again, and request-bound processes stop recording until it closes (the skipped requests are counted as dropped). Your requests are not slowed down in any case. - Everything is bounded. Records, bodies read from streams and batches are sized against the free
memory_limit; a download of several hundred MB cannot cause a "memory exhausted" fatal error. Bodies that do not fit are cut (truncated: true) or omitted. - Errors never reach your code. Every failure inside the SDK is swallowed and logged at most once a minute with
error_log().
| Ingest answers | The SDK |
|---|---|
2xx |
Done. rejected records ({ accepted, rejected: [{ index, reason }] }) are counted in the log. |
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 organization_suspended |
Stops recording (nothing is kept, nothing is serialized) and, after Retry-After (default 60 s), one process of the pool sends an empty batch to probe. Recording resumes when the probe succeeds. |
other 429, 408, 5xx (including 503 with Retry-After), network errors, timeouts |
Counts a failure for the circuit breaker (Retry-After opens it for that long). Long-running workers keep the batch and retry; request-bound processes cannot wait and count the records as dropped. |
401 |
Invalid or revoked key: the SDK disables itself and warns once. |
other 4xx |
The batch cannot be fixed by retrying: it is dropped, counted and reported once. |
Dropped records are reported to the app: the next batch carries dropped.records (and dropped.text_bodies / dropped.binary_bodies for bodies skipped because of memory limits).
APCu
With ext-apcu (and apc.enable_cli=1 for CLI) the circuit breaker, the quota / suspension pause, an invalid key and the dropped counters are shared by every worker of the pool, and the automatic labels are cached across requests. Without it each PHP process starts from a clean state: after a failure the next request tries again (still after its response, still bounded by the connect timeout), and after quota_exceeded every request is recorded and sent once before the pause is learned again.
Wire format
The SDK posts batches to POST {origin}/api/ingest with the header x-inspector-key. The format is the one of the Node SDK, defined by ingest.schema.json (JSON Schema draft 07): one record per request with its attempts, body descriptors (utf8, part or none with an omitted reason), error objects with a cause chain, and multipart/form-data (a batch part plus one part per binary body) when capture_binary is on. The body is gzip or zstd compressed (content-encoding). sdk.name is inspector-rest-sdk-php.
Development
composer install vendor/bin/phpunit
Tests validate every batch the SDK produces against the wire schema. tests/schema is a copy of the Node SDK's schema/ directory (scripts/sync-schema.sh refreshes it). The suite also starts real HTTP servers (php -S) and PHP child processes with a small memory_limit. APCu-specific tests run when the extension is enabled.
License
MIT