@apifuse/provider-sdk 2.2.0-beta.1 → 2.2.0-beta.11

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.
Files changed (261) hide show
  1. package/AUTHORING.md +106 -0
  2. package/CHANGELOG.md +41 -0
  3. package/README.md +5 -1
  4. package/SUBMISSION.md +1 -1
  5. package/bin/apifuse-check.ts +44 -59
  6. package/bin/apifuse-create.ts +1 -1
  7. package/bin/apifuse-dev.ts +27 -52
  8. package/bin/apifuse-pack-check.ts +14 -0
  9. package/bin/apifuse-pack-smoke.ts +22 -81
  10. package/bin/apifuse-pack-types.ts +266 -0
  11. package/bin/apifuse-perf.ts +45 -127
  12. package/bin/apifuse-record.ts +53 -70
  13. package/bin/apifuse-submit-check.ts +510 -45
  14. package/bin/apifuse-sync-assets.ts +117 -0
  15. package/bin/apifuse.ts +1 -1
  16. package/bin/submit-check-delimited-text.ts +50 -0
  17. package/bin/submit-check-xml-semantics.ts +204 -0
  18. package/bin/submit-check-xml.ts +134 -0
  19. package/dist/auth-turn/index.d.ts +3 -3
  20. package/dist/auth.d.ts +2 -2
  21. package/dist/auth.js +9 -18
  22. package/dist/ceremonies/index.d.ts +1 -1
  23. package/dist/ceremonies/index.js +8 -18
  24. package/dist/cli/commands.d.ts +1 -1
  25. package/dist/cli/commands.js +8 -0
  26. package/dist/cli/create.d.ts +3 -0
  27. package/dist/cli/create.js +34 -35
  28. package/dist/cli/prompt-assets.d.ts +80 -0
  29. package/dist/cli/prompt-assets.js +743 -0
  30. package/dist/cli/templates/provider/AGENTS.md.tpl +17 -8
  31. package/dist/config/loader.d.ts +149 -8
  32. package/dist/config/loader.js +378 -89
  33. package/dist/contract-serialization.d.ts +2 -2
  34. package/dist/contract-serialization.js +3 -6
  35. package/dist/contract-types.d.ts +2 -2
  36. package/dist/contract.d.ts +3 -3
  37. package/dist/contract.js +4 -6
  38. package/dist/define.d.ts +8 -1
  39. package/dist/define.js +119 -122
  40. package/dist/dev.d.ts +1 -1
  41. package/dist/dev.js +1 -1
  42. package/dist/errors.d.ts +4 -1
  43. package/dist/errors.js +48 -0
  44. package/dist/i18n/catalog.d.ts +2 -2
  45. package/dist/i18n/catalog.js +4 -10
  46. package/dist/i18n/index.d.ts +2 -2
  47. package/dist/i18n/index.js +2 -2
  48. package/dist/i18n/keys.d.ts +2 -2
  49. package/dist/index.d.ts +44 -42
  50. package/dist/index.js +39 -37
  51. package/dist/lint.js +8 -15
  52. package/dist/provider.d.ts +11 -11
  53. package/dist/provider.js +9 -9
  54. package/dist/public-schema-field-lint.d.ts +1 -1
  55. package/dist/recipes/gov-api.js +1 -1
  56. package/dist/runtime/auth-flow.d.ts +1 -1
  57. package/dist/runtime/auth-flow.js +3 -3
  58. package/dist/runtime/browser.d.ts +1 -1
  59. package/dist/runtime/browser.js +15 -29
  60. package/dist/runtime/cache.d.ts +1 -1
  61. package/dist/runtime/cache.js +4 -8
  62. package/dist/runtime/choice.d.ts +1 -1
  63. package/dist/runtime/choice.js +31 -35
  64. package/dist/runtime/credential.d.ts +1 -1
  65. package/dist/runtime/credential.js +1 -1
  66. package/dist/runtime/env.d.ts +1 -1
  67. package/dist/runtime/executor.d.ts +1 -1
  68. package/dist/runtime/executor.js +15 -3
  69. package/dist/runtime/http.d.ts +2 -2
  70. package/dist/runtime/http.js +144 -348
  71. package/dist/runtime/insights.d.ts +1 -1
  72. package/dist/runtime/insights.js +6 -13
  73. package/dist/runtime/instrumentation.d.ts +2 -2
  74. package/dist/runtime/instrumentation.js +56 -19
  75. package/dist/runtime/keyring.js +1 -1
  76. package/dist/runtime/namespace.js +1 -1
  77. package/dist/runtime/otlp.d.ts +1 -1
  78. package/dist/runtime/perf.d.ts +1 -1
  79. package/dist/runtime/provider.d.ts +1 -1
  80. package/dist/runtime/provider.js +1 -2
  81. package/dist/runtime/proxy-errors.d.ts +1 -1
  82. package/dist/runtime/proxy-errors.js +9 -7
  83. package/dist/runtime/proxy-nodemaven.d.ts +35 -0
  84. package/dist/runtime/proxy-nodemaven.js +128 -0
  85. package/dist/runtime/proxy-retry-policy.d.ts +40 -0
  86. package/dist/runtime/proxy-retry-policy.js +326 -0
  87. package/dist/runtime/proxy-telemetry.d.ts +2 -1
  88. package/dist/runtime/proxy-telemetry.js +55 -52
  89. package/dist/runtime/redis.d.ts +1 -1
  90. package/dist/runtime/redis.js +2 -4
  91. package/dist/runtime/request-options.d.ts +1 -1
  92. package/dist/runtime/secrets.d.ts +27 -0
  93. package/dist/runtime/secrets.js +51 -0
  94. package/dist/runtime/state.d.ts +2 -2
  95. package/dist/runtime/state.js +15 -4
  96. package/dist/runtime/stealth.d.ts +2 -2
  97. package/dist/runtime/stealth.js +108 -212
  98. package/dist/runtime/stt.d.ts +1 -1
  99. package/dist/runtime/stt.js +11 -15
  100. package/dist/runtime/trace.d.ts +2 -2
  101. package/dist/runtime/trace.js +2 -4
  102. package/dist/runtime/waterfall.d.ts +1 -1
  103. package/dist/schema.d.ts +1 -1
  104. package/dist/schema.js +7 -15
  105. package/dist/serve.d.ts +1 -1
  106. package/dist/serve.js +1 -1
  107. package/dist/server/index.d.ts +7 -7
  108. package/dist/server/index.js +6 -6
  109. package/dist/server/self-test-redaction.d.ts +1 -1
  110. package/dist/server/self-test-redaction.js +1 -1
  111. package/dist/server/self-test.d.ts +104 -3
  112. package/dist/server/self-test.js +673 -115
  113. package/dist/server/serve.d.ts +105 -4
  114. package/dist/server/serve.js +588 -80
  115. package/dist/server/types.d.ts +10 -9
  116. package/dist/server/types.js +3 -7
  117. package/dist/stateful/errors.d.ts +14 -0
  118. package/dist/stateful/errors.js +14 -0
  119. package/dist/stateful/http-provider-event-emitter.d.ts +40 -0
  120. package/dist/stateful/http-provider-event-emitter.js +237 -0
  121. package/dist/stateful/http-session-owner-registry.d.ts +44 -0
  122. package/dist/stateful/http-session-owner-registry.js +210 -0
  123. package/dist/stateful/index.d.ts +18 -0
  124. package/dist/stateful/index.js +18 -0
  125. package/dist/stateful/provider-event-delivery-failures.d.ts +32 -0
  126. package/dist/stateful/provider-event-delivery-failures.js +43 -0
  127. package/dist/stateful/provider-event-pipeline-metrics.d.ts +46 -0
  128. package/dist/stateful/provider-event-pipeline-metrics.js +48 -0
  129. package/dist/stateful/provider-event-pipeline.d.ts +50 -0
  130. package/dist/stateful/provider-event-pipeline.js +1 -0
  131. package/dist/stateful/provider-events.d.ts +101 -0
  132. package/dist/stateful/provider-events.js +289 -0
  133. package/dist/stateful/session-key.d.ts +15 -0
  134. package/dist/stateful/session-key.js +86 -0
  135. package/dist/stateful/stateful-provider-adapter-context.d.ts +5 -0
  136. package/dist/stateful/stateful-provider-adapter-context.js +42 -0
  137. package/dist/stateful/stateful-provider-adapter-metrics.d.ts +15 -0
  138. package/dist/stateful/stateful-provider-adapter-metrics.js +21 -0
  139. package/dist/stateful/stateful-provider-adapter.d.ts +98 -0
  140. package/dist/stateful/stateful-provider-adapter.js +287 -0
  141. package/dist/stateful/stateful-provider-observability.d.ts +62 -0
  142. package/dist/stateful/stateful-provider-observability.js +161 -0
  143. package/dist/stateful/stateful-provider-owner-forwarder.d.ts +41 -0
  144. package/dist/stateful/stateful-provider-owner-forwarder.js +207 -0
  145. package/dist/stateful/stateful-provider-runtime-context.d.ts +32 -0
  146. package/dist/stateful/stateful-provider-runtime-context.js +60 -0
  147. package/dist/stateful/stateful-provider-runtime-executor.d.ts +34 -0
  148. package/dist/stateful/stateful-provider-runtime-executor.js +52 -0
  149. package/dist/stateful/stateful-provider-session-routing.d.ts +71 -0
  150. package/dist/stateful/stateful-provider-session-routing.js +353 -0
  151. package/dist/stateful/stateful-provider-session-runtime.d.ts +98 -0
  152. package/dist/stateful/stateful-provider-session-runtime.js +245 -0
  153. package/dist/stateful-signing.d.ts +18 -0
  154. package/dist/stateful-signing.js +27 -0
  155. package/dist/stealth/profiles.d.ts +1 -1
  156. package/dist/stealth/profiles.js +5 -14
  157. package/dist/stream.d.ts +1 -1
  158. package/dist/testing/index.d.ts +2 -2
  159. package/dist/testing/index.js +2 -2
  160. package/dist/testing/run.d.ts +1 -1
  161. package/dist/testing/run.js +7 -14
  162. package/dist/types.d.ts +87 -1
  163. package/dist/user-input.d.ts +30 -0
  164. package/dist/user-input.js +66 -0
  165. package/package.json +14 -5
  166. package/src/auth-turn/index.ts +1 -1
  167. package/src/auth.ts +28 -86
  168. package/src/ceremonies/index.ts +24 -78
  169. package/src/cli/commands.ts +10 -0
  170. package/src/cli/create.ts +42 -35
  171. package/src/cli/prompt-assets.ts +865 -0
  172. package/src/cli/templates/provider/AGENTS.md.tpl +17 -8
  173. package/src/config/loader.ts +543 -208
  174. package/src/contract-serialization.ts +5 -11
  175. package/src/contract-types.ts +2 -2
  176. package/src/contract.ts +12 -28
  177. package/src/define.ts +247 -505
  178. package/src/dev.ts +4 -9
  179. package/src/errors.ts +58 -5
  180. package/src/i18n/catalog.ts +10 -32
  181. package/src/i18n/index.ts +2 -2
  182. package/src/i18n/keys.ts +5 -11
  183. package/src/index.ts +49 -42
  184. package/src/lint.ts +89 -159
  185. package/src/provider.ts +15 -11
  186. package/src/public-schema-field-lint.ts +7 -33
  187. package/src/recipes/gov-api.ts +2 -5
  188. package/src/runtime/auth-flow.ts +5 -7
  189. package/src/runtime/browser.ts +64 -187
  190. package/src/runtime/cache.ts +20 -67
  191. package/src/runtime/choice.ts +79 -132
  192. package/src/runtime/credential.ts +2 -2
  193. package/src/runtime/env.ts +1 -1
  194. package/src/runtime/executor.ts +23 -20
  195. package/src/runtime/http.ts +195 -559
  196. package/src/runtime/insights.ts +15 -53
  197. package/src/runtime/instrumentation.ts +78 -65
  198. package/src/runtime/keyring.ts +7 -19
  199. package/src/runtime/namespace.ts +2 -7
  200. package/src/runtime/otlp.ts +12 -23
  201. package/src/runtime/perf.ts +1 -1
  202. package/src/runtime/provider.ts +4 -9
  203. package/src/runtime/proxy-errors.ts +29 -42
  204. package/src/runtime/proxy-nodemaven.ts +178 -0
  205. package/src/runtime/proxy-retry-policy.ts +469 -0
  206. package/src/runtime/proxy-telemetry.ts +79 -77
  207. package/src/runtime/redis.ts +4 -12
  208. package/src/runtime/request-options.ts +4 -13
  209. package/src/runtime/secrets.ts +64 -0
  210. package/src/runtime/state.ts +41 -110
  211. package/src/runtime/stealth.ts +162 -377
  212. package/src/runtime/stt.ts +38 -94
  213. package/src/runtime/trace.ts +14 -44
  214. package/src/runtime/waterfall.ts +5 -18
  215. package/src/schema.ts +23 -84
  216. package/src/serve.ts +1 -1
  217. package/src/server/index.ts +24 -7
  218. package/src/server/self-test-redaction.ts +2 -2
  219. package/src/server/self-test.ts +857 -132
  220. package/src/server/serve.ts +859 -266
  221. package/src/server/types.ts +7 -19
  222. package/src/stateful/README.md +146 -0
  223. package/src/stateful/errors.ts +23 -0
  224. package/src/stateful/http-provider-event-emitter.ts +314 -0
  225. package/src/stateful/http-session-owner-registry.ts +306 -0
  226. package/src/stateful/index.ts +18 -0
  227. package/src/stateful/provider-event-delivery-failures.ts +80 -0
  228. package/src/stateful/provider-event-pipeline-metrics.ts +95 -0
  229. package/src/stateful/provider-event-pipeline.ts +61 -0
  230. package/src/stateful/provider-events.ts +462 -0
  231. package/src/stateful/session-key.ts +111 -0
  232. package/src/stateful/stateful-provider-adapter-context.ts +59 -0
  233. package/src/stateful/stateful-provider-adapter-metrics.ts +48 -0
  234. package/src/stateful/stateful-provider-adapter.ts +562 -0
  235. package/src/stateful/stateful-provider-observability.ts +261 -0
  236. package/src/stateful/stateful-provider-owner-forwarder.ts +279 -0
  237. package/src/stateful/stateful-provider-runtime-context.ts +92 -0
  238. package/src/stateful/stateful-provider-runtime-executor.ts +96 -0
  239. package/src/stateful/stateful-provider-session-routing.ts +555 -0
  240. package/src/stateful/stateful-provider-session-runtime.ts +403 -0
  241. package/src/stateful-signing.ts +46 -0
  242. package/src/stealth/profiles.ts +10 -26
  243. package/src/stream.ts +8 -19
  244. package/src/testing/index.ts +2 -2
  245. package/src/testing/run.ts +19 -67
  246. package/src/types.ts +88 -1
  247. package/src/user-input.ts +118 -0
  248. package/dist/cli/templates/provider/CLAUDE.md.tpl +0 -1
  249. package/src/cli/templates/provider/CLAUDE.md.tpl +0 -1
  250. /package/dist/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
  251. /package/dist/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
  252. /package/dist/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
  253. /package/dist/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
  254. /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
  255. /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
  256. /package/src/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
  257. /package/src/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
  258. /package/src/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
  259. /package/src/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
  260. /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
  261. /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
@@ -1,15 +1,15 @@
1
1
  import { z } from "zod";
2
2
  export declare const ConnectionModeSchema: z.ZodEnum<{
3
- credentials: "credentials";
4
3
  none: "none";
4
+ credentials: "credentials";
5
5
  oauth2: "oauth2";
6
6
  "platform-managed": "platform-managed";
7
7
  }>;
8
8
  export declare const OperationConnectionSchema: z.ZodObject<{
9
9
  id: z.ZodString;
10
10
  mode: z.ZodEnum<{
11
- credentials: "credentials";
12
11
  none: "none";
12
+ credentials: "credentials";
13
13
  oauth2: "oauth2";
14
14
  "platform-managed": "platform-managed";
15
15
  }>;
@@ -21,11 +21,12 @@ export declare const OperationConnectionSchema: z.ZodObject<{
21
21
  export declare const OperationRequestSchema: z.ZodObject<{
22
22
  requestId: z.ZodString;
23
23
  input: z.ZodRecord<z.ZodString, z.ZodUnknown>;
24
+ connectionId: z.ZodOptional<z.ZodString>;
24
25
  connection: z.ZodOptional<z.ZodObject<{
25
26
  id: z.ZodString;
26
27
  mode: z.ZodEnum<{
27
- credentials: "credentials";
28
28
  none: "none";
29
+ credentials: "credentials";
29
30
  oauth2: "oauth2";
30
31
  "platform-managed": "platform-managed";
31
32
  }>;
@@ -54,21 +55,21 @@ export declare const OperationSuccessResponseSchema: z.ZodObject<{
54
55
  stale: z.ZodBoolean;
55
56
  keys: z.ZodArray<z.ZodString>;
56
57
  source: z.ZodOptional<z.ZodEnum<{
57
- loader: "loader";
58
- memory: "memory";
59
58
  mixed: "mixed";
60
59
  redis: "redis";
60
+ memory: "memory";
61
+ loader: "loader";
61
62
  }>>;
62
63
  }, z.core.$strip>>;
63
64
  retry: z.ZodOptional<z.ZodObject<{
64
65
  attempts: z.ZodNumber;
65
66
  retries: z.ZodNumber;
66
67
  preset: z.ZodOptional<z.ZodEnum<{
67
- aggressive_read: "aggressive_read";
68
68
  off: "off";
69
- rate_limit_aware: "rate_limit_aware";
70
- safe_read: "safe_read";
71
69
  transport_transient: "transport_transient";
70
+ safe_read: "safe_read";
71
+ aggressive_read: "aggressive_read";
72
+ rate_limit_aware: "rate_limit_aware";
72
73
  }>>;
73
74
  transport: z.ZodEnum<{
74
75
  native: "native";
@@ -100,8 +101,8 @@ export declare const AuthFlowRequestSchema: z.ZodObject<{
100
101
  connection: z.ZodOptional<z.ZodObject<{
101
102
  id: z.ZodString;
102
103
  mode: z.ZodEnum<{
103
- credentials: "credentials";
104
104
  none: "none";
105
+ credentials: "credentials";
105
106
  oauth2: "oauth2";
106
107
  "platform-managed": "platform-managed";
107
108
  }>;
@@ -1,11 +1,6 @@
1
1
  import { z } from "zod";
2
- import { HttpRetryPreset } from "../types";
3
- export const ConnectionModeSchema = z.enum([
4
- "oauth2",
5
- "credentials",
6
- "platform-managed",
7
- "none",
8
- ]);
2
+ import { HttpRetryPreset } from "../types.js";
3
+ export const ConnectionModeSchema = z.enum(["oauth2", "credentials", "platform-managed", "none"]);
9
4
  export const OperationConnectionSchema = z.object({
10
5
  id: z.string(),
11
6
  mode: ConnectionModeSchema,
@@ -17,6 +12,7 @@ export const OperationConnectionSchema = z.object({
17
12
  export const OperationRequestSchema = z.object({
18
13
  requestId: z.string(),
19
14
  input: z.record(z.string(), z.unknown()),
15
+ connectionId: z.string().optional(),
20
16
  connection: OperationConnectionSchema.optional(),
21
17
  headers: z.record(z.string(), z.string()).optional(),
22
18
  trace: z.record(z.string(), z.string()).optional(),
@@ -0,0 +1,14 @@
1
+ export type StatefulControlPlaneOperation = "resolve" | "acquire" | "renew" | "release";
2
+ export declare class StatefulControlPlaneError extends Error {
3
+ readonly code: string;
4
+ readonly operation: StatefulControlPlaneOperation;
5
+ readonly status?: number;
6
+ readonly cause?: unknown;
7
+ constructor(input: {
8
+ readonly code: string;
9
+ readonly message: string;
10
+ readonly operation: StatefulControlPlaneOperation;
11
+ readonly status?: number;
12
+ readonly cause?: unknown;
13
+ });
14
+ }
@@ -0,0 +1,14 @@
1
+ export class StatefulControlPlaneError extends Error {
2
+ code;
3
+ operation;
4
+ status;
5
+ cause;
6
+ constructor(input) {
7
+ super(input.message);
8
+ this.name = "StatefulControlPlaneError";
9
+ this.code = input.code;
10
+ this.operation = input.operation;
11
+ this.status = input.status;
12
+ this.cause = input.cause;
13
+ }
14
+ }
@@ -0,0 +1,40 @@
1
+ import type { ProviderEventDeliveryFailureRecorder } from "./provider-event-delivery-failures.js";
2
+ import type { ProviderEventPublisher, ProviderEventPublishOptions, PublishAck } from "./provider-event-pipeline.js";
3
+ import { type ProviderEventMetricEmitter } from "./provider-event-pipeline-metrics.js";
4
+ import type { ProviderEvent } from "./provider-events.js";
5
+ type FetchTransport = (url: string | URL | Request, init?: RequestInit) => Promise<Response>;
6
+ export type HttpProviderEventEmitterOptions = {
7
+ readonly baseUrl: string;
8
+ readonly secret: string;
9
+ readonly fetch?: FetchTransport;
10
+ readonly clock?: () => Date;
11
+ readonly random?: () => number;
12
+ readonly metricEmitter?: ProviderEventMetricEmitter;
13
+ readonly failureRecorder?: ProviderEventDeliveryFailureRecorder;
14
+ readonly maxBufferedEvents?: number;
15
+ readonly retryBaseMs?: number;
16
+ readonly retryMaxMs?: number;
17
+ readonly maxAttempts?: number;
18
+ readonly jitterRatio?: number;
19
+ };
20
+ export type ProviderEventFlushReport = {
21
+ /** Events delivered during this emitter's lifetime. */
22
+ readonly delivered: number;
23
+ /** Events permanently dropped during this emitter's lifetime. */
24
+ readonly failed: number;
25
+ /** Events still buffered when flush returned. */
26
+ readonly pending: number;
27
+ };
28
+ /**
29
+ * Provider-pod HTTP publication with a bounded best-effort delivery guarantee and at-least-once
30
+ * transport retries. This is not durable at-least-once delivery: buffered events can be lost if
31
+ * the process is killed. Graceful shutdown should drain the in-memory buffer with flush().
32
+ */
33
+ export declare class HttpProviderEventEmitter implements ProviderEventPublisher {
34
+ #private;
35
+ constructor(options: HttpProviderEventEmitterOptions);
36
+ publish(event: ProviderEvent, options: ProviderEventPublishOptions): PublishAck;
37
+ pendingCount(): number;
38
+ flush(timeoutMs?: number): Promise<ProviderEventFlushReport>;
39
+ }
40
+ export {};
@@ -0,0 +1,237 @@
1
+ import { statefulSignedHeaders } from "../stateful-signing.js";
2
+ import { NOOP_PROVIDER_EVENT_METRIC_EMITTER, providerEventMetricLabels, } from "./provider-event-pipeline-metrics.js";
3
+ const DEFAULT_MAX_BUFFERED_EVENTS = 1_000;
4
+ const DEFAULT_RETRY_BASE_MS = 500;
5
+ const DEFAULT_RETRY_MAX_MS = 30_000;
6
+ const DEFAULT_MAX_ATTEMPTS = 10;
7
+ const DEFAULT_JITTER_RATIO = 0.2;
8
+ const CONSOLE_PROVIDER_EVENT_DELIVERY_FAILURE_RECORDER = {
9
+ record(failure) {
10
+ console.error(JSON.stringify({
11
+ event: "provider_event_delivery_failed",
12
+ eventId: failure.eventId,
13
+ reason: failure.reason,
14
+ attempts: failure.attempts,
15
+ }));
16
+ },
17
+ };
18
+ /**
19
+ * Provider-pod HTTP publication with a bounded best-effort delivery guarantee and at-least-once
20
+ * transport retries. This is not durable at-least-once delivery: buffered events can be lost if
21
+ * the process is killed. Graceful shutdown should drain the in-memory buffer with flush().
22
+ */
23
+ export class HttpProviderEventEmitter {
24
+ #baseUrl;
25
+ #secret;
26
+ #fetch;
27
+ #clock;
28
+ #random;
29
+ #metricEmitter;
30
+ #failureRecorder;
31
+ #maxBufferedEvents;
32
+ #retryBaseMs;
33
+ #retryMaxMs;
34
+ #maxAttempts;
35
+ #jitterRatio;
36
+ #queue = [];
37
+ #drainPromise;
38
+ #deliveredCount = 0;
39
+ #failedCount = 0;
40
+ constructor(options) {
41
+ if (options.baseUrl.trim().length === 0) {
42
+ throw new Error("Provider event ingest baseUrl is required.");
43
+ }
44
+ if (options.secret.trim().length === 0) {
45
+ throw new Error("Provider event ingest secret is required.");
46
+ }
47
+ this.#baseUrl = options.baseUrl.replace(/\/+$/, "");
48
+ this.#secret = options.secret;
49
+ this.#fetch = options.fetch ?? globalThis.fetch;
50
+ this.#clock = options.clock ?? (() => new Date());
51
+ this.#random = options.random ?? Math.random;
52
+ this.#metricEmitter = options.metricEmitter ?? NOOP_PROVIDER_EVENT_METRIC_EMITTER;
53
+ this.#failureRecorder =
54
+ options.failureRecorder ?? CONSOLE_PROVIDER_EVENT_DELIVERY_FAILURE_RECORDER;
55
+ this.#maxBufferedEvents = positiveInteger(options.maxBufferedEvents ?? DEFAULT_MAX_BUFFERED_EVENTS, "maxBufferedEvents");
56
+ this.#retryBaseMs = nonnegativeFinite(options.retryBaseMs ?? DEFAULT_RETRY_BASE_MS, "retryBaseMs");
57
+ this.#retryMaxMs = nonnegativeFinite(options.retryMaxMs ?? DEFAULT_RETRY_MAX_MS, "retryMaxMs");
58
+ this.#maxAttempts = positiveInteger(options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS, "maxAttempts");
59
+ this.#jitterRatio = boundedRatio(options.jitterRatio ?? DEFAULT_JITTER_RATIO, "jitterRatio");
60
+ if (this.#retryMaxMs < this.#retryBaseMs) {
61
+ throw new Error("Provider event retryMaxMs must be greater than or equal to retryBaseMs.");
62
+ }
63
+ }
64
+ publish(event, options) {
65
+ const accepted = this.#enqueue(event, options);
66
+ return { accepted, queued: this.#queue.length };
67
+ }
68
+ pendingCount() {
69
+ return this.#queue.length;
70
+ }
71
+ async flush(timeoutMs = 30_000) {
72
+ nonnegativeFinite(timeoutMs, "flush timeout");
73
+ this.#ensureDrain();
74
+ if (this.#queue.length === 0 || timeoutMs === 0)
75
+ return this.#flushReport();
76
+ let timeout;
77
+ const timedOut = new Promise((resolve) => {
78
+ timeout = setTimeout(resolve, timeoutMs);
79
+ });
80
+ await Promise.race([this.#drainPromise ?? Promise.resolve(), timedOut]);
81
+ if (timeout)
82
+ clearTimeout(timeout);
83
+ return this.#flushReport();
84
+ }
85
+ #flushReport() {
86
+ return {
87
+ delivered: this.#deliveredCount,
88
+ failed: this.#failedCount,
89
+ pending: this.#queue.length,
90
+ };
91
+ }
92
+ #enqueue(event, options) {
93
+ let rawBody;
94
+ try {
95
+ rawBody = JSON.stringify({
96
+ ...event,
97
+ ownerFence: options.ownerFence,
98
+ });
99
+ }
100
+ catch (error) {
101
+ this.#recordFailure(event, "attempts_exhausted", 0, error);
102
+ return false;
103
+ }
104
+ if (this.#queue.length >= this.#maxBufferedEvents) {
105
+ const oldest = this.#queue.shift();
106
+ if (oldest) {
107
+ oldest.dropped = true;
108
+ oldest.abortController?.abort();
109
+ this.#recordFailure(oldest.event, "buffer_overflow", oldest.attempts);
110
+ }
111
+ }
112
+ this.#queue.push({
113
+ event,
114
+ rawBody,
115
+ idempotencyKey: options.idempotencyKey ?? event.eventId,
116
+ attempts: 0,
117
+ dropped: false,
118
+ });
119
+ this.#ensureDrain();
120
+ return true;
121
+ }
122
+ #ensureDrain() {
123
+ if (this.#drainPromise || this.#queue.length === 0)
124
+ return;
125
+ this.#drainPromise = Promise.resolve()
126
+ .then(() => this.#drain())
127
+ .finally(() => {
128
+ this.#drainPromise = undefined;
129
+ if (this.#queue.length > 0)
130
+ this.#ensureDrain();
131
+ });
132
+ }
133
+ async #drain() {
134
+ while (this.#queue.length > 0) {
135
+ const current = this.#queue[0];
136
+ if (!current)
137
+ return;
138
+ current.attempts += 1;
139
+ const delivered = await this.#send(current);
140
+ if (current.dropped)
141
+ continue;
142
+ if (delivered) {
143
+ if (this.#queue[0] === current)
144
+ this.#queue.shift();
145
+ this.#deliveredCount += 1;
146
+ continue;
147
+ }
148
+ if (current.attempts >= this.#maxAttempts) {
149
+ if (this.#queue[0] === current)
150
+ this.#queue.shift();
151
+ this.#recordFailure(current.event, "attempts_exhausted", current.attempts);
152
+ continue;
153
+ }
154
+ await delay(this.#retryDelay(current.attempts));
155
+ }
156
+ }
157
+ async #send(buffered) {
158
+ const timestamp = this.#clock().toISOString();
159
+ const path = "/v1/stateful/events";
160
+ const abortController = new AbortController();
161
+ buffered.abortController = abortController;
162
+ try {
163
+ const response = await this.#fetch(`${this.#baseUrl}${path}`, {
164
+ method: "POST",
165
+ headers: {
166
+ "content-type": "application/json",
167
+ "x-apifuse-event-id": buffered.idempotencyKey,
168
+ ...statefulSignedHeaders({
169
+ secret: this.#secret,
170
+ timestamp,
171
+ rawBody: buffered.rawBody,
172
+ method: "POST",
173
+ path,
174
+ }),
175
+ },
176
+ body: buffered.rawBody,
177
+ signal: abortController.signal,
178
+ });
179
+ return response.ok;
180
+ }
181
+ catch {
182
+ return false;
183
+ }
184
+ finally {
185
+ if (buffered.abortController === abortController) {
186
+ buffered.abortController = undefined;
187
+ }
188
+ }
189
+ }
190
+ #retryDelay(attempts) {
191
+ const exponential = Math.min(this.#retryMaxMs, this.#retryBaseMs * 2 ** Math.max(0, attempts - 1));
192
+ const jitter = 1 + (this.#random() * 2 - 1) * this.#jitterRatio;
193
+ return Math.max(0, Math.round(exponential * jitter));
194
+ }
195
+ #recordFailure(event, reason, attempts, error) {
196
+ this.#failedCount += 1;
197
+ this.#incrementDropMetric(event);
198
+ try {
199
+ const recorded = this.#failureRecorder.record({
200
+ eventId: event.eventId,
201
+ reason,
202
+ attempts,
203
+ failedAt: this.#clock().toISOString(),
204
+ ...(error ? { error: "Provider event could not be serialized." } : {}),
205
+ });
206
+ void Promise.resolve(recorded).catch(() => { });
207
+ }
208
+ catch { }
209
+ }
210
+ #incrementDropMetric(event, emitter = this.#metricEmitter) {
211
+ try {
212
+ emitter.increment("apifuse_stateful_provider_event_drop_total", providerEventMetricLabels(event));
213
+ }
214
+ catch { }
215
+ }
216
+ }
217
+ function delay(ms) {
218
+ return new Promise((resolve) => setTimeout(resolve, ms));
219
+ }
220
+ function positiveInteger(value, name) {
221
+ if (!Number.isInteger(value) || value <= 0) {
222
+ throw new Error(`Provider event ${name} must be a positive integer.`);
223
+ }
224
+ return value;
225
+ }
226
+ function nonnegativeFinite(value, name) {
227
+ if (!Number.isFinite(value) || value < 0) {
228
+ throw new Error(`Provider event ${name} must be a non-negative finite number.`);
229
+ }
230
+ return value;
231
+ }
232
+ function boundedRatio(value, name) {
233
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
234
+ throw new Error(`Provider event ${name} must be between 0 and 1.`);
235
+ }
236
+ return value;
237
+ }
@@ -0,0 +1,44 @@
1
+ import { StatefulControlPlaneError, type StatefulControlPlaneOperation } from "./errors.js";
2
+ import { type SessionKey } from "./session-key.js";
3
+ import type { AcquireSessionOwnerInput, AcquireSessionOwnerResult, ReleaseSessionOwnerInput, RenewSessionOwnerInput, SessionOwnerRecord, SessionOwnerRegistry } from "./stateful-provider-session-runtime.js";
4
+ type FetchTransport = (url: string | URL | Request, init?: RequestInit) => Promise<Response>;
5
+ export type SessionOwnerScope = {
6
+ readonly serviceAccountId: string;
7
+ readonly providerId: string;
8
+ readonly connectionId?: string;
9
+ };
10
+ export type HttpSessionOwnerRegistryOptions = {
11
+ readonly baseUrl: string;
12
+ readonly secret: string;
13
+ readonly scope?: SessionOwnerScope;
14
+ readonly fetch?: FetchTransport;
15
+ readonly clock?: () => Date;
16
+ readonly requestTimeoutMs?: number;
17
+ };
18
+ /**
19
+ * A mutating registry request failed after it may have reached the control plane. Callers must
20
+ * resolve the session owner and reconcile instead of blindly retrying the mutation.
21
+ */
22
+ export declare class AmbiguousRegistryOperationError extends StatefulControlPlaneError {
23
+ readonly ambiguous = true;
24
+ constructor(input: {
25
+ readonly operation: Exclude<StatefulControlPlaneOperation, "resolve">;
26
+ readonly message: string;
27
+ readonly cause: unknown;
28
+ });
29
+ }
30
+ export type HttpSessionOwnerRecord = Omit<SessionOwnerRecord, "sessionKey"> & {
31
+ readonly sessionKey: SessionKey;
32
+ };
33
+ export type HttpAcquireSessionOwnerResult = Omit<AcquireSessionOwnerResult, "record"> & {
34
+ readonly record: HttpSessionOwnerRecord;
35
+ };
36
+ export declare class HttpSessionOwnerRegistry implements SessionOwnerRegistry {
37
+ #private;
38
+ constructor(options: HttpSessionOwnerRegistryOptions);
39
+ resolve(sessionKey: SessionKey, now?: Date, signal?: AbortSignal): Promise<HttpSessionOwnerRecord | null>;
40
+ acquire(input: AcquireSessionOwnerInput, signal?: AbortSignal): Promise<HttpAcquireSessionOwnerResult>;
41
+ renew(input: RenewSessionOwnerInput, signal?: AbortSignal): Promise<HttpSessionOwnerRecord | null>;
42
+ release(input: ReleaseSessionOwnerInput, signal?: AbortSignal): Promise<boolean>;
43
+ }
44
+ export {};
@@ -0,0 +1,210 @@
1
+ import { z } from "zod";
2
+ import { statefulSignedHeaders } from "../stateful-signing.js";
3
+ import { StatefulControlPlaneError } from "./errors.js";
4
+ import { parseSessionKey } from "./session-key.js";
5
+ const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
6
+ /**
7
+ * A mutating registry request failed after it may have reached the control plane. Callers must
8
+ * resolve the session owner and reconcile instead of blindly retrying the mutation.
9
+ */
10
+ export class AmbiguousRegistryOperationError extends StatefulControlPlaneError {
11
+ ambiguous = true;
12
+ constructor(input) {
13
+ super({
14
+ code: "STATEFUL_CONTROL_PLANE_OPERATION_AMBIGUOUS",
15
+ message: input.message,
16
+ operation: input.operation,
17
+ cause: input.cause,
18
+ });
19
+ this.name = "AmbiguousRegistryOperationError";
20
+ }
21
+ }
22
+ const SessionKeySchema = z
23
+ .string()
24
+ .min(1)
25
+ .transform((value, context) => {
26
+ try {
27
+ parseSessionKey(value);
28
+ return value;
29
+ }
30
+ catch (error) {
31
+ context.addIssue({
32
+ code: "custom",
33
+ message: error instanceof Error ? error.message : "Invalid canonical session key.",
34
+ });
35
+ return z.NEVER;
36
+ }
37
+ });
38
+ const OwnerRecordSchema = z.object({
39
+ sessionKey: SessionKeySchema,
40
+ ownerPodId: z.string().min(1),
41
+ ownerEndpoint: z.string().min(1),
42
+ generation: z.number().int().positive(),
43
+ leaseExpiresAt: z.string().refine(isTimestamp),
44
+ status: z.enum(["acquiring", "connected", "draining", "expired"]),
45
+ lastUsedAt: z.string().refine(isTimestamp),
46
+ });
47
+ const AcquireResultSchema = z.object({
48
+ record: OwnerRecordSchema,
49
+ acquired: z.boolean(),
50
+ });
51
+ const ResolveResponseSchema = z.union([
52
+ OwnerRecordSchema,
53
+ z.object({ record: OwnerRecordSchema }).transform((value) => value.record),
54
+ z.object({ data: OwnerRecordSchema }).transform((value) => value.data),
55
+ ]);
56
+ const AcquireResponseSchema = z.union([
57
+ AcquireResultSchema,
58
+ z.object({ data: AcquireResultSchema }).transform((value) => value.data),
59
+ ]);
60
+ const RenewResponseSchema = z.union([
61
+ OwnerRecordSchema.nullable(),
62
+ z.object({ record: OwnerRecordSchema.nullable() }).transform((value) => value.record),
63
+ z.object({ data: OwnerRecordSchema.nullable() }).transform((value) => value.data),
64
+ ]);
65
+ const ReleaseResponseSchema = z.union([
66
+ z.boolean(),
67
+ z.object({ released: z.boolean() }).transform((value) => value.released),
68
+ z.object({ data: z.boolean() }).transform((value) => value.data),
69
+ ]);
70
+ export class HttpSessionOwnerRegistry {
71
+ #baseUrl;
72
+ #secret;
73
+ #scope;
74
+ #fetch;
75
+ #clock;
76
+ #requestTimeoutMs;
77
+ constructor(options) {
78
+ if (options.baseUrl.trim().length === 0) {
79
+ throw new Error("Stateful control-plane baseUrl is required.");
80
+ }
81
+ if (options.secret.trim().length === 0) {
82
+ throw new Error("Stateful control-plane secret is required.");
83
+ }
84
+ this.#baseUrl = options.baseUrl.replace(/\/+$/, "");
85
+ this.#secret = options.secret;
86
+ this.#scope = options.scope;
87
+ this.#fetch = options.fetch ?? globalThis.fetch;
88
+ this.#clock = options.clock ?? (() => new Date());
89
+ this.#requestTimeoutMs = positiveInteger(options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS, "requestTimeoutMs");
90
+ }
91
+ async resolve(sessionKey, now, signal) {
92
+ const response = await this.#post("resolve", {
93
+ ...this.#scope,
94
+ sessionKey,
95
+ ...(now ? { now: now.toISOString() } : {}),
96
+ }, signal);
97
+ if (response.status === 404)
98
+ return null;
99
+ return this.#parse(response, "resolve", ResolveResponseSchema);
100
+ }
101
+ async acquire(input, signal) {
102
+ const response = await this.#post("acquire", {
103
+ ...this.#scope,
104
+ ...input,
105
+ ...(input.now ? { now: input.now.toISOString() } : {}),
106
+ }, signal);
107
+ return this.#parse(response, "acquire", AcquireResponseSchema);
108
+ }
109
+ async renew(input, signal) {
110
+ const response = await this.#post("renew", {
111
+ ...this.#scope,
112
+ ...input,
113
+ ...(input.now ? { now: input.now.toISOString() } : {}),
114
+ }, signal);
115
+ return this.#parse(response, "renew", RenewResponseSchema);
116
+ }
117
+ async release(input, signal) {
118
+ const response = await this.#post("release", {
119
+ ...this.#scope,
120
+ ...input,
121
+ }, signal);
122
+ return this.#parse(response, "release", ReleaseResponseSchema);
123
+ }
124
+ async #post(operation, body, callerSignal) {
125
+ callerSignal?.throwIfAborted();
126
+ const rawBody = JSON.stringify(body);
127
+ const timestamp = this.#clock().toISOString();
128
+ const path = `/v1/stateful/sessions/owners/${operation}`;
129
+ const timeoutSignal = AbortSignal.timeout(this.#requestTimeoutMs);
130
+ const signal = AbortSignal.any(callerSignal ? [callerSignal, timeoutSignal] : [timeoutSignal]);
131
+ try {
132
+ return await this.#fetch(`${this.#baseUrl}${path}`, {
133
+ method: "POST",
134
+ headers: {
135
+ "content-type": "application/json",
136
+ ...statefulSignedHeaders({
137
+ secret: this.#secret,
138
+ timestamp,
139
+ rawBody,
140
+ method: "POST",
141
+ path,
142
+ }),
143
+ },
144
+ body: rawBody,
145
+ signal,
146
+ });
147
+ }
148
+ catch (cause) {
149
+ const timedOut = timeoutSignal.aborted && !callerSignal?.aborted;
150
+ if (operation !== "resolve") {
151
+ throw new AmbiguousRegistryOperationError({
152
+ operation,
153
+ message: timedOut
154
+ ? `Stateful control-plane ${operation} timed out after ${this.#requestTimeoutMs}ms; resolve the session owner and reconcile before retrying.`
155
+ : `Stateful control-plane ${operation} request failed after it may have committed; resolve the session owner and reconcile before retrying.`,
156
+ cause,
157
+ });
158
+ }
159
+ throw new StatefulControlPlaneError({
160
+ code: "STATEFUL_CONTROL_PLANE_REQUEST_FAILED",
161
+ message: timedOut
162
+ ? `Stateful control-plane resolve timed out after ${this.#requestTimeoutMs}ms; retry resolve or check control-plane availability.`
163
+ : "Stateful control-plane resolve request failed.",
164
+ operation,
165
+ cause,
166
+ });
167
+ }
168
+ }
169
+ async #parse(response, operation, schema) {
170
+ if (!response.ok) {
171
+ throw new StatefulControlPlaneError({
172
+ code: "STATEFUL_CONTROL_PLANE_HTTP_ERROR",
173
+ message: `Stateful control-plane ${operation} returned status ${response.status}.`,
174
+ operation,
175
+ status: response.status,
176
+ });
177
+ }
178
+ const rawBody = await response.text();
179
+ let body;
180
+ try {
181
+ body = JSON.parse(rawBody);
182
+ }
183
+ catch (cause) {
184
+ throw invalidResponse(operation, response.status, cause);
185
+ }
186
+ const parsed = schema.safeParse(body);
187
+ if (!parsed.success) {
188
+ throw invalidResponse(operation, response.status, parsed.error);
189
+ }
190
+ return parsed.data;
191
+ }
192
+ }
193
+ function invalidResponse(operation, status, cause) {
194
+ return new StatefulControlPlaneError({
195
+ code: "STATEFUL_CONTROL_PLANE_INVALID_RESPONSE",
196
+ message: `Stateful control-plane ${operation} returned an invalid response.`,
197
+ operation,
198
+ status,
199
+ cause,
200
+ });
201
+ }
202
+ function isTimestamp(value) {
203
+ return Number.isFinite(Date.parse(value));
204
+ }
205
+ function positiveInteger(value, name) {
206
+ if (!Number.isInteger(value) || value <= 0) {
207
+ throw new Error(`Stateful control-plane ${name} must be a positive integer.`);
208
+ }
209
+ return value;
210
+ }
@@ -0,0 +1,18 @@
1
+ export * from "../stateful-signing.js";
2
+ export * from "./errors.js";
3
+ export * from "./http-provider-event-emitter.js";
4
+ export * from "./http-session-owner-registry.js";
5
+ export * from "./provider-event-delivery-failures.js";
6
+ export * from "./provider-event-pipeline-metrics.js";
7
+ export * from "./provider-event-pipeline.js";
8
+ export * from "./provider-events.js";
9
+ export * from "./session-key.js";
10
+ export * from "./stateful-provider-adapter-context.js";
11
+ export * from "./stateful-provider-adapter-metrics.js";
12
+ export * from "./stateful-provider-adapter.js";
13
+ export * from "./stateful-provider-observability.js";
14
+ export * from "./stateful-provider-owner-forwarder.js";
15
+ export * from "./stateful-provider-runtime-context.js";
16
+ export * from "./stateful-provider-runtime-executor.js";
17
+ export * from "./stateful-provider-session-routing.js";
18
+ export * from "./stateful-provider-session-runtime.js";