Processes: long-running work on the worker
A trusted module can keep work running: a connection it holds open (a chat bot's presence, a device, a stream from a provider), a loop that watches something. That is a process. SHADE runs each one on the worker container role only, in a worker thread of its own with a heap limit, restarts it when it crashes and shows its state on the Modules page. Untrusted modules have no processes: long-running code needs the trust of the process.
What a module writes
Two parts of the manifest: the process itself in processes, and its parameters under the same name in the process
capability (see Capabilities).
import { defineModule, getModuleSettings, moduleKv } from '@shadestack/module-sdk/server'
export default defineModule({
name: 'readme-cards',
version: '1.0.0',
description: 'Cards for a README, with a Discord presence.',
capabilities: {
http: {},
kv: { data: { purpose: 'readmeCards.keeps', personal: 'none' } },
process: {
need: 'optional', // works without; an admin switches it on
processes: {
presence: { mode: 'singleton', memoryMb: 64, stopTimeoutMs: 10_000, maxRestarts: 10 }
}
}
},
processes: [
{
name: 'presence',
run: async (ctx, signal) => {
const { discordToken } = await getModuleSettings(ctx, 'readme-cards')
const socket = await connectToDiscord(discordToken, { signal })
socket.on('presence', status => void moduleKv(ctx).set('presence', status))
// Run until SHADE stops it, then let go of what it holds.
await new Promise<void>(resolve => signal.addEventListener('abort', () => resolve(), { once: true }))
await socket.close()
}
}
]
})
run(ctx, signal)runs untilsignalaborts, then returns within its stop timeout. Returning or throwing before that is a crash: SHADE starts it again with backoff.ctxis the module's own actor, as in a schedule: it may do what the manifest'suseslists and nothing more, and read its own settings and kv. A singleton's context also hasctx.leaseToken, which grows with every new holder, also across a Redis restart: store it beside writes that must not race a takeover (as abigint: it has about 16 digits), and refuse a lower one.- The parameters (
ProcessParams):Parameter Values Default What it does modesingleton,per-instance(required) singleton: one copy per instance, on whichever worker holds its lease.per-instance: one on every worker.memoryMb64–256 64 The thread's V8 heap ( resourceLimits.maxOldGenerationSizeMb). Less than 64 is refused (see Memory).stopTimeoutMs1000–30000 10000 How long a stop waits for runto return before the thread is terminated.maxRestarts1–50 10 Crashes in a row before the process is marked failed. - Checked when the module loads. Each process is
{ name, run }with a short name, once, and has its parameters incapabilities.process.processes, which names no process the manifest doesn't have.shade-module buildrefuses a manifest whose processes the declaration doesn't name, and writes the declaration into the package; the worker runs each process with the parameters of that signed declaration. The consent shows each process with its mode, memory and restarts; an update that adds a process, raises its memory or restarts, or turns a singleton into a process on every worker asks again. - Untrusted modules: a sandbox package that requires
processis refused at install ("readme-cards requires the process capability, which needs a trusted module"); an optional one is skipped, and its routes still work. An untrusted module can't haveprocessesat all.
Memory
A process's thread loads SHADE's server code before the module's own: about 30 MB of its heap. So
memoryMb is at least 64, and 64 when the declaration gives none: a declaration
below it is refused when the module loads and at build ("memoryMb must be at least 64 MB: a process's thread needs
about 30 MB for SHADE's own code before the module's"). A process that still runs out of its heap stops with "The
process ran out of memory (its limit is 64 MB)" and is restarted like any crash. memoryMb caps
the V8 heap only, not ArrayBuffers or native memory. The worker's budget, SHADE_PROCESSES_MEMORY_MB (192 by default),
is the sum of the memoryMb of the processes it runs at once.
Testing a process
The testing entry runs one process once, as the worker would: as the module's own actor, with a signal that aborts after
forMs, then its stop timeout.
import { runProcessOnce } from '@shadestack/module-sdk/testing'
const result = await runProcessOnce(ctx, plugin, 'presence', { forMs: 1_000 })
expect(result).toEqual({ ended: 'stopped' }) // or 'ended', 'threw' (with error), 'timeout'
Long-lived connections
A process can hold a connection open: a broker or device feed over WebSocket, an exchange's price stream, a chat
service, an event stream (text/event-stream) that runs for hours. They don't fit moduleFetch, which answers in 10
seconds with at most 5 MB. A trusted module opens them through ctx.connections, under the streams of its network
capability (Capabilities), with the address rules of Network: a stream does not pass by the
gate that every other call out of SHADE passes. Only a process's ctx has connections; routes, schedules, thread
tasks and the sandbox don't, and an untrusted module keeps request-and-answer calls only.
export default defineModule({
name: 'prices',
// …
capabilities: {
process: { processes: { feed: { mode: 'singleton' } } },
network: { streams: ['wss://stream.exchange.example', 'https://events.exchange.example'] }
},
processes: [
{
name: 'feed',
run: async (ctx, signal) => {
const feed = await ctx.connections!.open('wss://stream.exchange.example/v1', {
headers: { authorization: `Bearer ${await apiKey(ctx)}` },
open: () => void feed.send(JSON.stringify({ subscribe: 'eur-usd' })),
message: async message => void await moduleKv(ctx).set('eur-usd', JSON.parse(String(message))),
closed: ({ reason, willReconnect }) => ctx.log.info('the feed closed', { reason, willReconnect }),
failed: ({ error }) => ctx.log.warn('the feed could not connect', { error })
})
await new Promise<void>(resolve => signal.addEventListener('abort', () => resolve(), { once: true }))
await feed.close()
}
}
]
})
- Declared streams.
network.streamslists each host with its protocol:wss://hostfor a WebSocket,https://hostfor a stream (a long response read as it comes).*.example.comcovers the names under it. Only the default port, and no IP addresses or local names. Each is astream …line on the consent screen and the Modules page, and a new one asks again.ws://andhttp://do not exist here. open(url, options)resolves as the first attempt starts, and refuses at once (FORBIDDEN, counted for the module) an address the capability does not name, an address that points into the server's own network, a name with a user name or password, and a ninth connection. It never follows a redirect: a WebSocket upgrade or a stream answered with one is refused, so theheadersyou give (an authorization header) only ever reach the origin they were given for.- The handlers.
open(the first time and after each reconnect),message(a WebSocket's text as a string and its binary as bytes; a stream's chunk as bytes),closed(reason:server,closed,idle,too-large,too-sloworprotocol,code,willReconnect) andfailed(error,willReconnect).messagegets one message at a time, in order: the next waits until it returns. A handler that throws is logged under the module and the connection goes on.connection.send(data)(WebSocket only) returns false when the connection is not open. - Limits, set by SHADE: a message or chunk of at most 1 MB; a process that falls a megabyte behind for 10 seconds
has the connection closed (
too-slow); 2 minutes without data close it (idle; SHADE pings a WebSocket every 30 seconds, so a quiet but healthy one stays open); at most 8 open per module on a worker. - Reconnecting is SHADE's. A dropped connection is opened again with the backoff of a crashed process (1 second
doubling to 5 minutes, plus jitter), the capability and the address checked again at each attempt; one that held for a
minute starts from the beginning. If the rules no longer allow it (the capability or the host was withdrawn) it stops,
and
failedsayswillReconnect: false. Each connection's state (connecting, open, reconnecting, closed, refused) shows on the Modules page under its process, with the scheme and host only: the path and query can hold a token. - Stopping. When the process's
signalaborts, SHADE closes every connection (a close frame, then the socket) and refuses new ones, so the process has its whole stop timeout to end. - Not covered. Raw TCP, SMTP, FTP and database protocols stay out. A client program on shade-programs can hold a
long-lived connection over port 443 in a language of its own, and a trusted module reaches it with
callProgram.
In tests, runProcessOnce gives the process the same ctx.connections (streams only: the WebSocket client is the API's), and stubModuleNetwork({ resolve, dial, ca })
(the testing entry) puts a local server in place of the internet.
A standard socket
Libraries that speak a protocol over WebSocket (a gateway client, a message broker's) expect the standard WebSocket, not
ctx.connections. moduleSocket(ctx, url, options) gives them one. It is the same connection, with the same
declaration, address checks and limits, in the shape of the standard: readyState, send, close(code), binaryType,
onopen, onmessage, onerror, onclose and addEventListener.
import { moduleSocket } from '@shadestack/module-sdk/server'
run: async (ctx, signal) => {
const socket = await moduleSocket(ctx, 'wss://gateway.example.com/?v=10')
socket.binaryType = 'arraybuffer'
socket.onmessage = event => handle(event.data)
socket.onclose = event => ctx.log.info('closed', { code: event.code })
signal.addEventListener('abort', () => socket.close(), { once: true })
}
- It does not reconnect. A dropped socket ends with a close event, and the code that wants another calls
moduleSocketagain, which checks the rules again. A failed attempt is anerrorevent and a close event with code 1006, as in a browser. - Refusals throw before a socket exists: a host the
streamsdo not name,ws://, another port, an address inside the network (FORBIDDEN, counted for the module), a module that already holds as many connections as it may, and a module over its limit for the host (OutboundFailurewith reasonthrottled). - Every attempt counts against the module's 120 calls a minute to the host, the first and each reconnect, so a loop that keeps reconnecting is refused at once and nothing is sent.
- The close code is yours: 1000, or 3000 to 4999. Some services keep a session open for resuming after any other code than 1000.
Experimental until a second module uses sockets.
How SHADE runs them
The kernel's ProcessSupervisor (shade/kernel/processes/supervisor.ts) runs the processes of one worker. Per module,
process and worker:
stateDiagram-v2
accTitle: The states of a process
accDescr: A process starts stopped. Once wanted it is starting, and on 'ready' or a heartbeat it is running. On an exit, a throw, a return or no heartbeat for 15 seconds, a starting or running process goes to backoff and its restarts go up by one. When the wait is over, backoff goes to starting; when restarts exceed maxRestarts it goes to failed, until an admin's Restart, a switch on, or an update. After 10 minutes running, its restarts go back to 0. From any state, when it is no longer wanted or the lease is lost, it goes to stopping and then stopped. A singleton whose lease another worker holds stays stopped, shown as standby on that worker, and tries again every 10 seconds.
[*] --> stopped
stopped --> starting: wanted
starting --> running: 'ready' or a heartbeat
starting --> backoff: exit, throw, return, no heartbeat for 15 s (restarts + 1)
running --> backoff: exit, throw, return, no heartbeat for 15 s (restarts + 1)
backoff --> starting: the wait is over
backoff --> failed: restarts #gt; maxRestarts
running --> running: 10 minutes (restarts back to 0)
any --> stopping: no longer wanted, or the lease lost
stopping --> stopped
state "any state" as any
note right of failed: until an admin's Restart, a switch on, or an update
note left of stopped: singleton, lease held by another worker - stopped, "standby on #lt;worker#gt;", tries again every 10 s
| What | Number |
|---|---|
| Backoff before restart n | min(1 s × 2^(n−1), 5 min) plus 0–20 % jitter: 1, 2, 4, 8, 16, 32, 64, 128, 256, then 300 s (backoffDelay, shade/kernel/backoff.ts) |
Restarts before failed | maxRestarts, default 10 |
| Stable | after 10 minutes of running, its restarts go back to 0 |
| Heartbeat | every 5 s from the thread; none for 15 s (three missed) and the thread is terminated, a crash ("The process stopped answering") |
| Stop | posts stop (the thread aborts signal), waits stopTimeoutMs, then terminate(); the template's stop_grace_period is 40 s, above the longest stop timeout |
| Memory | a process whose memoryMb exceeds what is left of SHADE_PROCESSES_MEMORY_MB is not started: failed, "No memory left on this worker: needs 64 MB, 32 MB free" |
| Singleton lease | process:<plugin>:<process>, 30 s, renewed every 10 s; a lost renewal stops the process at once (at most one TTL of overlap); held through backoff, given up when it fails, stops or the worker stops |
- What should run (
wantedProcesses,apps/api/src/bootstrap/processes.ts): the processes of the trusted modules the worker loaded at start that are switched on, whoseprocesscapability is active, with the parameters of their signed (or loaded, for a development folder) declaration. - Following changes. The worker follows the
pluginschannel (Messages replacing polling): a module switched on starts its processes, one switched off, or whose optionalprocesscapability is switched off, stops them. The 60-second safety re-read catches a lost message. An update takes effect after the restart it needs: the worker stops every process gracefully and exits, and its host starts it again. - Blue-green. While an old and a new worker both run, the new one waits in standby until the old one gives the lease up on its graceful stop, or until the lease lapses when the old one died.
- Never outside the worker. Only the worker container role (and
all: development and the small profile) starts the supervisor.
The worker thread
apps/api/src/threads/process-thread.ts, built as dist/process-thread.mjs beside the server, is each process's thread.
nodeThreadFactory (apps/api/src/threads/thread-factory.ts) starts it with new Worker(entry, { workerData, resourceLimits, env: {} }): the heap is the process's memoryMb, the young generation at most 16 MB, the stack 4 MB, and the thread
gets no environment. config.ts stays the only reader of the environment; the thread gets the worker's config values
in workerData, with a database pool of its own of 2 connections.
The thread registers the module module hooks (so a package's imports get the API's own SDK, zod and drizzle), imports
the process's module and the modules it requires from those the worker loaded, loads them as the worker did (actions,
the module actor's uses, collections; no migrations), finds the process and runs it with a context made for
the module (asModule). It posts ready, then a heartbeat every 5 seconds. A process that throws or returns on
its own ends the thread with code 1 and its error; one that returns after the stop, with code 0. The events what a
process does writes are delivered from the outbox like any other (decision 0014), to every module that hears them.
Status
Each change is written to module_process_status (one row per module, process and worker: mode, status, restarts,
last error scrubbed and cut to 500 characters, its time, when it started, a note such as "standby on processes.purge-status deletes rows of workers not seen for a day. Each crash is also in the error log, as the
module's (package:<name>), with the process as its scope (process:<process>).
| Route | Who | What |
|---|---|---|
GET /api/packages/processes (?plugin=) | packages.read | Every process on every worker (listProcessStatus), with seen |
POST /api/packages/processes/:name/:process/restart | packages.manage | An admin's Restart (requestProcessRestart): asked for in Postgres (restart_requested_at), audited packages.process-restart, announced on plugins; every worker that has the process restarts it, a failed one with its restarts at 0. 404 when no worker has it |
processes is a reserved module name, so these never meet a module's own routes. A module's measured health
(see shade/features/packages/README.md in the shade repository) takes its processes from processHealthOf: a
process in failed or backoff on a current worker counts as unhealthy.
Where it is
| Part | What |
|---|---|
shade/kernel/modules/define.ts | ShadeModule.processes (a core part), ModuleProcess from the supervisor |
shade/kernel/modules/loader.ts | processProblems: trusted modules only, { name, run }, parameters in the declaration |
shade/features/packages/server/capability-definitions.ts | The process capability: trusted, its lines, its words, what asks again |
shade/kernel/processes/supervisor.ts, backoff.ts | ProcessSupervisor (sync, restart, stopAll, summary), the numbers, backoffDelay |
shade/features/packages/server/process-status.ts, process-status.sql.ts, shared/processes.ts | The status table and its services (with the connections' states), the view the admin reads |
shade/kernel/connections.ts, shade/features/packages/server/connections.ts, apps/api/src/threads/websocket-client.ts | Long-lived connections: the transports, limits and reconnecting, ctx.connections with the declared hosts, and the WebSocket client (ws, imported only there) |
apps/api/src/bootstrap/processes.ts | startProcesses (on the worker's startBackground), wantedProcesses |
apps/api/src/threads/thread-factory.ts, apps/api/src/threads/process-thread.ts | The thread factory and the thread entry |
apps/api/src/http/controllers/module-processes.ts | The routes above |
shade/features/packages/admin/components/ModuleProcessesTable.vue | The Modules page's table, on each module's card |
Tests
shade/test/kernel/processes/supervisor.test.ts(fake threads, test clock): "starts a process and records starting, then running at its first heartbeat", "restarts a crashed process with exponential backoff and records backoff between starts", "resets the restart count after ten minutes of running", "marks a process failed after its maximum restarts and starts it no more until an admin restarts it", "stops gracefully: aborts the signal, waits the stop timeout, then terminates", "terminates a process whose heartbeat stops for 15 seconds, and counts it as a crash", "refuses to start a process beyond the worker's memory budget, with the reason as its status", "starts processes when their module is switched on and stops them when it is switched off or its capability is skipped", "records each status change in order"; singletons on leases: "runs a singleton process on one worker only", "starts it on another worker once the first one's lease expires", "lets a new worker wait while the old one still holds the lease (blue-green), and take over when it releases", "stops a singleton at once when its lease is lost".shade/test/kernel/connections.test.ts(a local https server): refusals and the stream, no redirects;apps/api/test/threads/websocket-client.test.ts: the WebSocket, limits, reconnecting with the rules asked again, shutdown;shade/test/features/packages/server/connections.test.ts(Postgres): the declared hosts, refusals counted, only a process's context.shade/test/kernel/backoff.test.ts: "waits 1, 2, 4 … seconds, capped at five minutes, with at most 20 % jitter".shade/test/kernel/modules/loader.test.ts: "loads a trusted module's processes with their parameters, and refuses a process without them", "refuses a process with less than 64 MB, and gives one without memoryMb 64", "refuses processes in an untrusted module, as a part and as a capability";capabilities.test.ts: theprocesscapability offered to trusted modules.shade/test/features/packages/server/process-status.test.ts(Postgres): each worker's status with its error scrubbed, the list forpackages.readand the Restart forpackages.managethrough thepluginsmessage, the purge.apps/api/test/threads/thread-factory.test.ts: the heap limit, no environment, heartbeats, the graceful stop, terminate, and a thread that runs out of memory.apps/api/test/threads/process-thread.test.ts(Postgres): "runs a trusted module's process as the module's own actor until it is stopped, then ends with code 0", and the error when it throws or the module has no such process.apps/api/test/bootstrap/processes.test.ts(Postgres): the switch, the optional capability and an admin's Restart on every worker through thepluginsmessage, a crash in the error log, and "never runs a process on the admin or public container role".shade/module-sdk/test/testing.processes.test.ts:runProcessOnce.- e2e
plugins-processes.spec.ts, with core'sprocess-probefixture (a server package, installed switched off): an admin sees a running process and a failed one with its last error, restarts the failed one, and switching the module off stops them; the processes run in worker threads of the built API. pnpm deploy:smoke: the worker starts its supervisor, and the thread entry loads in a thread within 64 MB with the template's settings.