Skip to content
RouteSpear
Documentation
Documentation menu

Built-in JavaScript SDK API reference

Complete metric and run APIs plus synchronous HTTP, DNS, TCP, timing and logging options.

Select JavaScript (built-in) (js) and import the only available module:

const rs = require('routespear');

The bundled engine runs inside routespear-jsengine; the operator enables -script-execute-js. It is distinct from Node.js. There is no Node process, fs, npm module loading, browser DOM or global fetch. Its host networking methods below are synchronous. Do not assume timers, an event loop, promises or browser APIs merely because the code is JavaScript.

Metric methods

Metric methods immediately write one JSON line and return undefined, except the stop function returned by timer. options is an optional object. labels is an object whose values become strings. Observe the shared metric names, semantics and budgets.

Method Signature Options and behavior
rs.emit emit(metric) Emit a complete raw wire object. Required fields and values must already be valid.
rs.gauge gauge(name, value, options?) {unit: '', labels: {...}}; unit defaults empty.
rs.counter counter(name, value, options?) {unit: 'count', labels: {...}, cumulative: false}; emits delta unless cumulative is true.
rs.duration duration(name, milliseconds, options?) {labels: {...}}; fixed unit ms.
rs.ratio ratio(name, value, options?) {labels: {...}}; fraction 0–1, fixed unit ratio.
rs.bool bool(name, value, options?) {labels: {...}}; JavaScript truthiness maps to 1/0. "false" is truthy; pass a boolean.
rs.distribution distribution(name, values, options?) Number array; {unit: '', bounds: [...], labels: {...}}. Empty/omitted bounds select standard buckets.
rs.timer timer(name, options?) {labels: {...}}; returns a function that emits elapsed duration and returns milliseconds when called.

The returned timer function measures from its original start. Calling it twice emits twice; it is not automatically reset or disposed. Use try/finally when the duration should be emitted even if work throws.

Run helpers

Method Return and behavior
rs.args() Parsed stdin JSON, cached; empty input gives {}, invalid JSON throws.
rs.context() Cached agent, test, run object with label maps; see context schema.
rs.target() Configured target string, or empty string.
rs.testId() Check ID string.
rs.timeoutMs() Runtime budget in milliseconds; not a live remaining-time counter.
rs.secret(name) Named declared credential; missing references or read failures throw. Never emit/log the returned value.
rs.now() Monotonic elapsed milliseconds since this engine run began; not an epoch timestamp.
rs.sleep(milliseconds) Synchronous, interruptible wait; non-positive values return immediately. Counts against wall-clock budget.
rs.log(...values) Stringifies arguments, joins with spaces and writes one line to stderr. Returns undefined.

HTTP

const response = rs.http.get('https://api.example.com/health', { timeoutMs: 2000 });
const posted = rs.http.request('https://api.example.com/query', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ query: 'status' }),
  timeoutMs: 2000,
  followRedirects: false
});

rs.http.get(url, options?) fixes the method to GET. rs.http.request(url, options?) uses the supplied method, defaulting to GET. Only HTTP/HTTPS URLs are supported. Both return a response object synchronously.

Option Type / default Meaning
method String, GET Request only; trimmed and uppercased. get ignores this option.
headers Object of strings, empty Explicit request headers. Use rs.secret for credential values.
body String, empty Request body, at most 1 MiB. Encode JSON explicitly and set Content-Type.
timeoutMs Positive number, 30,000 Per-call deadline, also bounded by the invocation. Omitted/non-positive uses the default.
followRedirects Boolean, true Set false to return the redirect response without following it.
Response field Type / meaning
status Numeric HTTP status. A 4xx/5xx response does not automatically throw.
statusText Status reason text.
headers Object of response header strings.
body Retained response body string, up to 4 MiB.
bytes Number of retained body bytes.
truncated True when the response exceeded the body cap. Check before parsing or asserting body content.
url Final request URL after any followed redirects.
proto HTTP protocol string.
durationMs Observed request/response duration in milliseconds.

Network, TLS, target-policy and deadline errors throw. HTTP status failures are values for your check to evaluate. Parse JSON with JSON.parse(response.body); there is no .json() method. Do not emit a fabricated response duration when no response was returned. The host uses certificate verification and TLS 1.2+ and does not honor environment proxies or expose an insecure-TLS switch.

DNS

rs.dns.resolve(host, options?) returns {addresses: string[], durationMs: number}. Options are family and timeoutMs:

  • family: 'any' or omitted: any IP family.
  • family: 'ipv4': IPv4; aliases 4 and inet are also accepted as strings.
  • family: 'ipv6': IPv6; aliases 6 and inet6 are also accepted as strings.
  • timeoutMs: the same positive per-call millisecond deadline convention as HTTP.

ip4 and ip6 are not accepted family option values. Empty results and errors must be handled explicitly. DNS uses the agent’s resolver; this is not a configurable DNS-server or arbitrary-record query API.

const answer = rs.dns.resolve('api.example.com', { family: 'ipv4', timeoutMs: 2000 });
rs.duration('dns_ms', answer.durationMs);
rs.gauge('address_count', answer.addresses.length, { unit: 'count' });

TCP

rs.net.connect(host, port, options?) opens a TCP connection, records its address and connect duration, then closes it. port must be 1–65535. options.timeoutMs follows the same deadline convention. It returns {address: string, durationMs: number} or throws on error. It does not return a socket, exchange application data or perform TLS negotiation.

const connection = rs.net.connect('db.example.com', 5432, { timeoutMs: 2000 });
rs.duration('tcp_connect_ms', connection.durationMs);

Host API limits

HTTP, DNS and TCP share a budget of 512 host calls per invocation. HTTP bodies are capped at 4 MiB retained, request bodies at 1 MiB, and redirect chains are bounded (the host stops when the chain reaches ten prior requests). Target allow/deny policy is applied by the host dialer, including redirect destinations. No script option bypasses that policy. Sleep and CPU work still consume the overall script deadline, which can interrupt an infinite loop.

See complete checks and troubleshooting. Source implementation: engine/internal/engine/module.go and host.go under agent/plugins/script/.

Screenshot