durability 4.1.1 → 4.2.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,108 @@
1
+ import { z } from 'zod';
2
+ export const grantRowSchema = z.object({
3
+ grant_id: z.string(),
4
+ client_id: z.string(),
5
+ grp: z.string(),
6
+ permits: z.number().int().nonnegative(),
7
+ claimed: z.number().int().nonnegative(),
8
+ released: z.number().int().nonnegative(),
9
+ created_at: z.number().int().nonnegative(),
10
+ /** Unclaimed permits are reclaimed once this passes. */
11
+ expires_at: z.number().int().nonnegative(),
12
+ });
13
+ /** Permits a client may draw locally without a round trip; held by the holder. */
14
+ export const leaseRowSchema = z.object({
15
+ lease_id: z.string(),
16
+ client_id: z.string(),
17
+ grp: z.string(),
18
+ permits: z.number().int().nonnegative(),
19
+ /** Drawn permits the client has returned, as a high-water mark. */
20
+ released: z.number().int().nonnegative(),
21
+ created_at: z.number().int().nonnegative(),
22
+ /** Refreshed by every report; the lease is swept once this passes. */
23
+ expires_at: z.number().int().nonnegative(),
24
+ /** 1 once no more permits may be drawn; footprint stays until released. */
25
+ retired: z.number().int().min(0).max(1),
26
+ });
27
+ const grantColumns = grantRowSchema.keyof().options;
28
+ const leaseColumns = leaseRowSchema.keyof().options;
29
+ /**
30
+ * Permits a semaphore has handed out. Grants and leases are small and bounded
31
+ * by live clients, so aggregates are computed from `list()`.
32
+ */
33
+ export class HolderStore {
34
+ constructor(sql) {
35
+ this.sql = sql;
36
+ }
37
+ list() {
38
+ return grantRowSchema
39
+ .array()
40
+ .parse(this.sql
41
+ .exec('SELECT * FROM durability_semaphore_grants ORDER BY created_at')
42
+ .toArray());
43
+ }
44
+ get(grantId) {
45
+ return grantRowSchema
46
+ .optional()
47
+ .parse(this.sql
48
+ .exec('SELECT * FROM durability_semaphore_grants WHERE grant_id = ? LIMIT 1', grantId)
49
+ .toArray()[0]);
50
+ }
51
+ nextPendingAt() {
52
+ return grantRowSchema
53
+ .pick({ expires_at: true })
54
+ .optional()
55
+ .parse(this.sql
56
+ .exec(`SELECT expires_at FROM durability_semaphore_grants
57
+ WHERE claimed < permits
58
+ ORDER BY expires_at ASC
59
+ LIMIT 1`)
60
+ .toArray()[0])?.expires_at;
61
+ }
62
+ insert(row) {
63
+ return (this.sql
64
+ .exec(`INSERT INTO durability_semaphore_grants (${grantColumns.join(', ')})
65
+ VALUES (${grantColumns.map(() => '?').join(', ')})
66
+ ON CONFLICT(grant_id) DO NOTHING
67
+ RETURNING grant_id`, ...grantColumns.map((column) => row[column]))
68
+ .toArray().length > 0);
69
+ }
70
+ update(row) {
71
+ this.sql.exec(`UPDATE durability_semaphore_grants
72
+ SET permits = ?, claimed = ?, released = ?, expires_at = ?
73
+ WHERE grant_id = ?`, row.permits, row.claimed, row.released, row.expires_at, row.grant_id);
74
+ }
75
+ remove(grantId) {
76
+ this.sql.exec('DELETE FROM durability_semaphore_grants WHERE grant_id = ?', grantId);
77
+ }
78
+ listLeases() {
79
+ return leaseRowSchema
80
+ .array()
81
+ .parse(this.sql
82
+ .exec('SELECT * FROM durability_semaphore_leases ORDER BY created_at')
83
+ .toArray());
84
+ }
85
+ getLease(leaseId) {
86
+ return leaseRowSchema
87
+ .optional()
88
+ .parse(this.sql
89
+ .exec('SELECT * FROM durability_semaphore_leases WHERE lease_id = ? LIMIT 1', leaseId)
90
+ .toArray()[0]);
91
+ }
92
+ insertLease(row) {
93
+ return (this.sql
94
+ .exec(`INSERT INTO durability_semaphore_leases (${leaseColumns.join(', ')})
95
+ VALUES (${leaseColumns.map(() => '?').join(', ')})
96
+ ON CONFLICT(lease_id) DO NOTHING
97
+ RETURNING lease_id`, ...leaseColumns.map((column) => row[column]))
98
+ .toArray().length > 0);
99
+ }
100
+ updateLease(row) {
101
+ this.sql.exec(`UPDATE durability_semaphore_leases
102
+ SET permits = ?, released = ?, expires_at = ?, retired = ?
103
+ WHERE lease_id = ?`, row.permits, row.released, row.expires_at, row.retired, row.lease_id);
104
+ }
105
+ removeLease(leaseId) {
106
+ this.sql.exec('DELETE FROM durability_semaphore_leases WHERE lease_id = ?', leaseId);
107
+ }
108
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Experimental: this entry point may change or be removed in a minor
3
+ * release. Pin an exact version of `durability` when depending on it.
4
+ *
5
+ * @packageDocumentation
6
+ */
7
+ import { type TransformContext, type TransformStub } from '@durability/transforms';
8
+ import { type DurableObjectTarget } from './durable-object-target.js';
9
+ import { type PermitGrant, type PermitRequest, type PermitSync, type PermitSyncResult, type SemaphoreRequest, type SemaphoreResponse } from './semaphore-protocol.js';
10
+ import { DurabilitySemaphoreServer } from './semaphore-server.js';
11
+ export { SemaphoreProtocolError } from './errors.js';
12
+ export { durabilitySemaphoreMigrations, durabilitySemaphoreQueueMigrations, } from './migrations.js';
13
+ export type { GrantReport, GrantResult, PermitGrant, PermitRequest, PermitSync, PermitSyncResult, SemaphoreBlockedReason, SemaphoreRequest, SemaphoreResponse, } from './semaphore-protocol.js';
14
+ export type { SemaphoreAddress, SemaphoreClientConfig, } from './semaphore-client.js';
15
+ export { SemaphoreClient } from './semaphore-client.js';
16
+ export type { DurabilitySemaphoreConfig, DurabilitySemaphoreEvent, SemaphoreUsage, } from './semaphore-server.js';
17
+ export type { SemaphoreLeaseOptions, SemaphoreProvisioning, } from './semaphore-leases.js';
18
+ export { DurabilitySemaphoreQueue, type AdmittedItem, type DurabilitySemaphoreQueueConfig, type DurabilitySemaphoreQueueEvent, type SemaphoreHolder, type SemaphoreInput, type SemaphoreItemStatus, } from './semaphore-queue.js';
19
+ export type SemaphoreSession = {
20
+ request(key: string, message: PermitRequest): Promise<PermitGrant>;
21
+ sync(key: string, message: PermitSync): Promise<PermitSyncResult>;
22
+ setContext(context: TransformContext): {
23
+ invoke(method: string, args: unknown[]): Promise<unknown>;
24
+ };
25
+ };
26
+ export type DurabilitySemaphoreClientConfig<Target extends Rpc.DurableObjectBranded> = DurableObjectTarget<Target> & {
27
+ /** Chooses the application RPC method that forwards to `handle`; never hardcoded. */
28
+ invoke(stub: DurableObjectStub<Target>, message: SemaphoreRequest): Promise<SemaphoreResponse>;
29
+ locationHint?: (key: string) => DurableObjectLocationHint | undefined;
30
+ };
31
+ /**
32
+ * Inside a DO, holds one concurrency limit for many client Durable Objects.
33
+ * Outside the DO, `client()` routes semaphore messages to the application-owned
34
+ * holder class by key using ordinary @durability/transforms caller transforms.
35
+ */
36
+ export declare class DurabilitySemaphore extends DurabilitySemaphoreServer {
37
+ /**
38
+ * Routes semaphore messages to the application-owned holder class by key.
39
+ * Caller transforms such as `timeout` apply; transform context is not used.
40
+ */
41
+ static client<Target extends Rpc.DurableObjectBranded>(config: DurabilitySemaphoreClientConfig<Target>): TransformStub<SemaphoreSession>;
42
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Experimental: this entry point may change or be removed in a minor
3
+ * release. Pin an exact version of `durability` when depending on it.
4
+ *
5
+ * @packageDocumentation
6
+ */
7
+ import { createTransformStub, } from '@durability/transforms';
8
+ import { resolveNamespace, } from './durable-object-target.js';
9
+ import { SemaphoreProtocolError } from './errors.js';
10
+ import { SemaphoreClient } from './semaphore-client.js';
11
+ import { DurabilitySemaphoreServer } from './semaphore-server.js';
12
+ export { SemaphoreProtocolError } from './errors.js';
13
+ export { durabilitySemaphoreMigrations, durabilitySemaphoreQueueMigrations, } from './migrations.js';
14
+ export { SemaphoreClient } from './semaphore-client.js';
15
+ export { DurabilitySemaphoreQueue, } from './semaphore-queue.js';
16
+ /**
17
+ * Inside a DO, holds one concurrency limit for many client Durable Objects.
18
+ * Outside the DO, `client()` routes semaphore messages to the application-owned
19
+ * holder class by key using ordinary @durability/transforms caller transforms.
20
+ */
21
+ export class DurabilitySemaphore extends DurabilitySemaphoreServer {
22
+ /**
23
+ * Routes semaphore messages to the application-owned holder class by key.
24
+ * Caller transforms such as `timeout` apply; transform context is not used.
25
+ */
26
+ static client(config) {
27
+ const client = new SemaphoreClient({
28
+ invoke: (address, message) => {
29
+ const namespace = resolveNamespace(config, (text) => new SemaphoreProtocolError(text));
30
+ const stub = namespace.getByName(address.key, address.locationHint === undefined
31
+ ? undefined
32
+ : { locationHint: address.locationHint });
33
+ return config.invoke(stub, message);
34
+ },
35
+ ...(config.locationHint === undefined
36
+ ? {}
37
+ : { locationHint: config.locationHint }),
38
+ });
39
+ const session = {
40
+ request: (key, message) => client.request(key, message),
41
+ sync: (key, message) => client.sync(key, message),
42
+ setContext: () => ({
43
+ invoke: (method, args) => {
44
+ const key = args[0];
45
+ if (method === 'request') {
46
+ return client.request(key, args[1]);
47
+ }
48
+ if (method === 'sync') {
49
+ return client.sync(key, args[1]);
50
+ }
51
+ throw new SemaphoreProtocolError(`Unknown semaphore method "${method}"`);
52
+ },
53
+ }),
54
+ };
55
+ return createTransformStub(session);
56
+ }
57
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "durability",
3
- "version": "4.1.1",
3
+ "version": "4.2.0",
4
4
  "description": "Alarm-backed durable operations and typed WebSocket sync for Cloudflare Durable Objects",
5
5
  "type": "module",
6
6
  "license": "ISC",
@@ -31,6 +31,10 @@
31
31
  "types": "./dist/socket.d.ts",
32
32
  "import": "./dist/socket.js"
33
33
  },
34
+ "./experimental/semaphore": {
35
+ "types": "./dist/semaphore.d.ts",
36
+ "import": "./dist/semaphore.js"
37
+ },
34
38
  "./utils": {
35
39
  "types": "./dist/utils.d.ts",
36
40
  "import": "./dist/utils.js"
@@ -61,7 +65,7 @@
61
65
  "@standard-schema/spec": "^1.1.0",
62
66
  "zod": "^4.4.3",
63
67
  "@durability/storage": "^0.1.1",
64
- "@durability/transforms": "^0.4.0"
68
+ "@durability/transforms": "^0.5.0"
65
69
  },
66
70
  "peerDependencies": {
67
71
  "@cloudflare/workers-types": "^4.20260702.1"