↑ ↓ to move · Enter to open · Esc to close

Services

Services (mesh)

Signed calls between servers, events, health checks and discovery.

White.js can connect servers into one system: a site and its API, several back-end services, or separate sites that share data. Turn it on with mesh in white.config.js. Without it nothing below is active and nothing in your app changes.

js
// web/white.config.js
export default {
  mesh: {
    name: 'web',                                   // this service
    peers: {
      billing: {
        url: process.env.BILLING_URL,              // 'http://billing:3000'
        secret: process.env.BILLING_SECRET,        // `white mesh keygen`
        required: true,                            // /ready fails while billing is down
      },
    },
  },
};
js
// billing/white.config.js: the same link seen from the other side, with the same secret
export default {
  mesh: {
    name: 'billing',
    peers: { web: { url: process.env.WEB_URL, secret: process.env.BILLING_SECRET } },
  },
};

The name a service gives itself must be the name its peers use for it. A mismatch shows up as a rejected signature in white mesh status.

#Calling another service

js
export default (router, ctx) => {
  router.get('/invoices', async (req, res) => {
    const billing = ctx.mesh.peer('billing');
    const invoices = await billing.json('GET', '/api/internal/invoices', { query: { page: 1 } });
    res.json(invoices);
  });
};
Call Result
peer.get/post/put/patch/delete/head(path, options) { status, ok, headers, text, json, attempts, ms } for any answer from the service
peer.json(method, path, options) the parsed JSON body, or an UpstreamError when the answer is not 2xx

Options: json, form, body, query, headers, timeout, retries, idempotent, retryStatus, signal.

  • Signed. Every request carries an HMAC-SHA256 signature over the method, path and query, body hash, time, a one-time nonce, the caller and the receiver. The secret is never sent. Changing anything, replaying a request, or sending it to another service fails.
  • Request id. The id of the request being handled goes along automatically, so one user action can be followed through the logs of every service.
  • Retries. GET, HEAD, PUT, DELETE and OPTIONS are retried (exponential backoff with jitter, Retry-After respected) on network errors and 408, 429, 502, 503, 504. Other methods are retried only with idempotent: true. Every attempt gets a new signature.
  • Timeouts and errors. The default timeout is 5 seconds. A service that cannot be reached, times out, or has an open circuit throws an UpstreamError (502, 503 or 504), which a route that does not catch it turns into that status.
  • Circuit breaker. After 5 failures in a row (network errors, timeouts, 5xx) calls to that peer fail at once for 30 seconds, then one probe is let through. Tune with breaker: { threshold, cooldown } or turn off with breaker: false.
  • Redirects are never followed, paths cannot leave the peer's address, and responses over 5 MB are refused (maxResponse).

Defaults for all peers go next to name (timeout, retries, retryDelay, breaker) and can be overridden per peer.

#Receiving calls

URLs under /internal and /api/internal (the protect list) accept only signed requests from known services. A file server/routes/api/internal/invoices.js is therefore reachable by your other services and by nobody else:

js
export default (router, ctx) => {
  router.get('/', (req, res) => {
    res.json(db.invoices({ for: req.service.name })); // req.service.name is the verified caller
  });

  // limit one route to some services
  router.delete('/:id', ctx.mesh.auth({ allow: ['admin'] }), handler);
};

Outside the protected prefixes, use ctx.mesh.auth() (or serviceAuth() from white-js) on any route. Unknown callers, bad signatures, old timestamps (skew, 60 seconds) and replayed requests all get the same 401; the real reason is in the log. Repeated failures from one address are answered with 429. Signed requests skip the normal rate limit, since they are authenticated instead.

Signed requests must have no body or a JSON or form body (the signature covers the exact bytes). A caller must be a peer or listed in accept.

Signatures prove who is calling and that nothing changed; they do not hide the content. Use https between servers that do not share a private network. Replay protection is kept in memory of each instance; with several instances of one service, pass nonces (an object with claim(key, ttlMs) -> boolean, for example on Redis SET NX PX).

#Events

js
// billing: react to events from other services
ctx.mesh.on('user.created', async (event) => {
  await createAccount(event.data.id);       // event: { id, type, data, from, at }
});
ctx.mesh.on('user.*', handler);              // prefix; '*' matches everything

// users: tell the others
const result = await ctx.mesh.emit('user.created', { id: 7 });
// { id, delivered: ['billing'], failed: [] }

emit goes to every peer (or { to: ['billing'] }; a peer with events: false is skipped) and is retried. A handler that throws makes the sender retry, and a delivered event id is remembered for an hour, so each handler runs once per event. { wait: false } returns immediately. There is no stored queue: an event is lost if the sender dies before delivery, so for data that must not be lost write it to your database first and send the event after.

#Health, discovery and status

  • ctx.mesh.status() pings every peer: [{ name, ok, ms, version, breaker, error }].
  • Peers with required: true are part of /ready, so an instance without a needed service leaves the load balancer. /health stays independent of peers.
  • Every service answers (to known services only) at /_white/ping and /_white/manifest, which lists its routes, event patterns, version and the meta you set.
  • ctx.mesh.addPeer(name, { url, secret }), removePeer(name) and setPeerUrl(name, url) change peers at runtime, for example from a service registry.
  • white mesh status does the ping from the command line and exits with 1 when a peer is down.

#Standalone client

Code that is not a route (a worker, a script) can use the same client:

js
import { createClient } from 'white-js';
const billing = createClient({ name: 'billing', from: 'worker', url: process.env.BILLING_URL, secret: process.env.BILLING_SECRET });