@funcd-dev/shim 0.24.0 → 0.25.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/kv.d.ts CHANGED
@@ -1,14 +1,35 @@
1
- /** A function's view of its namespace-scoped KV (ADR-0069): get/put/del a binding's key, or list keys. */
1
+ /** A key's value with its version, which a compareAndSet or a delIf names. */
2
+ export interface KVEntry {
3
+ value: Uint8Array;
4
+ version: string;
5
+ }
6
+ /** How long a written key lives. Each write sets its own expiry: one without ttl leaves the key with none. */
7
+ export interface PutOptions {
8
+ /** Whole seconds from 1: the key lives at least ttl from when funcd takes the write, so a holder that counts its
9
+ * lease from before the call never counts past the key's expiry. Renew it with a compareAndSet and a new ttl. */
10
+ ttl?: number;
11
+ }
12
+ /** A function's view of its namespace-scoped KV (ADR-0069): get/put/del a binding's key, or list keys.
13
+ * putIfAbsent, compareAndSet and delIf write only while their condition holds and say who won: of racing writers
14
+ * exactly one gets the new version, the others null (false for a delete). */
2
15
  export interface KVClient {
3
16
  get(binding: string, key: string): Promise<Uint8Array | null>;
17
+ /** get() with the key's version (a missing key is null). */
18
+ getEntry(binding: string, key: string): Promise<KVEntry | null>;
4
19
  /** get() decoded as UTF-8 text — the common case (a missing key is null). Saves the caller a
5
20
  * TextDecoder dance; put() already accepts a string. */
6
21
  getText(binding: string, key: string): Promise<string | null>;
7
22
  /** get() decoded as UTF-8 text then JSON-parsed (a missing key is null). The structured-value
8
23
  * counterpart of getText; write with put(binding, key, JSON.stringify(value)). */
9
24
  getJSON<T = unknown>(binding: string, key: string): Promise<T | null>;
10
- put(binding: string, key: string, value: Uint8Array | string): Promise<void>;
25
+ put(binding: string, key: string, value: Uint8Array | string, opts?: PutOptions): Promise<void>;
26
+ /** Create the key: its new version, or null when it exists (an expired key does not). */
27
+ putIfAbsent(binding: string, key: string, value: Uint8Array | string, opts?: PutOptions): Promise<string | null>;
28
+ /** Replace the key while it is at version: its new version, or null when it is not. */
29
+ compareAndSet(binding: string, key: string, value: Uint8Array | string, version: string, opts?: PutOptions): Promise<string | null>;
11
30
  del(binding: string, key: string): Promise<void>;
31
+ /** Delete the key while it is at version, as a lease holder releases what it holds. */
32
+ delIf(binding: string, key: string, version: string): Promise<boolean>;
12
33
  list(binding: string, prefix?: string): Promise<string[]>;
13
34
  }
14
35
  /** Build the context.kv client. In a pool, `member` names the calling function on every request
package/dist/kv.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // same per-sandbox socket as context.invoke (FUNCD_INVOKE_SOCKET); the platform routes /kv/… to the
3
3
  // PDP-authorized Facade with the sandbox's namespace identity. Reached only through the built-in shim.
4
4
  import { send as sendOn } from "./socket.js";
5
- const send = (method, path, body, member) => sendOn('context.kv', method, path, body, member);
5
+ const send = (method, path, body, member, headers) => sendOn('context.kv', method, path, body, member, undefined, headers);
6
6
  const enc = encodeURIComponent;
7
7
  // key may be hierarchical ("a/b"); keep the "/" separators (the server's {key...} captures them), encode segments.
8
8
  const keyPath = (binding, key) => `/kv/${enc(binding)}/${key.split('/').map(enc).join('/')}`;
@@ -18,10 +18,28 @@ const json = (verb, r, text) => {
18
18
  });
19
19
  }
20
20
  };
21
+ const version = (r) => (r.etag ?? '').replace(/^"|"$/g, '');
22
+ const withTTL = (path, opts) => {
23
+ if (opts?.ttl === undefined)
24
+ return path;
25
+ if (!Number.isSafeInteger(opts.ttl) || opts.ttl < 1) {
26
+ throw new RangeError(`context.kv: ttl must be a whole number of seconds from 1, not ${opts.ttl}`);
27
+ }
28
+ return `${path}?ttl=${opts.ttl}`;
29
+ };
30
+ const bytes = (value) => typeof value === 'string' ? Buffer.from(value, 'utf8') : Buffer.from(value);
21
31
  /** Build the context.kv client. In a pool, `member` names the calling function on every request
22
32
  * (funcd checks it against the pool's members); the solo shim passes none. */
23
33
  export function makeKV(member) {
24
- const request = (method, path, body) => send(method, path, body, member);
34
+ const request = (method, path, body, headers) => send(method, path, body, member, headers);
35
+ const conditionalPut = async (verb, binding, key, value, opts, headers) => {
36
+ const r = await request('PUT', withTTL(keyPath(binding, key), opts), bytes(value), headers);
37
+ if (r.status === 412)
38
+ return null;
39
+ if (!ok(r))
40
+ throw fail(verb, r);
41
+ return version(r);
42
+ };
25
43
  return {
26
44
  async get(binding, key) {
27
45
  const r = await request('GET', keyPath(binding, key));
@@ -31,6 +49,14 @@ export function makeKV(member) {
31
49
  throw fail('get', r);
32
50
  return new Uint8Array(r.body);
33
51
  },
52
+ async getEntry(binding, key) {
53
+ const r = await request('GET', keyPath(binding, key));
54
+ if (r.status === 404)
55
+ return null;
56
+ if (!ok(r))
57
+ throw fail('getEntry', r);
58
+ return { value: new Uint8Array(r.body), version: version(r) };
59
+ },
34
60
  async getText(binding, key) {
35
61
  const r = await request('GET', keyPath(binding, key));
36
62
  if (r.status === 404)
@@ -47,17 +73,30 @@ export function makeKV(member) {
47
73
  throw fail('get', r);
48
74
  return json('getJSON', r, r.body.toString('utf8'));
49
75
  },
50
- async put(binding, key, value) {
51
- const buf = typeof value === 'string' ? Buffer.from(value, 'utf8') : Buffer.from(value);
52
- const r = await request('PUT', keyPath(binding, key), buf);
76
+ async put(binding, key, value, opts) {
77
+ const r = await request('PUT', withTTL(keyPath(binding, key), opts), bytes(value));
53
78
  if (!ok(r))
54
79
  throw fail('put', r);
55
80
  },
81
+ putIfAbsent(binding, key, value, opts) {
82
+ return conditionalPut('putIfAbsent', binding, key, value, opts, { 'if-none-match': '*' });
83
+ },
84
+ compareAndSet(binding, key, value, v, opts) {
85
+ return conditionalPut('compareAndSet', binding, key, value, opts, { 'if-match': `"${v}"` });
86
+ },
56
87
  async del(binding, key) {
57
88
  const r = await request('DELETE', keyPath(binding, key));
58
89
  if (!ok(r))
59
90
  throw fail('del', r);
60
91
  },
92
+ async delIf(binding, key, v) {
93
+ const r = await request('DELETE', keyPath(binding, key), undefined, { 'if-match': `"${v}"` });
94
+ if (r.status === 412)
95
+ return false;
96
+ if (!ok(r))
97
+ throw fail('delIf', r);
98
+ return true;
99
+ },
61
100
  async list(binding, prefix) {
62
101
  const q = prefix ? `?prefix=${enc(prefix)}` : '';
63
102
  const r = await request('GET', `/kv/${enc(binding)}${q}`);
package/dist/socket.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export interface Resp {
2
2
  status: number;
3
3
  body: Buffer;
4
+ /** The reply's ETag, when it has one: a KV key's version. */
5
+ etag?: string;
4
6
  }
5
- /** send makes one request; `client` names the context client in its errors ("context.kv"). */
6
- export declare function send(client: string, method: string, path: string, body: Buffer | undefined, member: string | undefined, contentType?: string): Promise<Resp>;
7
+ /** send makes one request with `extra` headers; `client` names the context client in its errors ("context.kv"). */
8
+ export declare function send(client: string, method: string, path: string, body: Buffer | undefined, member: string | undefined, contentType?: string, extra?: Record<string, string>): Promise<Resp>;
package/dist/socket.js CHANGED
@@ -2,8 +2,8 @@
2
2
  // per-sandbox socket (FUNCD_INVOKE_SOCKET), 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
- /** send makes one request; `client` names the context client in its errors ("context.kv"). */
6
- export function send(client, method, path, body, member, contentType) {
5
+ /** send makes one request with `extra` headers; `client` names the context client in its errors ("context.kv"). */
6
+ export function send(client, method, path, body, member, contentType, extra) {
7
7
  return new Promise((resolve, reject) => {
8
8
  const socketPath = process.env.FUNCD_INVOKE_SOCKET;
9
9
  if (!socketPath) {
@@ -17,12 +17,13 @@ export function send(client, method, path, body, member, contentType) {
17
17
  headers['content-type'] = contentType;
18
18
  if (member)
19
19
  headers[MEMBER_HEADER] = member;
20
+ Object.assign(headers, extra);
20
21
  const req = http.request({ socketPath, path, method, headers }, (res) => {
21
22
  const chunks = [];
22
23
  // A connection that drops mid-body errors the response, not the request, and never ends it.
23
24
  res.on('error', (err) => reject(new Error(`${client} ${method} ${path} failed: connection closed before the reply ended`, { cause: err })));
24
25
  res.on('data', (c) => chunks.push(c));
25
- res.on('end', () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks) }));
26
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks), etag: res.headers.etag }));
26
27
  });
27
28
  req.on('error', (err) => reject(new Error(`${client} ${method} ${path} failed: ${err.message}`, { cause: err })));
28
29
  if (body)
package/dist/types.d.ts CHANGED
@@ -4,7 +4,7 @@ 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
- export type { KVClient } from './kv.ts';
7
+ export type { KVClient, KVEntry, PutOptions } from './kv.ts';
8
8
  export type { BlobClient, SignOptions } from './blob.ts';
9
9
  export type { SQLClient, SQLExecResult, SQLParam, SQLParams, SQLRow, SQLStatement, SQLValues, } from './sql.ts';
10
10
  export type { ConfigClient } from './config.ts';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funcd-dev/shim",
3
- "version": "0.24.0",
3
+ "version": "0.25.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",