Repository navigation
feat: multi step api runner - #997
Conversation
…ting it Playwright 1.61 bundles its server code into coreBundle.js and no longer ships the codegen classes as importable modules, so the recorder's `playwright-core/lib/server/codegen/javascript` deep import no longer resolves. Vendor the minimal slice SyntheticsGenerator extends (_asLocator + _generateActionCall + JavaScriptFormatter) into src/formatter/codegen.ts, reusing the still-exported `iso` helpers (asLocator / formatObject / escapeWithQuotes) rather than vendoring the heavy locator logic. Formatter snapshots are unchanged. Also bump playwright/-chromium/-core to 1.61.0 (required for the native APIResponse TLS APIs) and refresh the device-descriptor Chrome UA in the options test that 1.61's bundled descriptors updated. Co-authored-by: Cursor <cursoragent@cursor.com>
Introduces apiJourney() DSL plus APIDriver, APINetworkManager, and the type-aware Runner/Gatherer/PluginManager branching needed to run API-only journeys without launching Chromium. Co-authored-by: Cursor <cursoragent@cursor.com>
Builds on the rebased api-journey commit: - PluginManager.output() now surfaces APINetworkManager results (previously dropped silently because of an instanceof NetworkManager check), and onStep() uses a proper union narrow instead of a lying cast. The browser/api branching is hidden behind a shared NetworkPlugin contract so the manager is transparent to journey type. - Runner only launches Chromium when at least one browser journey is scheduled; pure API suites skip launch entirely. - APIJourney now overrides _updateMonitor so 'synthetics push' registers it as an HTTP monitor instead of mislabeling it as browser. Journey base class gained a protected _setMonitor helper to make subclassing safe. - apiJourney.skip / apiJourney.only are now wired up. - APINetworkManager rewritten: only patches request.fetch (Playwright's helpers funnel through it, so the previous double-patch was double-counting requests), restores the prototype method on stop, handles fetch(Request, opts), wraps in try/finally so failed requests still leave a valid entry, drops dead Page/Frame barriers, surfaces status/headers/url/statusText. - APIJourney class trimmed: dead #cb / #driver fields removed; subclass now carries the http monitor override and forwards string|options upstream. - Reporter payload no longer carries browserDelay / browserconsole for API journeys; common_types updated accordingly. - Public API exports APIJourney / APIJourneyCallback / APIJourneyCallbackOpts / APIJourneyOptions / APIJourneyWithAnnotations. - Tests added: dsl/api-journey, plugins/api-network round-trip against a local HTTP server, plugins/plugin-manager API-driver coverage, core/api-runner end-to-end with browser launch spy, core/api-journey-register factory + skip/only wiring. Co-authored-by: Cursor <cursoragent@cursor.com>
Playwright's APIResponse doesn't expose securityDetails(), serverAddr(), or request/response timings (upstream microsoft/playwright#32647 and microsoft/playwright#34938 were both declined; see microsoft/playwright#40905 for the current ask). To still surface this for HTTPS API monitoring use cases (cert expiry, remote-address alerting, response size tracking), open a side-channel tls.connect() in parallel with each request and fold the result into the NetworkInfo entry: - securityDetails: issuer, subjectName, protocol, validFrom, validTo - remoteIPAddress / remotePort - coarse dns / connect / ssl timings Probes are cached per host:port within a journey and silently skipped for HTTP or on failure (timeout, refused, untrusted) so they never affect the actual request. Also derive request and response body bytes (Content-Length preferred, buffer fallback) and emit server.ip / server.port in the JSON reporter. Co-authored-by: Cursor <cursoragent@cursor.com>
- Empty step with no requests must not break network-event step attribution: the next step's requests must still be assigned to that step's reference identity (required for waterfall grouping). - API journeys must have isolated APIRequestContexts: a cookie set in journey A must not leak into journey B. - HTTPS journey verifies the full pipeline emits TLS securityDetails, remote address, and response body bytes. Co-authored-by: Cursor <cursoragent@cursor.com>
Splits the README usage section into "Browser journeys" and "API journeys (no browser)" so users discover apiJourney() without having to dig through the Elastic docs site. Adds a runnable example under examples/todos/api.journey.ts showing OAuth-style multi-step API checks. Co-authored-by: Cursor <cursoragent@cursor.com>
- Replace non-null assertions with explicit narrowing in api-tls and api-runner tests so the `@typescript-eslint/no-non-null-assertion` rule is satisfied. - Apply prettier formatting to api-tls.ts and json.test.ts. Co-authored-by: Cursor <cursoragent@cursor.com>
Heartbeat hands API monitor scripts to `elastic-synthetics` as inline source via `--inline`. When that source uses ESM (e.g. `import` / top-level await) — which is the natural shape for `apiJourney()` and `step()` imports — Node's `vm.runInContext` path falls over with `SyntaxError: Cannot use import statement outside a module`, silently dropping the run. Detect ESM-shaped inline source and execute it via a temporary `.mjs` module file resolved with a `Module._resolveFilename` alias so `@elastic/synthetics` keeps resolving to the agent-installed copy. The CommonJS fast path is unchanged. Co-authored-by: Cursor <cursoragent@cursor.com>
The new ESM inline loader path compiles the source as a regular module rather than running it through the new Function(...) wrapper, so `params` is no longer injected as an implicit local. The test needs to pull it out of the apiJourney callback args like the sibling browser test does. Co-authored-by: Cursor <cursoragent@cursor.com>
Address review findings from end-to-end review of the API journey work: - src/reporters/json.ts: `formatTLS` previously called `new Date(undefined * 1000).toISOString()` when a TLS probe resolved with `protocol` set but cert dates missing (malformed `valid_from` / `valid_to`). That throws `RangeError: Invalid time value` and sinks the entire `journey/end` document. Route the dates through a defensive `epochToIso` helper that returns `undefined` for non-finite inputs, and add a regression test. - src/plugins/api-tls.ts: For IP-literal hosts the `lookup` event never fires, so `dnsEnd` stayed at its `-1` sentinel and cascaded into `connect: -1`. Treat the missing DNS phase as `dns: 0` and measure `connect` from `dnsStart`, so the timing breakdown stays meaningful. Add a probe test that exercises this path. - src/plugins/api-network.ts: `_currentStep` was typed `Partial<Step>` but initialised to `null`, contradicting the shared `NetworkPlugin` shape. Widen the field type to `Partial<Step> | null`. - src/loader.ts: Drop the `journey(` / `apiJourney(` heuristic from `isModuleInlineSource`. The regex matched inside string literals and comments, silently routing legacy inline scripts through the ESM loader and stripping the implicit `step` / `page` / `params` injection. Key off `import` / `export` only — that's the contract documented in the README. Also register a best-effort `process.exit` cleanup hook for the materialised `mkdtempSync` directory so long-lived hosts don't accumulate tmp dirs. - __tests__/plugins/api-network.test.ts: Add a guard that exercises every `APIRequestContext` helper (`get`/`post`/`put`/`patch`/ `delete`/`head`/`fetch`) so a future Playwright that bypasses `this.fetch` on any of them stops being a silent capture loss. - __tests__/core/api-runner.test.ts: Add a mixed-mode test verifying that a suite with both a `journey()` and an `apiJourney()` launches Chromium exactly once and routes each journey through the right driver type. Co-authored-by: Cursor <cursoragent@cursor.com>
Mirror the existing browser-journey scaffold examples with API-journey counterparts so users adopting `npx @elastic/synthetics <dir>` see both monitoring shapes side by side. - templates/journeys/api-example.journey.ts: minimal `apiJourney` with two GET steps and status assertions, structurally parallel to the existing `example.journey.ts`. - templates/journeys/advanced-api-example.journey.ts and its `advanced-api-example-helpers.ts`: multi-step API journey demonstrating the recommended shape — small reusable step builders, shared state populated by earlier steps and consumed by later ones, with a thunk-based id deletion to make the registration vs. execution timing explicit. - templates/synthetics.config.ts: adds `params.apiUrl` defaulting to jsonplaceholder.typicode.com so the API examples run out of the box; users override per-environment for their own service. - templates/README.md: distinguishes browser vs. API journey examples and explains when to reach for each. Co-authored-by: Cursor <cursoragent@cursor.com>
`CLIMock.output()` returns only the last stdout chunk, and the existing test fed that into `JSON.parse`. On Linux CI a single chunk can hold multiple NDJSON events from the json reporter, which makes the parse throw `SyntaxError: Unexpected non-whitespace character after JSON at position N`. The test was therefore order- and flush-dependent and recently started flaking. Switch to the `cli.buffer()` accumulator (which join+split-by-line correctly reconstructs NDJSON regardless of chunk boundaries) and locate the `journey/start` event explicitly instead of assuming the last chunk holds exactly one event. A defensive `tryParse` swallows the rare partial-line case where the listener detaches mid-event, so the lookup keeps working without resorting to longer waits. Co-authored-by: Cursor <cursoragent@cursor.com>
…t 1.61 Playwright 1.61 (microsoft/playwright#40932) exposes APIResponse.securityDetails() and APIResponse.serverAddr(), returning the same shapes the browser network path already consumes. Drop the tls.connect() side-channel (api-tls.ts), its per-origin cache, and the probe-fold blocks in APINetworkManager in favour of reading cert info and remote address straight off the response used by the actual request. This gives true per-request fidelity (final hop on redirects), removes the extra parallel TLS handshake, and now also reports server.ip/port over plain HTTP. The synthesized dns/connect/ssl timings (which came from a separate socket) are gone. A small normalizeTLSProtocol keeps the "TLSv1.3" -> "TLS 1.3" shape the JSON reporter expects. Co-authored-by: Cursor <cursoragent@cursor.com>
mcapell
left a comment
There was a problem hiding this comment.
Overall looks great. I've added a few questions / comments, but I've been testing it locally and it works as expected.
The only thing we are missing is to update the push monitor feature. There are some type === "browser" gates in that logic (example), and I think we need to include the new "api" one.
| }, | ||
| not_after: new Date(tls.validTo * 1000).toISOString(), | ||
| not_before: new Date(tls.validFrom * 1000).toISOString(), | ||
| not_after: epochToIso(tls.validTo), |
There was a problem hiding this comment.
question: is this change needed for the apiJourney? The new implementation looks too defensive
There was a problem hiding this comment.
Kept — it guards a real crash: a malformed cert date makes new Date(...).toISOString() throw RangeError and sink the whole journey/end doc (regression test in json.test.ts). Trimmed the comment.
- Register API journeys as `api` monitor type (was `http`) and bundle them like browser monitors in push (buildMonitorSchema + dry-run extraction). - Emit ECS `server.ip`/`server.port` for API journeys only; browser output keeps the address under `http.response`. - Use monotonic `now()` for API network timings. - Abort push with a clear message when API monitors target Kibana < 9.6.0. - Tighten verbose comments across the API journey code. Co-authored-by: Cursor <cursoragent@cursor.com>
The existing api routing tests build SynthEvent structs by hand, so they never exercise decoding the JSON the synthetics agent actually emits. This adds TestE2EAPIJourneyAgentOutput, which feeds the exact ndjson an `apiJourney(...)` produces (captured from elastic/synthetics#997) through the same decode path production uses (json.Unmarshal into SynthEvent, as runCmd's json.Decoder does) and the real stream enricher. It pins the on-the-wire contract heartbeat depends on: * journey.type propagates to synthetics.journey.type: api * journey/network_info routes to the api.network dataset (matching the Fleet integration's api_network data stream) * API-only ECS server.ip/server.port from root_fields survive enrichment * the url string in root_fields is parsed into ECS url.* Verified against a live run of @elastic/synthetics@api-journey: the agent emits journey.type "api" on every event and carries server/tls/http under journey/network_info root_fields exactly as asserted here. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com>
Adds a live end-to-end run of the `api` monitor type that drives the real @elastic/synthetics agent (inline apiJourney against a local server) through the scenarios framework, complementing the fixture-based wire-level test. apiJourney() ships only in unreleased @elastic/synthetics, so: - The scenario is gated behind ELASTIC_SYNTHETICS_API_CAPABLE and pruned from the DB otherwise, so existing browser/lightweight jobs are unaffected. - A dedicated CI step installs a capable synthetics commit (elastic/synthetics#997, f2bf619) and runs only TestAPISummaries. Switch it to @elastic/synthetics@<release> and drop the env gate once that ships. The inline source is module-style (leading import) so the agent registers a real API journey instead of the implicit browser journey a bare script yields. Also modernizes two pre-existing loops in framework.go surfaced by --whole-files lint. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com>
Move the inline apiJourney-capable @elastic/synthetics install out of the Buildkite pipeline into a reusable `mage installSyntheticsAgent` goal so the same setup can be run locally with one command. The goal clones the pinned commit (elastic/synthetics#997), builds it, and installs from the local path (npm's git-dependency install fails with ENOTDIR during prepare). The commit is overridable via SYNTHETICS_COMMIT. Addresses review feedback from @v1v. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com>
…50802) * feat(heartbeat): add `api` monitor type for synthetics API journeys Heartbeat now recognises `monitor.type: api`, a new synthetics-driven monitor type that runs multi-step API checks via Playwright's `APIRequestContext` without launching Chromium. API monitors reuse the existing synthexec runtime that browser monitors use (same project/inline source pipeline, same SynthEvent stream, same wrappers/summarizer plugin set, same `synthetics` data stream). The only differences are: * A new `x-pack/heartbeat/monitors/api` package registers the `api` plugin and bridges it to `browser.NewSourceJob`. The `ELASTIC_SYNTHETICS_CAPABLE` env gate (which exists to keep browser monitors from running on machines without GUI libs) is intentionally skipped — API journeys never launch Chromium. * `browser/sourcejob.extraArgs` now filters browser-only CLI flags (`--sandbox`, `--screenshots`, `--throttling`/`--no-throttling`) when the monitor type is `api`. `--playwright-options` and `--ignore-https-errors` are still forwarded since both apply to `APIRequestContext`. * `journey/network_info` events from API journeys are routed to a new `synthetics.api.network` dataset (vs. `browser.network`), so ingest pipelines and Kibana dashboards can branch cleanly without inspecting `journey.type` on every doc. * `SynthEvent.Journey.Type` (new) is propagated through `ToMap()` so downstream consumers see `synthetics.journey.type: api`. Older synthetics agents that don't emit the field continue to be treated as browser for back-compat. Central plumbing change: a new `stdfields.IsSyntheticsType(t)` helper returns true for `browser` and `api`. The four call sites that used to special-case `"browser"` (wrappers, summarizer, factory data-stream auto-config, logger network-info extraction) now use the helper. `heartbeat.config` adds a default scaling limit + `SYNTHETICS_LIMIT_API` env var for the new type. Requires `@elastic/synthetics` >= <TBD-version> on the host (the release that introduces the `apiJourney(...)` DSL, elastic/synthetics#997). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(heartbeat): satisfy golangci-lint on files touched by api monitor PR The api-monitor PR enabled CI's `--whole-files` golangci-lint mode on the files it modified, surfacing seven pre-existing violations (plus several more masked by `max-same-issues: 3`) that had been ignored while those files were untouched on main: * heartbeat/monitors/logger/logger.go: `extractRunInfo` was doing five unchecked type assertions on `interface{}` values pulled out of the event, e.g. `monType.(string)`, which trip `errcheck`'s `check-type-assertions: true` and would panic on a malformed event. Switched to the `, ok` form and append a typed error to the existing aggregated-error path so callers see "monitor.type is not a string, got <T>" instead of a runtime panic. * heartbeat/monitors/wrappers/summarizer/summarizer.go: changed `Summarizer.contsRemaining` from `uint16` to `int` so that `contsRemaining += len(conts)` no longer needs the `uint16(len(conts))` narrowing conversion that gosec G115 flags. The field is only used as an internal "still to process" counter compared against 0; widening to int is semantically identical. * heartbeat/monitors/factory.go, heartbeat/config/config.go, heartbeat/monitors/logger/logger.go, x-pack/heartbeat/monitors/browser/sourcejob.go, x-pack/heartbeat/monitors/browser/synthexec/synthtypes.go: annotated the remaining `logp.L()` fallbacks with targeted `//nolint:forbidigo` directives that explain why the call site doesn't have a contextual `*logp.Logger` (factory predates per-beat loggers in FactoryParams; preProcessors is invoked from reload paths; ToMap/extraArgs/StdFields are pure mapping helpers with no logger handle; getLogger() is the documented pre- SetLogger fallback; DefaultConfig runs before the beat-scoped logger is constructed). These match the dozens of other `logp.L()` callers across `heartbeat/` that pre-date the "accept *logp.Logger as a parameter" rule and a real refactor is tracked separately. * In `NewFactory`, hoisted `logger := logp.L()` to a local so the struct literal stays `goimports`-aligned with the `//nolint` directive sitting next to the assignment instead of inside the field block. Verified locally with the same filter CI uses (`--new-from-patch ... --new=false --whole-files`) against golangci-lint v2.5.0 on `./heartbeat/...` and `./x-pack/heartbeat/...`: 0 issues. All affected unit tests still pass. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * fix(heartbeat): align api journey network dataset with integration package `journey/network_info` events emitted by API journeys were being routed to `synthetics.api.network`, but the Fleet `synthetics` integration package defines the companion stream as `data_stream/api_network/manifest.yml` with `dataset: api.network`. That mismatch caused Heartbeat to write to an auto-created `synthetics-synthetics.api.network-default` data stream that the Fleet-generated agent API key was not scoped to, and Elasticsearch returned `security_exception` / 403 — every API journey network event was silently dropped. Use `api.network` so the routed dataset matches the package, the agent API key includes the right `create_doc` privilege, and the documents land in `synthetics-api.network-default` like the rest of the synthetics integration. The companion-side fix — Fleet must actually enable the `api_network` stream for API monitors — lives in the linked Kibana PR (`format_synthetics_policy.ts`). Without both halves the API key is still missing the privilege. Co-authored-by: Cursor <cursoragent@cursor.com> * test(heartbeat): add wire-level e2e for apiJourney agent output The existing api routing tests build SynthEvent structs by hand, so they never exercise decoding the JSON the synthetics agent actually emits. This adds TestE2EAPIJourneyAgentOutput, which feeds the exact ndjson an `apiJourney(...)` produces (captured from elastic/synthetics#997) through the same decode path production uses (json.Unmarshal into SynthEvent, as runCmd's json.Decoder does) and the real stream enricher. It pins the on-the-wire contract heartbeat depends on: * journey.type propagates to synthetics.journey.type: api * journey/network_info routes to the api.network dataset (matching the Fleet integration's api_network data stream) * API-only ECS server.ip/server.port from root_fields survive enrichment * the url string in root_fields is parsed into ECS url.* Verified against a live run of @elastic/synthetics@api-journey: the agent emits journey.type "api" on every event and carries server/tls/http under journey/network_info root_fields exactly as asserted here. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * style(heartbeat): tighten verbose comments in api monitor PR Review pass on the comments this PR introduced: condense multi-line comments to single lines where the "why" fits, and trim the rest. Most notably the 10-line dataset-routing block in enrich.go and the package/ doc comments in api.go, config.go, sourcejob.go, stdfields.go and the tests. Required //nolint justifications are kept. No behavior change. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * feat(heartbeat): raise default api monitor concurrency to 8 The api monitor type initially reused browser's default job limit of 2, but that ceiling exists because each browser run launches a full Chromium instance. API journeys run the same Node.js agent without Chromium and only issue HTTP requests, so they are far lighter and can safely run at higher concurrency. Default to 8 (still bounding Node process fan-out, unlike the unbounded pure-Go lightweight types) and keep it overridable via SYNTHETICS_LIMIT_API. Adds default + override test coverage. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * fix(heartbeat): set api monitor concurrency to 4 based on benchmark The previous default of 8 was a guess that assumed API journeys were dramatically lighter than browser. Benchmarking the actual agent (@elastic/synthetics api-journey branch) on the same host told a different story: * API journey run: ~210 MB peak RSS, ~1.1s wall * browser journey run: ~460 MB peak RSS, ~1.1s wall The Node/synthetics runtime (bundled Playwright + esbuild loader) has a heavy baseline, so an API run is only ~2.2x lighter than browser, not the 4x+ assumed. Anchoring to browser's limit of 2 (a ~920 MB envelope for the type), ~4 API runs fit the same memory budget (4x210 ~= 840 MB); 8 would nearly double the browser memory ceiling. Wall time is comparable, so memory is the binding constraint. Default to 4, still overridable via SYNTHETICS_LIMIT_API. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * fix(heartbeat): address api monitor review feedback - Enforce ELASTIC_SYNTHETICS_CAPABLE gate in the api plugin: API journeys run the same Node.js agent as browser and it's only present where that env is set, so the gate must apply here too. - Register the api plugin with browser's params-insensitive HashConfig (via RegisterWithHashFunc) so Fleet parameter pushes don't cause unnecessary monitor stop/restarts. Exported browser.HashConfig for reuse. - IsSyntheticsType now matches the registered aliases (synthetic, synthetics/synthetic, synthetics/api) in addition to browser/api. - changelog: set PR link and @elastic/synthetics >= 1.25.0. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * fix(heartbeat): more api monitor review nits - Remove the private SourceJob.plugin() shim; callers use exported Plugin(). - Include the monitor type in the StdFields deserialize warning instead of hardcoding "browser", now that SourceJob backs both browser and api. - Use assert (not require) for the non-fatal checks in the api/browser extraArgs and IsSyntheticsType tests. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * fix(heartbeat): satisfy modernize linter on api monitor PR files CI runs golangci-lint in --whole-files mode on files this PR touches, which surfaced modernize violations (pre-existing plus a few from this PR): interface{} -> any, C-style loops -> range-over-int, and an unneeded loop-var copy. No behavior change. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * test(heartbeat): cover api plugin registration and capability gate Adds api_test.go, closing the biggest coverage gap for the api monitor type (api.create had no direct tests): - TestAPIPluginRegistered: api and its synthetics/api alias resolve to the api plugin and carry a params-insensitive HashConfig. - TestAPICreateRequiresSyntheticsCapable: create returns the not-synthetics-capable error unless ELASTIC_SYNTHETICS_CAPABLE is set, pinning the gate mcapell flagged. - TestAPICreatePassesGateWhenCapable: with the gate open (non-root), create builds a single-endpoint plugin off the shared browser pipeline. - TestAPIHashIgnoresParams: the registered hash ignores params and matches browser.HashConfig, so Fleet param pushes are no-op reloads. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * test(heartbeat): add real apiJourney e2e scenario (pinned agent) Adds a live end-to-end run of the `api` monitor type that drives the real @elastic/synthetics agent (inline apiJourney against a local server) through the scenarios framework, complementing the fixture-based wire-level test. apiJourney() ships only in unreleased @elastic/synthetics, so: - The scenario is gated behind ELASTIC_SYNTHETICS_API_CAPABLE and pruned from the DB otherwise, so existing browser/lightweight jobs are unaffected. - A dedicated CI step installs a capable synthetics commit (elastic/synthetics#997, f2bf619) and runs only TestAPISummaries. Switch it to @elastic/synthetics@<release> and drop the env gate once that ships. The inline source is module-style (leading import) so the agent registers a real API journey instead of the implicit browser journey a bare script yields. Also modernizes two pre-existing loops in framework.go surfaced by --whole-files lint. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * ci(heartbeat): run api journey e2e in the existing unit-test step Rather than a separate CI step, install the pinned apiJourney-capable synthetics commit in the existing x-pack/heartbeat Ubuntu unit-test job and set ELASTIC_SYNTHETICS_API_CAPABLE=true. Browser and api scenarios then run off one agent install, avoiding a duplicate Playwright/Chromium download (the browser scenarios already pull it there). Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * test(heartbeat): add failing api journey down-path scenario Mirrors the existing failing-browser scenario: an inline apiJourney that throws after the request so the journey ends down. Tagged `api`, so TestAPISummaries now exercises both the up and down summary paths against the real agent (request.get doesn't throw on non-2xx by itself). Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * fix(heartbeat): replace remaining interface{} with any in api PR tests golangci-lint modernize flagged interface{} usages in browser test files touched by this PR (--whole-files mode reports the entire changed file). Convert them to the any alias to keep the lint (ubuntu) check green. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * ci(heartbeat): make pinned synthetics install robust against ENOTDIR Installing the pinned apiJourney-capable @elastic/synthetics git commit over the base image's released global install fails npm's atomic rename with ENOTDIR when the existing entry is a symlink, so the unit-test step never reached mage build. Remove the existing global package first, then install the pinned commit, and smoke-check the binary. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * ci(heartbeat): install pinned synthetics into a private npm prefix Removing the base image's global @elastic/synthetics before installing the pinned git commit still hit npm's ENOTDIR on the atomic rename-aside, so the unit-test step never reached mage build. Install into a private empty npm prefix ($HOME/.npm-apijourney) instead: with nothing to rename aside the ENOTDIR can't occur, we stop mutating the shared global, and prepending the prefix bin keeps elastic-synthetics (and the inline api journeys) on the pinned apiJourney-capable build. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * ci(heartbeat): escape shell vars from Buildkite interpolation Buildkite interpolates ${VAR} at pipeline-upload time, so ${HOME}, ${PATH} and ${NPM_CONFIG_PREFIX} were substituted with the upload-time environment (NPM_CONFIG_PREFIX unset -> empty), which clobbered PATH and made mkdir fail. Escape them with $$ so they expand in the runtime shell instead. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * ci(heartbeat): build pinned synthetics from source instead of git dep npm's git-dependency install (github:elastic/synthetics#<sha>) fails with ENOTDIR during its prepare step, even into a fresh private prefix, so the unit-test step never reached mage build. Clone the pinned commit, build it, and install from the local path (npm install -g .) into the private prefix instead - the local-path install avoids npm's broken git-dep prepare flow. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * ci(heartbeat): extract synthetics agent install into a mage goal Move the inline apiJourney-capable @elastic/synthetics install out of the Buildkite pipeline into a reusable `mage installSyntheticsAgent` goal so the same setup can be run locally with one command. The goal clones the pinned commit (elastic/synthetics#997), builds it, and installs from the local path (npm's git-dependency install fails with ENOTDIR during prepare). The commit is overridable via SYNTHETICS_COMMIT. Addresses review feedback from @v1v. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * ci(heartbeat): install pinned synthetics into a private npm prefix from the mage goal Build 30685 failed with "No elastic-synthetics executable found for nodejs 22.20.0": the mage goal did `npm rm -g` then a default-global install, which broke the CI image's asdf shim so the agent wasn't resolvable at test time. Restore the private-prefix approach that passed in build 30684: the pipeline exports NPM_CONFIG_PREFIX/PATH so both the goal's `npm install -g .` and the subsequent `mage build unitTest` resolve the pinned build and bypass asdf shims. The clone/build/install steps stay in the mage goal per review feedback. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * ci(heartbeat): keep pinned synthetics checkout on disk in the mage goal Build 30686 failed the api scenarios with "Cannot use import statement outside a module": the mage goal cloned into a temp dir and deleted it right after `npm install -g .`. That global install links back to the checkout's built dist, so deleting it left the agent running unbuilt src/*.ts, which can't load ESM inline apiJourney scripts. Clone into a stable path and leave it on disk (removing only stale copies up front), matching the inline install that passed in build 30684. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * ci(heartbeat): drop redundant npm prefix env from unit-test step Per review feedback, make the synthetics install a single command. The NPM_CONFIG_PREFIX/PATH/mkdir lines were a leftover from an earlier ENOTDIR workaround and are no-ops now: under asdf the pinned agent always installs to the node global (verified by the "Reshimming asdf nodejs" step) and the tests resolve it via the asdf shim, exactly like the go-integ step's plain `npm install -g`. The step now just runs `mage installSyntheticsAgent`, which clones, builds, and installs the pinned commit on its own. Assisted-By: Cursor Co-authored-by: Cursor <cursoragent@cursor.com> * fix(heartbeat/browser): IsAPI() now matches synthetics/api alias Config.IsAPI() only matched the canonical 'api' type, so a monitor configured with type: synthetics/api (which Fleet emits) fell into the browser branch of extraArgs and received --sandbox/--screenshots/ --throttling flags that break API-only, no-Chromium runs. Extract IsAPIType() into stdfields alongside IsSyntheticsType() so all alias knowledge lives in one place. Make TestExtraArgsForAPIMonitor table-driven over both 'api' and 'synthetics/api' to pin the regression. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
|
🎉 This PR is included in version 1.25.0 🎉 The release is available on: Your semantic-release bot 📦🚀 |
…streams (#19178) * [Synthetics] Add `synthetics/api` input + `api` / `api.network` data streams Adds the Fleet integration package side of API Journey monitors so private locations can deliver `monitor.type: api` policies to Heartbeat. Companion to elastic/synthetics#997 (agent), elastic/beats#50802 (Heartbeat input), and elastic/kibana#270874 (UI / SO / project monitor). WHY: elastic/kibana#270874 has a TODO in `format_synthetics_policy.ts` explicitly waiting on this package — `inputs.find(input.type === 'synthetics/api')` resolves to undefined until a `synthetics >= 1.7.0` package is installed, so private-location API monitors return `hasInput: false` and surface a "package needs upgrade" warning. That PR also explicitly says the new input must be designed fresh, NOT forked from `synthetics/browser`, because the var schema differs. WHAT: * manifest.yml: bump 1.6.1 -> 1.7.0 and add `synthetics/api` input. * New data stream `api` (dataset `api`) — journey/step events for API monitors. ILM 30d hot / 365d delete (matches browser). Vars are the API-correct subset of browser: - drops `screenshots`, `throttling.config`, `synthetics_args` because `(*SourceJob).extraArgs` in elastic/beats#50802 strips `--sandbox`, `--screenshots`, `--throttling`/`--no-throttling` for `monitor.type: api`. - keeps `playwright_options` and `ignore_https_errors` (both supported by Playwright's APIRequestContext). - default `type: api`. Fields mirror browser, with `monitor.type: api`, a new `synthetics.journey.type` keyword (emitted by `synthexec/synthtypes.go` in elastic/beats#50802 and `JSONReporter` in elastic/synthetics#997), and the Chromium-only `browser.experience` / `browser.relative_trace` groups removed. * New data stream `api_network` (dataset `api.network`) — the dataset `synthexec/enrich.go` in elastic/beats#50802 routes API-journey `journey/network_info` events to. ILM 1d hot / 14d delete (matches browser_network). Fields mirror browser_network (TLS / server / resolve groups already covered by ECS) with the same `journey.type` addition. No stream-level vars — inherits from the parent `synthetics/api` input, same model as `browser_network`. Validated locally with `elastic-package format` and `elastic-package check` (lint + build green). Co-authored-by: Cursor <cursoragent@cursor.com> * [Synthetics] Align api/api.network mappings with existing streams Add kibanaUrl, map observer.geo.name as keyword, drop leftover docker TODOs, and point the 1.9.0 changelog at this PR. * [Synthetics] Map API network server.* and http.response.status Index server.ip/port and the agent-emitted status code on api.network so Discover/KQL work under dynamic: false. --------- Co-authored-by: Cursor <cursoragent@cursor.com>
…and add/edit form Introduces a new "API Journey" monitor type that runs multi-step API checks via Playwright's APIRequestContext (no browser launch). Mirrors the runtime/SO shape of Browser so Heartbeat / Fleet integration only needs to branch on `monitor.type === "api"`. * common/runtime_types/monitor_management/monitor_configs.ts: - MonitorTypeEnum.API = 'api' - FormMonitorType.API = 'api' (was previously a stub named API_MULTISTEP) * common/runtime_types/monitor_management/monitor_types.ts: APIFields / APISimpleFields / APIAdvancedFields codecs (structurally identical to Browser; Heartbeat's `api` plugin filters browser-only flags). * common/constants/monitor_defaults.ts: DEFAULT_API_SIMPLE_FIELDS + DEFAULT_API_ADVANCED_FIELDS wired into DEFAULT_FIELDS[MonitorTypeEnum.API]. * monitor_add_edit form (defaults/field_config/form_config/formatter/ validation/step_config): adds an "API Journey" tile with apmTrace icon, inline-script source as default, no throttling/screenshots in advanced options, and form-side validation that omits THROTTLING_CONFIG. Aligns Kibana with elastic/synthetics#997 (agent) and elastic/beats#50802 (Heartbeat input). Co-authored-by: Cursor <cursoragent@cursor.com>
…and add/edit form Introduces a new "API Journey" monitor type that runs multi-step API checks via Playwright's APIRequestContext (no browser launch). Mirrors the runtime/SO shape of Browser so Heartbeat / Fleet integration only needs to branch on `monitor.type === "api"`. * common/runtime_types/monitor_management/monitor_configs.ts: - MonitorTypeEnum.API = 'api' - FormMonitorType.API = 'api' (was previously a stub named API_MULTISTEP) * common/runtime_types/monitor_management/monitor_types.ts: APIFields / APISimpleFields / APIAdvancedFields codecs (structurally identical to Browser; Heartbeat's `api` plugin filters browser-only flags). * common/constants/monitor_defaults.ts: DEFAULT_API_SIMPLE_FIELDS + DEFAULT_API_ADVANCED_FIELDS wired into DEFAULT_FIELDS[MonitorTypeEnum.API]. * monitor_add_edit form (defaults/field_config/form_config/formatter/ validation/step_config): adds an "API Journey" tile with apmTrace icon, inline-script source as default, no throttling/screenshots in advanced options, and form-side validation that omits THROTTLING_CONFIG. Aligns Kibana with elastic/synthetics#997 (agent) and elastic/beats#50802 (Heartbeat input). Co-authored-by: Cursor <cursoragent@cursor.com>
…and add/edit form Introduces a new "API Journey" monitor type that runs multi-step API checks via Playwright's APIRequestContext (no browser launch). Mirrors the runtime/SO shape of Browser so Heartbeat / Fleet integration only needs to branch on `monitor.type === "api"`. * common/runtime_types/monitor_management/monitor_configs.ts: - MonitorTypeEnum.API = 'api' - FormMonitorType.API = 'api' (was previously a stub named API_MULTISTEP) * common/runtime_types/monitor_management/monitor_types.ts: APIFields / APISimpleFields / APIAdvancedFields codecs (structurally identical to Browser; Heartbeat's `api` plugin filters browser-only flags). * common/constants/monitor_defaults.ts: DEFAULT_API_SIMPLE_FIELDS + DEFAULT_API_ADVANCED_FIELDS wired into DEFAULT_FIELDS[MonitorTypeEnum.API]. * monitor_add_edit form (defaults/field_config/form_config/formatter/ validation/step_config): adds an "API Journey" tile with apmTrace icon, inline-script source as default, no throttling/screenshots in advanced options, and form-side validation that omits THROTTLING_CONFIG. Aligns Kibana with elastic/synthetics#997 (agent) and elastic/beats#50802 (Heartbeat input). Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: run inline api monitors as apiJourney, not journey Heartbeat sets ELASTIC_SYNTHETICS_MONITOR_TYPE=api on the child process for Fleet/Kibana `api` monitors, but the --inline runner's legacy (non-import) source path always wrapped the piped script in a plain journey(...) call and never read that variable. journey.type therefore stayed "browser", so Gatherer.setupDriver always built a full browser Driver (never the APIDriver added in #997), Chromium always launched, and network capture never started -- API Journey monitors produced no journey/network_info events at all. loadInlineScript now checks ELASTIC_SYNTHETICS_MONITOR_TYPE and wraps the script in apiJourney(...) instead when it's "api", matching the apiJourney(...) module-import path that already worked correctly. Verified locally: reverting this change reproduces the bug (the new test in cli.test.ts times out because a full browser launches instead of the fast, browser-less API path), and the same revert with a bare CLI invocation shows the script executing as a browser journey (screenshot/block events, no journey/network_info). * style: fix prettier formatting in cli.test.ts CI lint job failed format:check on the new inline api monitor test's multi-line args array. * fix: reduce e2e compatibility-matrix flakiness Downloaded the junit artifacts from two flaky `test (X.Y.Z)` CI runs (the console log shows nothing on failure since --reporter junit only writes to the XML file). Both showed the same cause: Monitor ... check failed: error executing step: page.goto: Timeout 50000ms exceeded. The browser-monitor e2e check navigates to the live elastic.co homepage with Playwright's default waitUntil: 'load', which blocks until every resource on the page (analytics, fonts, ads) finishes. Under CI resource contention (full ES/Kibana/Fleet/Agent stack running alongside it) that occasionally exceeds the monitor's 50s navigation timeout. Waiting for 'domcontentloaded' instead is enough to prove the browser-monitor pipeline works end-to-end and isn't coupled to how long elastic.co's third-party assets take to load. Also stopped `elastic-package stack down` from printing a scary (but harmless) "Error: tearing down the stack failed" line on every fresh runner in setup_integration.sh -- there's nothing to tear down yet, and it was misleading during triage of the actual failure above. * feat: add --inline-api flag and document --inline's browser default --inline previously only switched to an API journey via the Heartbeat-only ELASTIC_SYNTHETICS_MONITOR_TYPE=api env var, which wasn't discoverable and had no equivalent for invoking the CLI by hand. Document that --inline runs as a browser journey by default in its own help text, and add --inline-api as the explicit CLI opt-in, wired through loader.ts's isInlineAPIMonitor alongside the env var.
## ✨ Summary Adds **API Journey** monitors to Synthetics: Playwright `APIRequestContext` journeys (`apiJourney(...)`) that run multi-step HTTP checks without launching a browser. ## 🚀 Rollout - **Private locations:** supported by default. - **Elastic-managed locations:** disabled by default. Enable them explicitly in `kibana.yml`: ```yaml xpack.uptime.enableApiJourneyPublicLocations: true ``` The setting is enforced consistently for the create/edit form, bulk location changes, direct monitor APIs, Test now, monitor inspection, and project-monitor pushes. The browser UI receives the setting so public locations are selectable only when it is enabled. ## 📦 What’s included - API monitor types, defaults, validation, and the Create/Edit **API Journey** form. - Fleet support for the `synthetics/api` input and `api.network` stream. - Management, overview, details, error, test-run, filtering, and badge support for step-based API journeys. - Private-location policy formatting, API script encoding, project monitor normalization, and global parameter interpolation. | Related | | | --- | --- | | DSL | [elastic/synthetics#997](elastic/synthetics#997) | | Heartbeat input | [elastic/beats#50802](elastic/beats#50802) | ## 🖼️ Screenshot  ## 🧪 Test plan - [x] Jest: monitor validation (private default and public-flag cases), location-support utility, bulk location flyout, and bulk update API. - [x] `node scripts/type_check --project x-pack/solutions/observability/plugins/synthetics/tsconfig.json` - [x] ESLint and i18n validation. - [x] `node scripts/check.js --scope=branch` - [ ] Manual: private location with a Heartbeat build containing elastic/beats#50802. - [ ] Manual: Elastic-managed location with `xpack.uptime.enableApiJourneyPublicLocations: true` and an agent containing elastic/synthetics#997.
## ✨ Summary Adds **API Journey** monitors to Synthetics: Playwright `APIRequestContext` journeys (`apiJourney(...)`) that run multi-step HTTP checks without launching a browser. ## 🚀 Rollout - **Private locations:** supported by default. - **Elastic-managed locations:** disabled by default. Enable them explicitly in `kibana.yml`: ```yaml xpack.uptime.enableApiJourneyPublicLocations: true ``` The setting is enforced consistently for the create/edit form, bulk location changes, direct monitor APIs, Test now, monitor inspection, and project-monitor pushes. The browser UI receives the setting so public locations are selectable only when it is enabled. ## 📦 What’s included - API monitor types, defaults, validation, and the Create/Edit **API Journey** form. - Fleet support for the `synthetics/api` input and `api.network` stream. - Management, overview, details, error, test-run, filtering, and badge support for step-based API journeys. - Private-location policy formatting, API script encoding, project monitor normalization, and global parameter interpolation. | Related | | | --- | --- | | DSL | [elastic/synthetics#997](elastic/synthetics#997) | | Heartbeat input | [elastic/beats#50802](elastic/beats#50802) | ## 🖼️ Screenshot  ## 🧪 Test plan - [x] Jest: monitor validation (private default and public-flag cases), location-support utility, bulk location flyout, and bulk update API. - [x] `node scripts/type_check --project x-pack/solutions/observability/plugins/synthetics/tsconfig.json` - [x] ESLint and i18n validation. - [x] `node scripts/check.js --scope=branch` - [ ] Manual: private location with a Heartbeat build containing elastic/beats#50802. - [ ] Manual: Elastic-managed location with `xpack.uptime.enableApiJourneyPublicLocations: true` and an agent containing elastic/synthetics#997.
## ✨ Summary Adds **API Journey** monitors to Synthetics: Playwright `APIRequestContext` journeys (`apiJourney(...)`) that run multi-step HTTP checks without launching a browser. ## 🚀 Rollout - **Private locations:** supported by default. - **Elastic-managed locations:** disabled by default. Enable them explicitly in `kibana.yml`: ```yaml xpack.uptime.enableApiJourneyPublicLocations: true ``` The setting is enforced consistently for the create/edit form, bulk location changes, direct monitor APIs, Test now, monitor inspection, and project-monitor pushes. The browser UI receives the setting so public locations are selectable only when it is enabled. ## 📦 What’s included - API monitor types, defaults, validation, and the Create/Edit **API Journey** form. - Fleet support for the `synthetics/api` input and `api.network` stream. - Management, overview, details, error, test-run, filtering, and badge support for step-based API journeys. - Private-location policy formatting, API script encoding, project monitor normalization, and global parameter interpolation. | Related | | | --- | --- | | DSL | [elastic/synthetics#997](elastic/synthetics#997) | | Heartbeat input | [elastic/beats#50802](elastic/beats#50802) | ## 🖼️ Screenshot  ## 🧪 Test plan - [x] Jest: monitor validation (private default and public-flag cases), location-support utility, bulk location flyout, and bulk update API. - [x] `node scripts/type_check --project x-pack/solutions/observability/plugins/synthetics/tsconfig.json` - [x] ESLint and i18n validation. - [x] `node scripts/check.js --scope=branch` - [ ] Manual: private location with a Heartbeat build containing elastic/beats#50802. - [ ] Manual: Elastic-managed location with `xpack.uptime.enableApiJourneyPublicLocations: true` and an agent containing elastic/synthetics#997.
Summary
Adds
apiJourney(...)— runs API-only checks without launching a browser. Same DSL shape asjourney(...), but the callback receives an isolatedAPIRequestContextinstead of aPage/Browserdriver. Pushes to Kibana as an HTTP-type monitor.Closes
APIRequestContextelastic/synthetics-dev#464What's in the PR
APIJourneyDSL — subclass ofJourney, monitor type'http', fullmonitor.use(...)/params/expect/.skip/.onlysupport.launchBrowserif no browser journeys are registered.APINetworkManager— interceptsAPIRequestContext.fetch(the single funnel) and captures URL, method, status, headers (redacted), body bytes, timings, and step attribution.APIResponse.securityDetails()(cert issuer / subject /validFrom/validTo/ protocol) andAPIResponse.serverAddr()(remote IP / port) straight off the response from the actual request, mirroring the browser network path. HTTPS and plain HTTP surfaceserver.ip/server.port; cert info follows redirects to the final hop. No extra socket or parallel handshake.coreBundle.jsand no longer exports the recorder's codegen classes, so the minimal sliceSyntheticsGeneratorextends (_asLocator/_generateActionCall/JavaScriptFormatter) is vendored intosrc/formatter/codegen.ts, reusing Playwright's still-exportedisohelpers. Recorder snapshots are unchanged.PluginManager— commonNetworkPlugininterface so API network data isn't dropped at journey-end.JSONReporter— emitsjourney.type: 'api', omits browser-only fields, surfacestls.*andserver.ip/server.port.Tests
All green across:
dsl/api-journey,core/api-journey-register— DSL + factoryplugins/api-network,plugins/plugin-manager— capture, native TLS / remote-addr, orchestrationcore/api-runner— e2e, no-browser, failure path, empty-step grouping, cookie isolation, HTTPS with TLS / IP / body-bytesreporters/json—type: 'api'emission, server / TLS fieldsformatter/javascript— recorder codegen snapshots unchanged against the vendored generatorManual verification
Ran the built CLI against
api.github.com,httpbin.org, and a local self-signed HTTPS server. Confirmed: no browser spawned, fulltls.*/server.*/body.bytespopulated, cookies isolated, redaction still works.Docs
examples/todos/api.journey.tsrunnable example added.Follow-ups (separate PRs)
journey.type: 'api'in waterfall, monitor list, data stream. Open question from [proposal] Lightweight API journeys DSL #900 needs an answer.elastic/enhancements#25818(Atos France).dns,connect,ssl,wait,receive) —APIResponsedoesn't expose per-phase timings; needs Nodehttp.Agenthooks (or a future Playwright API).microsoft/playwright#32613); could complement the response fields.