@funcd-dev/shim 0.34.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/addon.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // worker-node local API, which checks the binding and the path before it forwards the request.
3
3
  import http from 'node:http';
4
4
  import { MEMBER_HEADER } from "./invoke.js";
5
+ import { localApi } from "./localapi.js";
5
6
  import { startClientSpan } from "./tracespan.js";
6
7
  /** The local API header that marks an answer as the engine's; a call that funcd refused carries none. */
7
8
  export const ADDON_REPLY_HEADER = 'x-funcd-addon-reply';
@@ -33,8 +34,8 @@ export function makeAddon(opts = {}) {
33
34
  span?.end('ERROR', err.message, httpStatus);
34
35
  throw err;
35
36
  };
36
- const socketPath = process.env.FUNCD_INVOKE_SOCKET;
37
- if (!socketPath) {
37
+ const api = localApi();
38
+ if (!api) {
38
39
  return fail(new Error('context.addon: worker-node local API socket unavailable (FUNCD_INVOKE_SOCKET unset)'));
39
40
  }
40
41
  if (!path.startsWith('/')) {
@@ -48,6 +49,7 @@ export function makeAddon(opts = {}) {
48
49
  });
49
50
  if (body)
50
51
  headers['content-length'] = String(body.length);
52
+ Object.assign(headers, api.headers);
51
53
  if (opts.member)
52
54
  headers[MEMBER_HEADER] = opts.member;
53
55
  if (span)
@@ -55,7 +57,7 @@ export function makeAddon(opts = {}) {
55
57
  const target = new URL(request.url);
56
58
  const reply = await new Promise((resolve, reject) => {
57
59
  const req = http.request({
58
- socketPath,
60
+ ...api.options,
59
61
  path: `/addon/${encodeURIComponent(alias)}${target.pathname}${target.search}`,
60
62
  method: request.method,
61
63
  headers,
package/dist/funclog.js CHANGED
@@ -5,14 +5,17 @@
5
5
  // (Node + Python) emit the SAME wire, so the reader is language-agnostic.
6
6
  //
7
7
  // Channel selection at startup (env, in order):
8
- // FUNCD_LOG_FD = a numeric fd (e.g. "3") → fs.writeSync(fd, line) [SYNCHRONOUS — minimal crash-tail loss]
9
- // FUNCD_LOG_SOCK = a unix socket path → net.connect(path), write lines to it
10
- // neither set → no capture; console stays as-is (Path A / stdout)
8
+ // FUNCD_LOG_FD = a numeric fd (e.g. "3") → fs.writeSync(fd, line) [SYNCHRONOUS — minimal crash-tail loss]
9
+ // FUNCD_LOG_SOCK = a unix socket path → net.connect(path), write lines to it
10
+ // FUNCD_LOG_STDOUT = set, with neither above → every console call prints its line to stdout (funcd ADR-0346
11
+ // Decision 4: a worker in a container has no channel, and funcd
12
+ // keeps its stdout as lines, without the records' fields)
13
+ // none set → no capture; console stays as-is (Path A / stdout)
11
14
  //
12
15
  // Pure Node, built-ins only (node:fs, node:net, node:worker_threads) — no npm deps, so it bundles into shim.mjs/pool.mjs.
13
16
  import { writeSync } from 'node:fs';
14
17
  import { connect } from 'node:net';
15
- import { inspect } from 'node:util';
18
+ import { format, inspect } from 'node:util';
16
19
  import { threadId } from 'node:worker_threads';
17
20
  import { currentInv } from "./invcontext.js";
18
21
  const SEVERITY = {
@@ -404,8 +407,12 @@ export function openChannel(env, lock) {
404
407
  * already opened (ADR-0101: log + trace capture share ONE channel), else it opens from env. A pool
405
408
  * worker passes its `member` name, stamped on every record as `funcd.member`. */
406
409
  export function installConsoleCapture(env = process.env, sink = openChannel(env), member) {
407
- if (!sink)
408
- return false;
410
+ if (!sink) {
411
+ if (!env.FUNCD_LOG_STDOUT)
412
+ return false;
413
+ printToStdout();
414
+ return true;
415
+ }
409
416
  const bound = recordBound(env);
410
417
  const methods = ['debug', 'log', 'info', 'warn', 'error'];
411
418
  for (const method of methods) {
@@ -420,3 +427,18 @@ export function installConsoleCapture(env = process.env, sink = openChannel(env)
420
427
  }
421
428
  return true;
422
429
  }
430
+ /** printToStdout makes every console call print its formatted line to stdout, synchronously: the record funcd keeps
431
+ * as a line when FUNCD_LOG_STDOUT is set and no channel is (funcd ADR-0346 Decision 4). */
432
+ function printToStdout() {
433
+ const methods = ['debug', 'log', 'info', 'warn', 'error'];
434
+ for (const method of methods) {
435
+ console[method] = (...args) => {
436
+ try {
437
+ writeSync(1, `${format(...args)}\n`);
438
+ }
439
+ catch {
440
+ // a closed stdout must never crash the function — drop the line.
441
+ }
442
+ };
443
+ }
444
+ }
package/dist/invoke.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // platform bind-mounts the per-sandbox socket and provides its path via FUNCD_INVOKE_SOCKET; the
3
3
  // handler calls context.invoke(alias, input) and the platform brokers the call to the linked target.
4
4
  import http from 'node:http';
5
+ import { localApi } from "./localapi.js";
5
6
  import { startClientSpan } from "./tracespan.js";
6
7
  /** Build the context.invoke implementation. The returned function POSTs `input` to
7
8
  * /invoke/<alias> over the worker-node UDS and resolves the target's JSON output, or rejects on a
@@ -18,13 +19,14 @@ export function makeInvoke(opts = {}) {
18
19
  span?.end('ERROR', err.message, httpStatus);
19
20
  reject(err);
20
21
  };
21
- const socketPath = process.env.FUNCD_INVOKE_SOCKET;
22
- if (!socketPath) {
22
+ const api = localApi();
23
+ if (!api) {
23
24
  fail(new Error('context.invoke: worker-node local API socket unavailable (FUNCD_INVOKE_SOCKET unset)'));
24
25
  return;
25
26
  }
26
27
  const body = JSON.stringify(input ?? null);
27
28
  const headers = {
29
+ ...api.headers,
28
30
  'content-type': 'application/json',
29
31
  'content-length': Buffer.byteLength(body),
30
32
  };
@@ -33,7 +35,7 @@ export function makeInvoke(opts = {}) {
33
35
  if (span)
34
36
  headers.traceparent = span.traceparent;
35
37
  const req = http.request({
36
- socketPath,
38
+ ...api.options,
37
39
  path: `/invoke/${encodeURIComponent(alias)}`,
38
40
  method: 'POST',
39
41
  headers,
@@ -84,8 +86,8 @@ export function makeFetch(opts = {}) {
84
86
  span?.end('ERROR', err.message, httpStatus);
85
87
  throw err;
86
88
  };
87
- const socketPath = process.env.FUNCD_INVOKE_SOCKET;
88
- if (!socketPath) {
89
+ const api = localApi();
90
+ if (!api) {
89
91
  return fail(new Error('context.fetch: worker-node local API socket unavailable (FUNCD_INVOKE_SOCKET unset)'));
90
92
  }
91
93
  if (!path.startsWith('/')) {
@@ -99,6 +101,7 @@ export function makeFetch(opts = {}) {
99
101
  });
100
102
  if (body)
101
103
  headers['content-length'] = String(body.length);
104
+ Object.assign(headers, api.headers);
102
105
  if (opts.member)
103
106
  headers[MEMBER_HEADER] = opts.member;
104
107
  if (span)
@@ -106,7 +109,7 @@ export function makeFetch(opts = {}) {
106
109
  const target = new URL(request.url);
107
110
  const reply = await new Promise((resolve, reject) => {
108
111
  const req = http.request({
109
- socketPath,
112
+ ...api.options,
110
113
  path: `/fetch/${encodeURIComponent(alias)}${target.pathname}${target.search}`,
111
114
  method: request.method,
112
115
  headers,
package/dist/job.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ import type { Json } from './types.ts';
2
+ /** funcd's problem, the body of a refusal (RFC 9457). */
3
+ export interface JobProblem {
4
+ type: string;
5
+ title: string;
6
+ status: number;
7
+ detail: string;
8
+ }
9
+ /** A start or a read of a run that funcd refused. */
10
+ export declare class JobError extends Error {
11
+ /** The HTTP status of the refusal. */
12
+ readonly status: number;
13
+ /** funcd's problem. */
14
+ readonly problem: JobProblem;
15
+ constructor(call: string, problem: JobProblem);
16
+ }
17
+ /** A run of a Job, as context.job.get reads it. */
18
+ export interface JobRunState {
19
+ /** The run's name. */
20
+ name: string;
21
+ /** Pending, Previewing, AwaitingApproval, Running, Succeeded, Failed, Cancelled or Rejected. */
22
+ phase: string;
23
+ /** Why the run is in its phase, empty while it runs. */
24
+ reason: string;
25
+ /** When the run started running, an RFC 3339 time; null before. */
26
+ startedAt: string | null;
27
+ /** When the run ended, an RFC 3339 time; null before. */
28
+ endedAt: string | null;
29
+ /** The handler's answer once the run Succeeded; null before. */
30
+ result: Json;
31
+ }
32
+ export interface JobClient {
33
+ /** Starts a run of the Job that the function binds under alias, with input as the run's input, and returns the
34
+ * run's name at once, without waiting for the run. Without name, funcd names the run <job>-<id>, and a start sent
35
+ * again starts a second run; with name, a start sent again with the same input returns that run, so a function
36
+ * called more than once for one event, as at-least-once delivery does, names the run from the event's id. A run of
37
+ * a Job without approval.bypass waits for a person's approval. Rejects with a JobError: 403 when the function binds
38
+ * no Job under alias or a Policy forbids it, 404 when the Job does not exist, 409 when another run holds the name,
39
+ * 413 when the input passes job.payloadLimit, and 422 when it does not match the Job's input schema. */
40
+ start(alias: string, input?: unknown, name?: string): Promise<string>;
41
+ /** Reads run, a run of the Job that the function binds under alias: its phase, its reason, its times and, once it
42
+ * Succeeded, its result. Rejects with a JobError: 403 when the function binds no Job under alias or a Policy
43
+ * forbids it, and 404 when the run is not one of that Job's, or funcd removed it after job.retention. */
44
+ get(alias: string, run: string): Promise<JobRunState>;
45
+ }
46
+ /** An approval of a run's preview (funcd ADR-0348): who approved it, the digest the approval names, and the document
47
+ * of that preview. */
48
+ export interface Approval {
49
+ approvedBy: string;
50
+ digest: string;
51
+ preview: Json;
52
+ }
53
+ /** Build context.job. In a pool, `member` names the calling function on every request; the solo shim passes none. */
54
+ export declare function makeJob(member?: string): JobClient;
55
+ /** readApproval reads the approval of the caller's own run from funcd (funcd ADR-0348): null for a run with none, as a
56
+ * run of a Job with approval.bypass. It fails when funcd does not answer the run, so a handler never runs with an
57
+ * approval it could not read. */
58
+ export declare function readApproval(): Promise<Approval | null>;
package/dist/job.js ADDED
@@ -0,0 +1,75 @@
1
+ // context.job (funcd ADR-0349): a Function starts a run of a Job that it binds, and reads it back, through funcd's
2
+ // worker-node local API, which checks the binding and Policies and admits the run as a person's. A Job's worker also
3
+ // reads its own run there, with the approval its handler's context carries (funcd ADR-0348).
4
+ import { send } from "./socket.js";
5
+ /** A start or a read of a run that funcd refused. */
6
+ export class JobError extends Error {
7
+ /** The HTTP status of the refusal. */
8
+ status;
9
+ /** funcd's problem. */
10
+ problem;
11
+ constructor(call, problem) {
12
+ super(`${call} failed: ${problem.status} ${problem.detail}`);
13
+ this.name = 'JobError';
14
+ this.status = problem.status;
15
+ this.problem = problem;
16
+ }
17
+ }
18
+ /** refusal is funcd's problem as a JobError. A body that is no problem, as the 422 of an input off the Job's contract,
19
+ * which answers as a Function's call does, keeps its text as the detail, as context.invoke's error does. */
20
+ function refusal(call, r) {
21
+ const text = r.body.toString('utf8');
22
+ let problem = { type: 'about:blank', title: '', status: r.status, detail: text };
23
+ try {
24
+ const parsed = JSON.parse(text);
25
+ problem = {
26
+ type: parsed.type ?? 'about:blank',
27
+ title: parsed.title ?? '',
28
+ status: parsed.status ?? r.status,
29
+ detail: parsed.detail ?? text,
30
+ };
31
+ }
32
+ catch {
33
+ // not JSON: keep its text
34
+ }
35
+ return new JobError(call, problem);
36
+ }
37
+ const parsed = (call, r) => {
38
+ try {
39
+ return JSON.parse(r.body.toString('utf8'));
40
+ }
41
+ catch (err) {
42
+ throw new Error(`${call} failed: ${r.status} reply is not JSON: ${err.message}`, { cause: err });
43
+ }
44
+ };
45
+ const ok = (r) => r.status >= 200 && r.status < 300;
46
+ /** Build context.job. In a pool, `member` names the calling function on every request; the solo shim passes none. */
47
+ export function makeJob(member) {
48
+ return {
49
+ async start(alias, input, name) {
50
+ const call = `context.job.start("${alias}")`;
51
+ const body = Buffer.from(JSON.stringify(name === undefined ? { input } : { input, name }), 'utf8');
52
+ const r = await send('context.job', 'POST', `/job/${encodeURIComponent(alias)}`, body, member, 'application/json');
53
+ if (!ok(r))
54
+ throw refusal(call, r);
55
+ return parsed(call, r).run;
56
+ },
57
+ async get(alias, run) {
58
+ const call = `context.job.get("${alias}", "${run}")`;
59
+ const r = await send('context.job', 'GET', `/job/${encodeURIComponent(alias)}/${encodeURIComponent(run)}`, undefined, member);
60
+ if (!ok(r))
61
+ throw refusal(call, r);
62
+ return parsed(call, r);
63
+ },
64
+ };
65
+ }
66
+ /** readApproval reads the approval of the caller's own run from funcd (funcd ADR-0348): null for a run with none, as a
67
+ * run of a Job with approval.bypass. It fails when funcd does not answer the run, so a handler never runs with an
68
+ * approval it could not read. */
69
+ export async function readApproval() {
70
+ const call = 'context.approval';
71
+ const r = await send(call, 'GET', '/job/run', undefined, undefined);
72
+ if (r.status !== 200)
73
+ throw refusal(call, r);
74
+ return parsed(call, r).approval ?? null;
75
+ }
@@ -0,0 +1,12 @@
1
+ import type http from 'node:http';
2
+ /** The header that carries a container worker's token to its own local API listener (funcd ADR-0346 Decision 6). */
3
+ export declare const TOKEN_HEADER = "x-funcd-invoke-token";
4
+ /** Where a request reaches the local API: the options that dial it and the headers every request carries. */
5
+ export interface LocalApi {
6
+ options: http.RequestOptions;
7
+ headers: Record<string, string>;
8
+ }
9
+ /** localApi is where this worker reaches funcd's local API: FUNCD_INVOKE_URL, the listener of a worker in a container,
10
+ * with FUNCD_INVOKE_TOKEN in TOKEN_HEADER on every request (funcd ADR-0346 Decision 6), else the socket
11
+ * FUNCD_INVOKE_SOCKET (funcd ADR-0064); undefined when neither is set. */
12
+ export declare function localApi(env?: NodeJS.ProcessEnv): LocalApi | undefined;
@@ -0,0 +1,17 @@
1
+ /** The header that carries a container worker's token to its own local API listener (funcd ADR-0346 Decision 6). */
2
+ export const TOKEN_HEADER = 'x-funcd-invoke-token';
3
+ /** localApi is where this worker reaches funcd's local API: FUNCD_INVOKE_URL, the listener of a worker in a container,
4
+ * with FUNCD_INVOKE_TOKEN in TOKEN_HEADER on every request (funcd ADR-0346 Decision 6), else the socket
5
+ * FUNCD_INVOKE_SOCKET (funcd ADR-0064); undefined when neither is set. */
6
+ export function localApi(env = process.env) {
7
+ const url = env.FUNCD_INVOKE_URL;
8
+ if (url) {
9
+ const u = new URL(url);
10
+ const headers = {};
11
+ if (env.FUNCD_INVOKE_TOKEN)
12
+ headers[TOKEN_HEADER] = env.FUNCD_INVOKE_TOKEN;
13
+ return { options: { host: u.hostname, port: u.port === '' ? 80 : Number(u.port) }, headers };
14
+ }
15
+ const socketPath = env.FUNCD_INVOKE_SOCKET;
16
+ return socketPath ? { options: { socketPath }, headers: {} } : undefined;
17
+ }
package/dist/socket.js CHANGED
@@ -1,16 +1,17 @@
1
1
  // The worker-node local API client shared by context.kv, context.blob and context.sql: one HTTP request over the
2
- // per-sandbox socket (FUNCD_INVOKE_SOCKET), as the calling pool member when one is given.
2
+ // local API (localApi), as the calling pool member when one is given.
3
3
  import http from 'node:http';
4
4
  import { MEMBER_HEADER } from "./invoke.js";
5
+ import { localApi } from "./localapi.js";
5
6
  /** send makes one request with `extra` headers; `client` names the context client in its errors ("context.kv"). */
6
7
  export function send(client, method, path, body, member, contentType, extra) {
7
8
  return new Promise((resolve, reject) => {
8
- const socketPath = process.env.FUNCD_INVOKE_SOCKET;
9
- if (!socketPath) {
9
+ const api = localApi();
10
+ if (!api) {
10
11
  reject(new Error(`${client}: worker-node local API socket unavailable (FUNCD_INVOKE_SOCKET unset)`));
11
12
  return;
12
13
  }
13
- const headers = {};
14
+ const headers = { ...api.headers };
14
15
  if (body)
15
16
  headers['content-length'] = body.byteLength;
16
17
  if (contentType)
@@ -18,7 +19,7 @@ export function send(client, method, path, body, member, contentType, extra) {
18
19
  if (member)
19
20
  headers[MEMBER_HEADER] = member;
20
21
  Object.assign(headers, extra);
21
- const req = http.request({ socketPath, path, method, headers }, (res) => {
22
+ const req = http.request({ ...api.options, path, method, headers }, (res) => {
22
23
  const chunks = [];
23
24
  // A connection that drops mid-body errors the response, not the request, and never ends it.
24
25
  res.on('error', (err) => reject(new Error(`${client} ${method} ${path} failed: connection closed before the reply ended`, { cause: err })));
package/dist/types.d.ts CHANGED
@@ -5,6 +5,7 @@ import type { ConfigClient } from './config.ts';
5
5
  import type { SecretClient } from './secret.ts';
6
6
  import type { LakeClient } from './lake.ts';
7
7
  import type { AddonClient } from './addon.ts';
8
+ import type { Approval, JobClient } from './job.ts';
8
9
  export type { KVClient, KVEntry, PutOptions } from './kv.ts';
9
10
  export type { BlobClient, SignOptions } from './blob.ts';
10
11
  export type { SQLClient, SQLExecResult, SQLParam, SQLParams, SQLRow, SQLStatement, SQLValues, } from './sql.ts';
@@ -12,6 +13,7 @@ export type { ConfigClient } from './config.ts';
12
13
  export type { SecretClient } from './secret.ts';
13
14
  export type { LakeClient, LakeEndpoint } from './lake.ts';
14
15
  export type { AddonClient, AddonError, AddonProblem } from './addon.ts';
16
+ export type { Approval, JobClient, JobError, JobProblem, JobRunState } from './job.ts';
15
17
  /** A CloudEvent — the normalized trigger envelope (ADR-0023). */
16
18
  export interface CloudEvent<T = unknown> {
17
19
  id: string;
@@ -68,6 +70,8 @@ export interface FunctionContext {
68
70
  /** The add-on objects that the function binds, by alias: fetch calls an object's engine through funcd, which serves
69
71
  * only the paths that the object's edge entry serves. */
70
72
  addon: AddonClient;
73
+ /** The Jobs that the function binds, by alias: start a run of one with an input, and read a run back. */
74
+ job: JobClient;
71
75
  /** The whole milliseconds left before the call's deadline, 0 once it has passed, or null when the call has none. */
72
76
  remainingMs(): number | null;
73
77
  /** Who signed in to the call, when funcd's edge signed a user in with an OpenID Connect provider: provider is the
@@ -91,10 +95,17 @@ export interface RunInfo {
91
95
  phase: 'run' | 'preview';
92
96
  startedBy: string;
93
97
  }
94
- /** The context a Job's handler gets (funcd ADR-0347): the FunctionContext plus its run. */
98
+ /** The context a Job's handler and its preview get (funcd ADR-0347, ADR-0348): the FunctionContext plus its run and,
99
+ * in the run's call, the approval it runs under. */
95
100
  export interface JobContext extends FunctionContext {
96
101
  run: RunInfo;
102
+ /** The person's approval of the preview that this run runs: who approved it, the preview's digest and its document.
103
+ * Null in the preview call, and for a run of a Job with approval.bypass. */
104
+ approval: Approval | null;
97
105
  }
106
+ /** A Job module's optional preview export (funcd ADR-0348): called in a run's preview call, before a person approves
107
+ * the run, it answers what the run would change, as JSON. A module with none previews its run's input. */
108
+ export type Preview<In = unknown> = (context: JobContext, event: CloudEvent<In>) => Json | Promise<Json>;
98
109
  /** A function handler: receives the context + CloudEvent, returns a response (or nothing). */
99
110
  export type Handler<In = unknown, Out = unknown> = (context: FunctionContext, event: CloudEvent<In>) => Out | Promise<Out>;
100
111
  /** An HTTP app (funcd ADR-0243): Hono, or any object whose fetch answers a Web Request. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funcd-dev/shim",
3
- "version": "0.34.0",
3
+ "version": "0.36.0",
4
4
  "type": "module",
5
5
  "description": "Types and the contract build for writing funcd functions in TypeScript",
6
6
  "license": "Apache-2.0",