Skip to main content
NetScriptdocs Search docs ⌘K v0.0.9
Browse documentation
View as Markdown

Provision with a background job

In this chapter you move member provisioning off the request path. You add the workers plugin, write a defineJobHandler job that adds a member to the workspace database from chapter 3, and trigger it through the Workers API. The caller that starts provisioning gets an immediate answer while the membership write runs in the background.

  1. 1 · Scaffold
  2. 2 · Auth
  3. 3 · Workspace data
  4. 4 · Provision job
  5. 5 · Route authz
  6. 6 · Deploy

What you will build

A provision-member background job: a handler written with defineJobHandler that parses a payload, creates a Member in the workspace datasource, and returns a success result. At the end you trigger it through the Workers API and see its execution in the executions feed and its trace in the Aspire dashboard.

Before you begin

You need the workspace database from chapter 3 with aspire start running. The workers plugin ships an API service and a background processor that Aspire orchestrates, and the dashboard at the URL Aspire prints is where you read job traces. Keep Aspire running while you add the plugin and trigger the job. Check that the workspace datasource is ready:

Shell
# In my-workspace/, with `aspire start` up in another terminal
netscript db status --db workspace   # the workspace datasource from chapter 3

Step 1 — Add the workers plugin

Add the workers plugin with its sample jobs, so you have a working reference to read:

Shell
netscript plugin install worker --name workers --samples
netscript plugin list

The installer registers the plugin and its service and background resources. The project's worker configuration points job discovery at workers/jobs/; author jobs there. The installed plugin's implementation stays under plugins/workers/.

Step 2 — Read the job-authoring API

A job is a function wrapped by defineJobHandler, given a stable id, and exported as the module default. The handler receives a ctx, does the work, and returns a result built with createSuccessResult or createFailureResult. The sample workers/jobs/health-check.ts shows the shape and the createJobTools(ctx) helpers:

TypeScript
The job shapeTypeScript
import {
  createSuccessResult,
  createFailureResult,
  defineJobHandler,
} from '@netscript/plugin-workers-core';
import { createJobTools } from './job-tools.ts';

const handler = defineJobHandler(async (ctx) => {
  const { log } = createJobTools(ctx);
  log.info('doing work');

  // ...do the work, return a result...
  return createSuccessResult({ status: 'ok' });
});

export default Object.assign(handler, { id: 'my-job' as const });

The tool surfaceTypeScript
// createJobTools(ctx) returns three helpers:
//
//   log.info / log.warn / log.error  — console-backed logging
//   progress(percent, message)        — telemetry + runtime progress hook
//   trace.addEvent / trace.withChildSpan — active-span event + real child span
//
// `id` is attached to the handler with Object.assign so the runtime
// registry can address the job by a stable string.

Step 3 — Scaffold the provision-member job

Generate the job module with the workers CLI rather than writing it by hand. The CLI's add-job verb is written as add job on the command line.

Shell
ns-workers add job provision-member

The command writes workers/jobs/provision-member.ts with the stable export, the payload-schema block and the handler wrapper in place, then refreshes the worker registry. Edit the generated file:

  1. Extend the generated payload schema with workspaceId, subject and role.
  2. Import createFailureResult.
  3. Add the workspace Prisma import and client.
  4. Replace the starter handler body with this logic:
TypeScript
const handler = defineJobHandler(async (ctx) => {
  const parsed = PayloadSchema.safeParse(ctx.payload ?? {});
  if (!parsed.success) {
    return createFailureResult('invalid provision-member payload');
  }

  const { workspaceId, subject, role } = parsed.data;

  const member = await workspaceDb.member.create({
    data: { workspaceId, subject, role },
  });

  return createSuccessResult({ memberId: member.id, workspaceId, subject });
});

That is the whole job. The membership write happens off the request path, so the caller that triggered provisioning never waits for it.

Step 4 — Confirm the generated registry

The Workers API addresses jobs by id, and the scaffold command refreshed the generated registry before it returned. provision-member is already discoverable; don't run a second generation step.

If aspire start was already up when you generated the registry, restart it (or let it hot-reload) so the Workers API and its background processor pick up the new job.

Step 5 — Trigger the job

The installer picked the Workers API host port, so copy the workers-api endpoint from the dashboard resource list. Check the service is healthy and the job is registered, then trigger it by its id. You need a real workspaceId: create a Workspace row first, or use one your seed created, and pass its id:

Shell
# Health is still a plain liveness probe.
curl <workers-endpoint>/health

# Inspect metadata, then enqueue through the durable workers API.
ns-workers show-job provision-member --json
ns-workers trigger provision-member \
  --payload='{ "workspaceId": "ws-1", "subject": "user:alice", "role": "member" }'

Verify your progress

A trigger returns quickly because the work runs in the background. Read the executions feed to confirm it ran:

Shell
ns-workers executions --limit=10 --json

You see an execution record for provision-member with a succeeded status and a result payload carrying the new memberId. The same run appears in the Aspire Traces view at the dashboard at the URL Aspire prints, where the framework emits the dispatch and execution span.

Workers API (endpoints used here)
Name · TypeDescription
GET /healthHTTP Liveness check for the Workers API service.
ns-workers show-job {id} --jsonCLI Inspect local job metadata by id.
ns-workers trigger {id} --payload=…CLI Enqueue an execution through the durable workers API.
ns-workers executions --limit=10 --jsonCLI Recent executions and their result payloads.
  • [ ] netscript plugin list shows the workers plugin.
  • [ ] workers/jobs/provision-member.ts exists and exports an id.
  • [ ] ns-workers show-job provision-member --json shows its metadata.
  • [ ] ns-workers trigger returns quickly, and ns-workers executions shows it succeeded with a memberId.
  • [ ] The job-dispatch trace appears in the Aspire Traces view.

What you built

A provision-member background job that writes a workspace membership off the request path, triggered through the Workers API and visible in the Aspire dashboard. The workspace service itself still answers anyone who asks. Next, you make its routes fail closed.

Search all documentation

Type a term to search the documentation.