@funcd-dev/shim 0.29.0 → 0.31.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.
@@ -0,0 +1,33 @@
1
+ import { type InvokeOptions } from './invoke.ts';
2
+ /** The local API header that marks an answer as the engine's; a call that funcd refused carries none. */
3
+ export declare const ADDON_REPLY_HEADER = "x-funcd-addon-reply";
4
+ /** funcd's problem, the body of a refusal (RFC 9457). */
5
+ export interface AddonProblem {
6
+ type: string;
7
+ title: string;
8
+ status: number;
9
+ detail: string;
10
+ }
11
+ /** A call that funcd refused before it reached the engine. */
12
+ export declare class AddonError extends Error {
13
+ /** The HTTP status of the refusal. */
14
+ readonly status: number;
15
+ /** funcd's problem. */
16
+ readonly problem: AddonProblem;
17
+ /** The seconds to wait before a retry, from the Retry-After of a 503, as while the namespace is held. */
18
+ readonly retryAfter?: number;
19
+ constructor(alias: string, problem: AddonProblem, retryAfter?: number);
20
+ }
21
+ export interface AddonClient {
22
+ /** Sends an HTTP request to the engine of the add-on object that the function binds under alias, through funcd, and
23
+ * returns the engine's answer as a Response, whatever its status; funcd follows no redirect. path starts with "/"
24
+ * and may carry a query, and init sets the method, the headers and the body, as for the global fetch. Rejects with
25
+ * an AddonError when funcd refuses the call: 403 for an alias the function does not bind or a call a Policy
26
+ * forbids, 404 for a path the object's edge entry does not serve, 413 for a request or an answer body over
27
+ * addons.callPayloadLimit, 1 MiB by default, and 503 while the object is not Ready, while its namespace is held
28
+ * (with retryAfter), or when the engine does not answer within addons.callTimeout, 10 seconds by default. */
29
+ fetch(alias: string, path: string, init?: RequestInit): Promise<Response>;
30
+ }
31
+ /** Build context.addon: fetch sends the request to /addon/<alias><path> on the local API, as the pool member when one
32
+ * is given, with the CLIENT span's traceparent. */
33
+ export declare function makeAddon(opts?: InvokeOptions): AddonClient;
package/dist/addon.js ADDED
@@ -0,0 +1,112 @@
1
+ // context.addon (funcd ADR-0338): a call of the engine of an add-on object that the function binds, through funcd's
2
+ // worker-node local API, which checks the binding and the path before it forwards the request.
3
+ import http from 'node:http';
4
+ import { MEMBER_HEADER } from "./invoke.js";
5
+ import { startClientSpan } from "./tracespan.js";
6
+ /** The local API header that marks an answer as the engine's; a call that funcd refused carries none. */
7
+ export const ADDON_REPLY_HEADER = 'x-funcd-addon-reply';
8
+ /** The statuses whose Response carries no body. */
9
+ const NULL_BODY = new Set([101, 204, 205, 304]);
10
+ /** A call that funcd refused before it reached the engine. */
11
+ export class AddonError extends Error {
12
+ /** The HTTP status of the refusal. */
13
+ status;
14
+ /** funcd's problem. */
15
+ problem;
16
+ /** The seconds to wait before a retry, from the Retry-After of a 503, as while the namespace is held. */
17
+ retryAfter;
18
+ constructor(alias, problem, retryAfter) {
19
+ super(`context.addon.fetch("${alias}") failed: ${problem.status} ${problem.detail}`);
20
+ this.name = 'AddonError';
21
+ this.status = problem.status;
22
+ this.problem = problem;
23
+ this.retryAfter = retryAfter;
24
+ }
25
+ }
26
+ /** Build context.addon: fetch sends the request to /addon/<alias><path> on the local API, as the pool member when one
27
+ * is given, with the CLIENT span's traceparent. */
28
+ export function makeAddon(opts = {}) {
29
+ return {
30
+ async fetch(alias, path, init) {
31
+ const span = startClientSpan(opts.sink ?? null, alias, opts.member, opts.bound);
32
+ const fail = (err, httpStatus) => {
33
+ span?.end('ERROR', err.message, httpStatus);
34
+ throw err;
35
+ };
36
+ const socketPath = process.env.FUNCD_INVOKE_SOCKET;
37
+ if (!socketPath) {
38
+ return fail(new Error('context.addon: worker-node local API socket unavailable (FUNCD_INVOKE_SOCKET unset)'));
39
+ }
40
+ if (!path.startsWith('/')) {
41
+ return fail(new Error(`context.addon.fetch("${alias}"): path "${path}" must start with "/"`));
42
+ }
43
+ const request = new Request(new URL(path, 'http://funcd.local'), init);
44
+ const body = request.body ? Buffer.from(await request.arrayBuffer()) : undefined;
45
+ const headers = {};
46
+ request.headers.forEach((value, key) => {
47
+ headers[key] = value;
48
+ });
49
+ if (body)
50
+ headers['content-length'] = String(body.length);
51
+ if (opts.member)
52
+ headers[MEMBER_HEADER] = opts.member;
53
+ if (span)
54
+ headers.traceparent = span.traceparent;
55
+ const target = new URL(request.url);
56
+ const reply = await new Promise((resolve, reject) => {
57
+ const req = http.request({
58
+ socketPath,
59
+ path: `/addon/${encodeURIComponent(alias)}${target.pathname}${target.search}`,
60
+ method: request.method,
61
+ headers,
62
+ }, (res) => {
63
+ const chunks = [];
64
+ res.on('error', (err) => reject(new Error(`context.addon.fetch("${alias}") failed: connection closed before the reply ended`, {
65
+ cause: err,
66
+ })));
67
+ res.on('data', (c) => chunks.push(c));
68
+ res.on('end', () => {
69
+ const replyHeaders = new Headers();
70
+ for (const [key, value] of Object.entries(res.headers)) {
71
+ for (const v of Array.isArray(value) ? value : [value]) {
72
+ if (v !== undefined)
73
+ replyHeaders.append(key, v);
74
+ }
75
+ }
76
+ resolve({ status: res.statusCode ?? 0, headers: replyHeaders, body: Buffer.concat(chunks) });
77
+ });
78
+ });
79
+ req.on('error', (err) => reject(new Error(`context.addon.fetch("${alias}") failed: ${err.message}`, { cause: err })));
80
+ req.end(body);
81
+ }).catch((err) => fail(err));
82
+ if (!reply.headers.has(ADDON_REPLY_HEADER)) {
83
+ return fail(refusal(alias, reply.status, reply.headers, reply.body), reply.status);
84
+ }
85
+ reply.headers.delete(ADDON_REPLY_HEADER);
86
+ span?.end(reply.status >= 500 ? 'ERROR' : 'OK', '', reply.status);
87
+ return new Response(NULL_BODY.has(reply.status) ? null : new Uint8Array(reply.body), {
88
+ status: reply.status,
89
+ headers: reply.headers,
90
+ });
91
+ },
92
+ };
93
+ }
94
+ /** refusal is funcd's problem as an AddonError; a body that is no problem keeps its text as the detail. */
95
+ function refusal(alias, status, headers, body) {
96
+ const text = body.toString('utf8');
97
+ let problem = { type: 'about:blank', title: '', status, detail: text };
98
+ try {
99
+ const parsed = JSON.parse(text);
100
+ problem = {
101
+ type: parsed.type ?? 'about:blank',
102
+ title: parsed.title ?? '',
103
+ status: parsed.status ?? status,
104
+ detail: parsed.detail ?? '',
105
+ };
106
+ }
107
+ catch {
108
+ // not a problem body: keep its text
109
+ }
110
+ const after = status === 503 ? Number.parseInt(headers.get('retry-after') ?? '', 10) : Number.NaN;
111
+ return new AddonError(alias, problem, Number.isFinite(after) ? after : undefined);
112
+ }
@@ -1,4 +1,5 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import type { Principal } from './principal.ts';
2
3
  /** The identity of the currently-executing invocation. */
3
4
  export interface InvContext {
4
5
  inv: string;
@@ -6,6 +7,7 @@ export interface InvContext {
6
7
  spanId: string;
7
8
  parentId: string;
8
9
  deadline?: number;
10
+ principal?: Principal;
9
11
  }
10
12
  /** invStore holds the active InvContext for the duration of a handler call (and its async
11
13
  * continuations). Per-thread: each worker/process imports its own instance, which is correct —
@@ -3,7 +3,8 @@
3
3
  // buildRecord) tag their records with the SAME inv/trace/span ids — the logs↔trace correlation that
4
4
  // closes ADR-0081's provenance open question. ADR-0081 specified this carrier but never shipped it
5
5
  // (inv/trace_id/span_id were hardcoded empty); this is where it is introduced. It also carries the
6
- // call's deadline, which ctx.remainingMs() reads (ADR-0226).
6
+ // call's deadline, which ctx.remainingMs() reads (ADR-0226), and its principal, which ctx.principal reads
7
+ // (funcd ADR-0335): the handler's context is one object for every call.
7
8
  //
8
9
  // Built-ins only (node:async_hooks) so it bundles into shim.mjs/pool.mjs.
9
10
  import { AsyncLocalStorage } from 'node:async_hooks';
@@ -0,0 +1,10 @@
1
+ import type { FunctionContext } from './types.ts';
2
+ /** The principal of a signed-in call, as ctx.principal holds it. */
3
+ export type Principal = NonNullable<FunctionContext['principal']>;
4
+ /** The headers funcd's edge sets for a signed-in call. An http app receives them as sent. */
5
+ export declare const PRINCIPAL_HEADERS: ReadonlySet<string>;
6
+ /** principalFrom builds a call's principal from its headers: provider and claims from X-Funcd-Principal, the standard
7
+ * Base64 of the JSON {provider, claims}, id from X-Funcd-Principal-Id and name from X-Funcd-Principal-Name. It is
8
+ * undefined when X-Funcd-Principal or X-Funcd-Principal-Id is absent or empty, or when X-Funcd-Principal is not that
9
+ * encoding of an object with a provider name and an object of claims. */
10
+ export declare function principalFrom(headers: Headers): Principal | undefined;
@@ -0,0 +1,37 @@
1
+ /** The headers funcd's edge sets for a signed-in call. An http app receives them as sent. */
2
+ export const PRINCIPAL_HEADERS = new Set([
3
+ 'x-funcd-principal',
4
+ 'x-funcd-principal-id',
5
+ 'x-funcd-principal-name',
6
+ 'x-funcd-id-token',
7
+ ]);
8
+ // Standard Base64 with its padding, the form the edge writes.
9
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
10
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
11
+ // Node reads each byte of a header value as one Latin-1 character; the edge writes the values as UTF-8.
12
+ const utf8 = (value) => Buffer.from(value, 'latin1').toString('utf8');
13
+ /** principalFrom builds a call's principal from its headers: provider and claims from X-Funcd-Principal, the standard
14
+ * Base64 of the JSON {provider, claims}, id from X-Funcd-Principal-Id and name from X-Funcd-Principal-Name. It is
15
+ * undefined when X-Funcd-Principal or X-Funcd-Principal-Id is absent or empty, or when X-Funcd-Principal is not that
16
+ * encoding of an object with a provider name and an object of claims. */
17
+ export function principalFrom(headers) {
18
+ const encoded = headers.get('x-funcd-principal');
19
+ const id = headers.get('x-funcd-principal-id');
20
+ if (!encoded || !id || !BASE64.test(encoded))
21
+ return undefined;
22
+ let value;
23
+ try {
24
+ value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.from(encoded, 'base64')));
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ if (!isObject(value) || typeof value.provider !== 'string' || value.provider === '' || !isObject(value.claims)) {
30
+ return undefined;
31
+ }
32
+ const principal = { provider: value.provider, id: utf8(id), claims: value.claims };
33
+ const name = headers.get('x-funcd-principal-name');
34
+ if (name)
35
+ principal.name = utf8(name);
36
+ return principal;
37
+ }
@@ -1,5 +1,6 @@
1
1
  import { type InvContext } from './invcontext.ts';
2
2
  import { type Sink } from './funclog.ts';
3
+ import type { Principal } from './principal.ts';
3
4
  /** parseTraceparent parses a W3C `traceparent` (`00-<trace32>-<span16>-<flags>`), returning the
4
5
  * trace-id + parent span-id, or null when absent/malformed/all-zero (⇒ the caller mints a root). */
5
6
  export declare function parseTraceparent(tp: string | undefined): {
@@ -9,8 +10,9 @@ export declare function parseTraceparent(tp: string | undefined): {
9
10
  /** newInvContext establishes the invocation identity: adopt the traceparent's trace-id + parent
10
11
  * span-id when present, else mint a root (fresh 16-byte trace). The span-id is the engine-provided
11
12
  * one (ADR-0105, X-Funcd-Span-Id) when a valid hex16 is given, else freshly minted (direct invoke).
12
- * `deadline` is the call's deadline (ADR-0226), absent without a valid X-Funcd-Timeout-Ms. */
13
- export declare function newInvContext(tp: string | undefined, providedSpanId?: string, deadline?: number): InvContext;
13
+ * `deadline` is the call's deadline (ADR-0226), absent without a valid X-Funcd-Timeout-Ms; `principal` is who signed
14
+ * in to the call (funcd ADR-0335), absent when nobody did. */
15
+ export declare function newInvContext(tp: string | undefined, providedSpanId?: string, deadline?: number, principal?: Principal): InvContext;
14
16
  /** A live invocation span: run the handler inside its context (so logs correlate), then end() it
15
17
  * with the outcome (which emits the span record on the channel). end() is idempotent. */
16
18
  export interface Span {
@@ -24,8 +26,8 @@ export interface Span {
24
26
  * X-Funcd-Span-Id — else mint); `links` are fan-in edges (X-Funcd-Span-Links) attached to the span;
25
27
  * `member` is the pool member, stamped as `funcd.member` (none in the solo shim); `bound` caps the span
26
28
  * record line (FUNCD_FUNCLOG_MAX_RECORD_BYTES); `deadline` is the call's deadline, which ctx.remainingMs()
27
- * reads (ADR-0226). */
28
- export declare function startSpan(sink: Sink | null, name: string, tp: string | undefined, spanId?: string, links?: string[], member?: string, bound?: number, deadline?: number): Span;
29
+ * reads (ADR-0226); `principal` is who signed in to the call, which ctx.principal reads (funcd ADR-0335). */
30
+ export declare function startSpan(sink: Sink | null, name: string, tp: string | undefined, spanId?: string, links?: string[], member?: string, bound?: number, deadline?: number, principal?: Principal): Span;
29
31
  /** The CLIENT span of one context.invoke call (ADR-0165). */
30
32
  export interface ClientSpan {
31
33
  /** 00-<caller trace>-<this span>-01, stamped on POST /invoke/{alias}. */
package/dist/tracespan.js CHANGED
@@ -30,8 +30,9 @@ export function parseTraceparent(tp) {
30
30
  /** newInvContext establishes the invocation identity: adopt the traceparent's trace-id + parent
31
31
  * span-id when present, else mint a root (fresh 16-byte trace). The span-id is the engine-provided
32
32
  * one (ADR-0105, X-Funcd-Span-Id) when a valid hex16 is given, else freshly minted (direct invoke).
33
- * `deadline` is the call's deadline (ADR-0226), absent without a valid X-Funcd-Timeout-Ms. */
34
- export function newInvContext(tp, providedSpanId, deadline) {
33
+ * `deadline` is the call's deadline (ADR-0226), absent without a valid X-Funcd-Timeout-Ms; `principal` is who signed
34
+ * in to the call (funcd ADR-0335), absent when nobody did. */
35
+ export function newInvContext(tp, providedSpanId, deadline, principal) {
35
36
  const adopted = parseTraceparent(tp);
36
37
  const spanId = providedSpanId && /^[0-9a-f]{16}$/.test(providedSpanId) ? providedSpanId : randomBytes(8).toString('hex');
37
38
  return {
@@ -40,6 +41,7 @@ export function newInvContext(tp, providedSpanId, deadline) {
40
41
  spanId,
41
42
  parentId: adopted ? adopted.parentId : '',
42
43
  deadline,
44
+ principal,
43
45
  };
44
46
  }
45
47
  /** emitSpan writes one span record. `ids` names the span (trace, span, parent, inv): the invocation's
@@ -91,9 +93,9 @@ function boundSpan(rec, bound) {
91
93
  * X-Funcd-Span-Id — else mint); `links` are fan-in edges (X-Funcd-Span-Links) attached to the span;
92
94
  * `member` is the pool member, stamped as `funcd.member` (none in the solo shim); `bound` caps the span
93
95
  * record line (FUNCD_FUNCLOG_MAX_RECORD_BYTES); `deadline` is the call's deadline, which ctx.remainingMs()
94
- * reads (ADR-0226). */
95
- export function startSpan(sink, name, tp, spanId, links = [], member, bound = DEFAULT_MAX_RECORD_BYTES, deadline) {
96
- const inv = newInvContext(tp, spanId, deadline);
96
+ * reads (ADR-0226); `principal` is who signed in to the call, which ctx.principal reads (funcd ADR-0335). */
97
+ export function startSpan(sink, name, tp, spanId, links = [], member, bound = DEFAULT_MAX_RECORD_BYTES, deadline, principal) {
98
+ const inv = newInvContext(tp, spanId, deadline, principal);
97
99
  const startNs = Date.now() * 1e6;
98
100
  const t0 = process.hrtime.bigint();
99
101
  const validLinks = links.filter((l) => /^[0-9a-f]{16}$/.test(l));
package/dist/types.d.ts CHANGED
@@ -4,12 +4,14 @@ import type { SQLClient } from './sql.ts';
4
4
  import type { ConfigClient } from './config.ts';
5
5
  import type { SecretClient } from './secret.ts';
6
6
  import type { LakeClient } from './lake.ts';
7
+ import type { AddonClient } from './addon.ts';
7
8
  export type { KVClient, KVEntry, PutOptions } from './kv.ts';
8
9
  export type { BlobClient, SignOptions } from './blob.ts';
9
10
  export type { SQLClient, SQLExecResult, SQLParam, SQLParams, SQLRow, SQLStatement, SQLValues, } from './sql.ts';
10
11
  export type { ConfigClient } from './config.ts';
11
12
  export type { SecretClient } from './secret.ts';
12
13
  export type { LakeClient, LakeEndpoint } from './lake.ts';
14
+ export type { AddonClient, AddonError, AddonProblem } from './addon.ts';
13
15
  /** A CloudEvent — the normalized trigger envelope (ADR-0023). */
14
16
  export interface CloudEvent<T = unknown> {
15
17
  id: string;
@@ -63,8 +65,21 @@ export interface FunctionContext {
63
65
  /** The Lakes that the function binds, by alias: the address of each Lake's gateway, and the token that the gateway
64
66
  * accepts from the function. */
65
67
  lake: LakeClient;
68
+ /** The add-on objects that the function binds, by alias: fetch calls an object's engine through funcd, which serves
69
+ * only the paths that the object's edge entry serves. */
70
+ addon: AddonClient;
66
71
  /** The whole milliseconds left before the call's deadline, 0 once it has passed, or null when the call has none. */
67
72
  remainingMs(): number | null;
73
+ /** Who signed in to the call, when funcd's edge signed a user in with an OpenID Connect provider: provider is the
74
+ * name of the OIDCProvider, id the user's subject (the sub claim), name the first of the claims name,
75
+ * preferred_username and email that is not empty, and claims the payload of the token that signed the user in, the
76
+ * ID token of a browser session or the Bearer token of an API call. Undefined when nobody signed in. */
77
+ principal?: {
78
+ provider: string;
79
+ id: string;
80
+ name?: string;
81
+ claims: Record<string, unknown>;
82
+ };
68
83
  }
69
84
  /** A function handler: receives the context + CloudEvent, returns a response (or nothing). */
70
85
  export type Handler<In = unknown, Out = unknown> = (context: FunctionContext, event: CloudEvent<In>) => Out | Promise<Out>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funcd-dev/shim",
3
- "version": "0.29.0",
3
+ "version": "0.31.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",