Runtime

Runtime

@axiljs/runtime turns @axiljs/decorator metadata into behaviour: per-request context, 26 interceptors for retries, audit, intent checks and resilience, shared stores and tRedact redaction.

5 min readUpdated DocumentationEdit this page
On this page6

@axiljs/decorator only records metadata: @tRetry({ attempts: 3 }) on a method does nothing by itself. @axiljs/runtime is the package that reads that metadata and makes it run.

It provides these pieces:

PieceWhat it doesMain exports
Request contextOne AsyncLocalStorage context per request (or job), so any code can read the request ID, user and tenant without passing req aroundrequestContext(), getContext(), runWithContext()
InterceptorsWraps decorated methods so tAudit, tRetry and tTimeout actually audit, retry and time outwire(), wireAll(), registerInterceptor(), TimeoutError
Intent verificationChecks the promises decorators declare (tReadOnly, tPure, tTenantIsolated, tIdempotent, tSlo, …) while the code runsconfigureIntent(), reportSideEffect(), getIntentViolations(), runtimeReport()
ResilienceCircuit breakers, fallbacks, bulkheads, concurrency limits, locks, caching and rate limitsenforcedDecorators(), getCircuitStates(), CircuitOpenError, RateLimitExceededError
Shared storesKeeps idempotency results, cache entries, locks and rate-limit counters correct across several instancesuseStores()
RedactionRemoves, masks or hashes tRedact / tSensitive fields in responses, logs and audit eventsredact(), redactResponses(), redactingTransport()

You can use any one of them without the others. Intent verification and resilience are both interceptors, so they need the same wire() call as tRetry and tTimeout.

Note

New in 0.3.4: intent verification and the resilience interceptors; the runtime enforces 26 decorators, up from 3. New in 0.3.5: AXIL_INTENT_MODE, runtimeReport() and setRateLimitStore(). New in 0.3.6: useStores().

Installation

❯npm install @axiljs/runtime @axiljs/decorator
❯pnpm add @axiljs/runtime @axiljs/decorator
❯yarn add @axiljs/runtime @axiljs/decorator
❯bun add @axiljs/runtime @axiljs/decorator

@axiljs/runtime depends on @axiljs/common, @axiljs/decorator, @axiljs/circuit (for retry()) and @axiljs/events (audit and retry events go to the global event bus).

Warning

Decorators are TypeScript legacy decorators. Your tsconfig.json must set "experimentalDecorators": true, otherwise the compiler emits TC39 decorators and no metadata is recorded.

60-second example

TypeScript
TS
1import { Application } from '@axiljs/core'
2import { tAudit, tRedact, tRetry, tSensitive, tTimeout } from '@axiljs/decorator'
3import { getContext, redactResponses, requestContext, wire } from '@axiljs/runtime'
4
5// 1. An entity whose fields carry redaction metadata
6class Customer {
7  id = 'c_1'
8  @tSensitive('PII') email = 'ann@example.com'                       // kept in responses, masked in logs/audit
9  @tRedact({ strategy: 'mask', visibleChars: 4 }) card = '4242424242424242'
10  @tRedact({ strategy: 'remove' }) passwordHash = 'scrypt$...'      // never leaves the API
11}
12
13// 2. A service whose methods carry reliability and audit metadata
14class CustomerService {
15  @tAudit({ action: 'customer.read', includeRequest: true })
16  @tRetry({ attempts: 3, backoff: 'exponential', retryOn: ['ECONNRESET'] })
17  @tTimeout(500)
18  async find(id: string) {
19    return { customer: new Customer(), requestId: getContext()?.requestId }
20  }
21}
22
23// 3. Turn the metadata into behaviour
24wire(CustomerService)
25
26const customers = new CustomerService()
27const app = new Application()
28
29app.use(requestContext())     // request ID, user and tenant for everything downstream
30app.use(redactResponses())    // tRedact fields stripped from every JSON body
31
32app.get('/customers/:id', async (req, res) => {
33  res.success(await customers.find(req.params.id))
34})
35
36await app.listen(3000)

A request to /customers/c_1 returns:

JSON
JSON
1{
2  "status": 200,
3  "code": "HTTP_200_OK",
4  "message": "Request successful",
5  "data": {
6    "customer": { "id": "c_1", "email": "ann@example.com", "card": "************4242" },
7    "requestId": "8f9b6c1e-4c1d-4c8e-9a51-2a7d3f0b6e11"
8  }
9}

The response also carries an x-request-id header, find() is retried on ECONNRESET, each attempt is cut off after 500 ms, and one audit.log event is emitted on the global event bus after the call finishes.

How the pieces fit

HTTP request
requestContext()
Auth / tenancy middleware
Route handler
Wired service method
tAudit (order 100)
tRetry (order 200)
tTimeout (order 300)
Original method
res.success() / res.json()
redactResponses()
  • requestContext() opens an AsyncLocalStorage context holding requestId, req and a bag. user and tenantId are read lazily from req.locals.

  • Auth / tenancy middleware sets req.locals.user and req.locals.tenant.

  • The route handler calls a wired service method, which runs through the interceptors, outermost first:

    • tAudit (order 100) reads actor, tenant, requestId and ip from getContext().
    • tRetry (order 200) uses @axiljs/circuit retry().
    • tTimeout (order 300) applies a per-attempt deadline.
    • Then the original method runs.
  • redactResponses() applies tRedact (and optionally tSensitive) to the body sent by res.success(...) / res.json(...).

  • The interceptors read the request context, so audit events know who did what and under which request ID.

  • tAudit passes args and result through redaction before emitting, so tRedact and tSensitive fields never reach the audit trail.

  • Context, retries, timeouts and redaction are all per request or per call. They need no shared state, so they work unchanged when you run many workers with @axiljs/scale.

  • Idempotency results, cache entries, locks and rate-limit counters are kept in memory by default. With several workers or instances, install shared stores.

Importing registers the built-ins

Importing @axiljs/runtime registers all 26 built-in interceptors as a side effect: tAudit, tRetry and tTimeout, the intent interceptors and the resilience interceptors. There is nothing else to configure before calling wire(). enforcedDecorators() lists them in order, and axil verify uses that list to show which decorators in your project are enforced.

Complete example project

The high-scale-api template combines this package with @axiljs/scale: request context, tAudit / tRetry / tTimeout on a service, tRedact / tSensitive on an entity, an error handler that maps TimeoutError to 504, and tests that drive the app in one process.

Terminal
❯axil create my-api --template high-scale-api

Next steps

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY