@useairfoil/connector-kit 0.4.0 → 0.5.1

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 (117) hide show
  1. package/METRICS.md +78 -0
  2. package/README.md +450 -88
  3. package/dist/auth/index.d.ts +2 -0
  4. package/dist/auth/index.js +3 -0
  5. package/dist/auth-DvU_CZ7C.js +42 -0
  6. package/dist/auth-DvU_CZ7C.js.map +1 -0
  7. package/dist/chunk-Bp6m_JJh.js +13 -0
  8. package/dist/connector-app/index.d.ts +14 -0
  9. package/dist/connector-app/index.js +11 -0
  10. package/dist/connector-app-d7Z-SZLQ.js +64 -0
  11. package/dist/connector-app-d7Z-SZLQ.js.map +1 -0
  12. package/dist/constants-BRhIX_rz.js +27 -0
  13. package/dist/constants-BRhIX_rz.js.map +1 -0
  14. package/dist/errors/index.d.ts +2 -0
  15. package/dist/errors/index.js +3 -0
  16. package/dist/errors-DHWylqRZ.js +8 -0
  17. package/dist/errors-DHWylqRZ.js.map +1 -0
  18. package/dist/index-Byr0Lf0C.d.ts +25 -0
  19. package/dist/index-CBT-JX-T.d.ts +173 -0
  20. package/dist/index-CTHVudvQ.d.ts +41 -0
  21. package/dist/index-CTLYQ74P.d.ts +80 -0
  22. package/dist/index-Coh_SkBs.d.ts +95 -0
  23. package/dist/index-D54ySAKn.d.ts +14 -0
  24. package/dist/index-DtJX_tic.d.ts +153 -0
  25. package/dist/index-J42AZaXU.d.ts +38 -0
  26. package/dist/index-fIIBVAai.d.ts +25 -0
  27. package/dist/index-o1-Z3n7V.d.ts +55 -0
  28. package/dist/index.d.ts +14 -165
  29. package/dist/index.js +50 -228
  30. package/dist/index.js.map +1 -1
  31. package/dist/ingestion/index.d.ts +6 -0
  32. package/dist/ingestion/index.js +10 -0
  33. package/dist/ingestion-BQo4cbGw.js +200 -0
  34. package/dist/ingestion-BQo4cbGw.js.map +1 -0
  35. package/dist/manifest/index.d.ts +2 -0
  36. package/dist/manifest/index.js +4 -0
  37. package/dist/manifest-ByE6YPG0.js +221 -0
  38. package/dist/manifest-ByE6YPG0.js.map +1 -0
  39. package/dist/metrics-CVAk1ALR.d.ts +53 -0
  40. package/dist/metrics-CWPy2Aqc.js +96 -0
  41. package/dist/metrics-CWPy2Aqc.js.map +1 -0
  42. package/dist/metrics.d.ts +4 -0
  43. package/dist/metrics.js +3 -0
  44. package/dist/publisher/index.d.ts +5 -0
  45. package/dist/publisher/index.js +6 -0
  46. package/dist/publisher-BYT3RLVO.js +131 -0
  47. package/dist/publisher-BYT3RLVO.js.map +1 -0
  48. package/dist/runtime-config/index.d.ts +2 -0
  49. package/dist/runtime-config/index.js +4 -0
  50. package/dist/runtime-config-BpB-d_bF.js +51 -0
  51. package/dist/runtime-config-BpB-d_bF.js.map +1 -0
  52. package/dist/server-CXTQ7odl.js +183 -0
  53. package/dist/server-CXTQ7odl.js.map +1 -0
  54. package/dist/service-DuFiQwid.js +191 -0
  55. package/dist/service-DuFiQwid.js.map +1 -0
  56. package/dist/service-IE5qaf9x.d.ts +32 -0
  57. package/dist/state-store/index.d.ts +3 -0
  58. package/dist/state-store/index.js +5 -0
  59. package/dist/state-store-yl6LiTQ0.js +198 -0
  60. package/dist/state-store-yl6LiTQ0.js.map +1 -0
  61. package/dist/status/index.d.ts +5 -0
  62. package/dist/status/index.js +6 -0
  63. package/dist/status-B-oZBc33.js +84 -0
  64. package/dist/status-B-oZBc33.js.map +1 -0
  65. package/dist/types-B35J5YPu.d.ts +174 -0
  66. package/dist/webhook/index.d.ts +6 -0
  67. package/dist/webhook/index.js +8 -0
  68. package/dist/webhook-DI-Afxkg.js +13 -0
  69. package/dist/webhook-DI-Afxkg.js.map +1 -0
  70. package/package.json +66 -8
  71. package/src/auth/index.ts +1 -0
  72. package/src/auth/token-cache.ts +54 -0
  73. package/src/connector-app/check.ts +76 -0
  74. package/src/connector-app/index.ts +2 -0
  75. package/src/connector-app/start.ts +42 -0
  76. package/src/core/builder.ts +81 -9
  77. package/src/core/index.ts +22 -0
  78. package/src/core/types.ts +204 -76
  79. package/src/errors/index.ts +1 -0
  80. package/src/index.ts +13 -28
  81. package/src/ingestion/engine.ts +409 -174
  82. package/src/ingestion/index.ts +1 -0
  83. package/src/manifest/config.ts +232 -0
  84. package/src/manifest/index.ts +14 -0
  85. package/src/manifest/manifest.ts +31 -0
  86. package/src/manifest/number-schema.ts +17 -0
  87. package/src/manifest/schema.ts +160 -0
  88. package/src/metrics.ts +128 -0
  89. package/src/publisher/console.ts +18 -0
  90. package/src/publisher/index.ts +7 -0
  91. package/src/publisher/instrumented.ts +68 -0
  92. package/src/publisher/service.ts +30 -13
  93. package/src/publisher/wings.ts +159 -72
  94. package/src/runtime/context.ts +15 -0
  95. package/src/runtime-config/constants.ts +27 -0
  96. package/src/runtime-config/error.ts +13 -0
  97. package/src/runtime-config/index.ts +3 -0
  98. package/src/runtime-config/layer.ts +56 -0
  99. package/src/state-store/index.ts +3 -0
  100. package/src/state-store/keys.ts +22 -0
  101. package/src/state-store/layer-key-value-store.ts +132 -0
  102. package/src/state-store/layer-memory.ts +11 -0
  103. package/src/state-store/layer-sql.ts +50 -0
  104. package/src/state-store/schema.ts +57 -0
  105. package/src/state-store/service.ts +51 -0
  106. package/src/state-store/state.ts +17 -0
  107. package/src/status/index.ts +2 -0
  108. package/src/status/route.ts +77 -0
  109. package/src/status/types.ts +33 -0
  110. package/src/telemetry.ts +288 -0
  111. package/src/webhook/index.ts +8 -0
  112. package/src/webhook/server.ts +209 -39
  113. package/src/webhook/types.ts +6 -17
  114. package/src/ingestion/state-store.ts +0 -36
  115. package/src/streams/pull-stream.ts +0 -54
  116. package/src/streams/webhook-queue.ts +0 -14
  117. /package/src/{core/errors.ts → errors/connector-error.ts} +0 -0
package/METRICS.md ADDED
@@ -0,0 +1,78 @@
1
+ # Connector Metrics And Status
2
+
3
+ Connector Kit emits standard metrics through Effect metrics. Production runtimes should use `Telemetry.layerOtlp()` with `OTEL_ENABLED=true`, `OTEL_EXPORTER_OTLP_ENDPOINT`, and optional `OTEL_EXPORTER_OTLP_HEADERS`. HTTP runtimes expose shallow process health at `GET /health`, Prometheus text at `GET /metrics`, and durable sync state at `GET /status`. Sandboxes can also merge `Telemetry.layerMetricsConsoleDump()` for periodic log output.
4
+
5
+ ## Metrics
6
+
7
+ | Name | Type | Unit | Attributes |
8
+ | -------------------------------------------------- | --------------- | --------------- | -------------------------------------------- |
9
+ | `airfoil_connector_entities_upserted_total` | counter | mutations | `connector`, `resource`, `source` |
10
+ | `airfoil_connector_entities_deleted_total` | counter | mutations | `connector`, `resource`, `source` |
11
+ | `airfoil_connector_batches_total` | counter | batches | `connector`, `resource`, `source`, `outcome` |
12
+ | `airfoil_connector_batch_size` | histogram | mutations/batch | `connector`, `resource`, `source` |
13
+ | `airfoil_connector_publish_duration_ms` | histogram timer | ms | `connector`, `resource`, `source` |
14
+ | `airfoil_connector_webhook_requests_total` | counter | requests | `connector`, `path`, `outcome` |
15
+ | `airfoil_connector_webhook_queue_depth` | gauge | batches | `connector` |
16
+ | `airfoil_connector_sync_state` | gauge | none | `connector`, `resource`, `state` |
17
+ | `airfoil_connector_last_success_timestamp_seconds` | gauge | Unix seconds | `connector`, `resource`, `source` |
18
+ | `airfoil_connector_api_retries_total` | counter | retries | `connector`, `reason` |
19
+
20
+ Batch `source` is `backfill`, `changes`, or `webhook`. Batch `outcome` is `accepted`, `rejected`, or `error`. Webhook `outcome` is `ok`, `read_error`, `invalid_json`, `invalid_payload`, `rejected`, or `handler_error`. Sync `state` is `pending`, `backfilling`, `live`, or `error`.
21
+
22
+ API retry `reason` is `transport`, `timeout`, `rate_limit`, or `server_error`. The counter increments only when another request will be attempted. Provider-side limiter waits without a failed request are not retries.
23
+
24
+ Counters are activity since process start, not entity population. Use `increase()` or `rate()` and let Prometheus/OTLP consumers handle process restarts. `sum(upserts) - sum(deletes)` is connector activity, not the current table size; current totals belong in Wings/data-lake tables.
25
+
26
+ The last-success gauge is restored from durable state after restart and is `0` until the source commits its first checkpoint. Calculate source freshness in Prometheus:
27
+
28
+ ```promql
29
+ time() - airfoil_connector_last_success_timestamp_seconds
30
+ ```
31
+
32
+ ## Sync Status
33
+
34
+ HTTP connector runtimes expose `GET /status` by default. The response shape is decoded by `Status.StatusResponseSchema`:
35
+
36
+ ```json
37
+ {
38
+ "connector": "producer-example",
39
+ "resources": [
40
+ {
41
+ "name": "products",
42
+ "state": "live",
43
+ "backfill": {
44
+ "completed": true,
45
+ "cutoff": "2026-01-01T00:00:00Z",
46
+ "lastSuccessAt": "2026-01-01T00:05:00Z"
47
+ },
48
+ "changes": {
49
+ "cursor": "2026-01-01T00:10:00Z",
50
+ "lastSuccessAt": "2026-01-01T00:10:01Z"
51
+ }
52
+ }
53
+ ]
54
+ }
55
+ ```
56
+
57
+ `ResourceStatusSchema`, `ResourceErrorSchema`, and `StatusUnavailableResponseSchema` are also exported from `@useairfoil/connector-kit/status` with their derived TypeScript types.
58
+
59
+ A resource with no persisted state is `pending`; an incomplete backfill is `backfilling`; completed backfill or changes-only resources are `live`. `lastSuccessAt` advances in the same durable write as its checkpoint and only after Wings accepts the batch.
60
+
61
+ Backfill or changes failures set `error` with a structured `lastError`. The error includes `source`, `operation`, a stable `code` and SDK-owned `message`, plus `at`; it never contains the raw Effect cause. Backfill and changes errors are stored independently, and `/status` returns the newer outstanding error when both exist.
62
+
63
+ When an expected source failure reaches the ingestion engine after any dependency retries, that source is parked until the process restarts. Other resources, webhooks, and HTTP routes keep running. Defects and interruption still terminate the runtime. `GET /health` only proves that the HTTP process is serving requests; provider, Wings, or PostgreSQL failures are reported through status and metrics instead.
64
+
65
+ ## Wings Contract
66
+
67
+ Import pure connector manifests from first-party producer packages, for example `@useairfoil/producer-polar/manifest`, through a registry. Use `Manifest.decodeConfig(manifest, input)` for canonical server-side validation and `Schema.toStandardSchemaV1(Manifest.configSchema(manifest))` for form resolvers. The schema accepts JSON-shaped config and browser form-shaped values, including stringified numbers/booleans and empty optional fields. Treat `field.required` and `field.default` independently: the canonical decoder treats an empty optional field as omitted and resolves its default, while an optional field without a default remains absent. Store user-facing connector config by manifest field `name`, then use `Manifest.toRuntimeDocument(...)` to map it to `field.runtimeKey` names. Hosted pods mount that complete JSON document read-only and point `AIRFOIL_CONFIG_PATH` at it; they do not receive one environment variable per user field. Secret rendering/redaction comes from `field.secret`, and existing secret values must not be returned to the browser. Platform-owned runtime config such as Wings host, namespace, tables, PostgreSQL bindings, webhook ports, and telemetry remains infrastructure-owned environment/Secret configuration outside the manifest document.
68
+
69
+ ```ts
70
+ import * as Manifest from "@useairfoil/connector-kit/manifest";
71
+ import { manifest as polarManifest } from "@useairfoil/producer-polar/manifest";
72
+ import { Schema } from "effect";
73
+
74
+ const schema = Schema.toStandardSchemaV1(Manifest.configSchema(polarManifest));
75
+ const result = await schema["~standard"].validate(formValues);
76
+ ```
77
+
78
+ Poll `GET /status` and decode with `Status.StatusResponseSchema`. Chart ingestion with `increase(airfoil_connector_entities_upserted_total[...])`, alert on `airfoil_connector_sync_state{state="error"} == 1`, and alert on non-`ok` webhook outcomes.
package/README.md CHANGED
@@ -1,123 +1,485 @@
1
1
  # @useairfoil/connector-kit
2
2
 
3
- Toolkit for building Airfoil connectors with Effect.
3
+ Toolkit for building Airfoil producer connectors with Effect.
4
4
 
5
- ---
5
+ `@useairfoil/connector-kit` gives connector authors the pieces needed to define, run, test, and publish resource-first producer connectors:
6
6
 
7
- ## User guide (build a connector)
7
+ - `Connector.define(...)` describes a connector.
8
+ - `Resource.entity(...)` describes a Wings table-backed resource.
9
+ - `Fetch.page(...)` and `Fetch.changes(...)` describe backfill and polling fetches.
10
+ - `Resource.webhook(...)` lets a resource normalize provider webhook payloads into mutations.
11
+ - `Webhook.route(...)` defines connector-level HTTP webhook routes.
12
+ - `Ingestion.run(...)` runs resource ingestion and checkpoints after accepted publishes.
13
+ - `Publisher.layerConsole` logs accepted batches locally.
14
+ - `Publisher.layerWings(...)` publishes resource mutations into Wings tables.
15
+ - `ConnectorApp.check(...)` validates selected resources before provisioning.
16
+ - `ConnectorApp.start(...)` starts a complete Node HTTP connector process.
17
+ - `Auth.makeTokenCache(...)` caches short-lived provider access tokens in memory.
8
18
 
9
- This section is for connector authors who want to build and run a connector.
19
+ The package is intentionally Layer-oriented: connector code defines resources and routes, while entrypoints provide runtime dependencies such as publishers, state stores, telemetry, and API clients.
10
20
 
11
- ### Install
21
+ ## Install
12
22
 
13
23
  ```bash
14
- bun add @useairfoil/connector-kit
24
+ pnpm add @useairfoil/connector-kit effect@^4.0.0-rc.108
15
25
  ```
16
26
 
17
- ### Minimal example
27
+ This repo currently uses the Effect v4 release candidate. In workspace packages, prefer the workspace catalog (`"effect": "catalog:"`) so all packages stay on the supported RC version.
28
+
29
+ ## Package Shape
30
+
31
+ The package root exposes the common connector authoring API:
18
32
 
19
33
  ```ts
20
- import { Schema, Effect, Layer, Stream } from "effect";
21
34
  import {
22
- defineConnector,
23
- defineEntity,
35
+ Auth,
36
+ Connector,
37
+ ConnectorApp,
38
+ ConnectorError,
39
+ Cursor,
40
+ Fetch,
41
+ Ingestion,
42
+ Manifest,
43
+ Metrics,
24
44
  Publisher,
25
- runConnector,
26
- StateStoreInMemory,
27
- WebhookServerLayer,
28
- makeWebhookQueue,
45
+ Resource,
46
+ RuntimeConfig,
47
+ StateStore,
48
+ Status,
49
+ Telemetry,
50
+ Webhook,
29
51
  } from "@useairfoil/connector-kit";
52
+ ```
30
53
 
31
- const Customer = Schema.Struct({
32
- id: Schema.String,
33
- email: Schema.String,
34
- created_at: Schema.Date,
35
- });
54
+ Subpath exports are available for runtime domains:
36
55
 
37
- const program = Effect.gen(function* () {
38
- const webhook = yield* makeWebhookQueue<Schema.Schema.Type<typeof Customer>>();
39
-
40
- const connector = defineConnector({
41
- name: "producer-example",
42
- entities: [
43
- defineEntity({
44
- name: "customers",
45
- schema: Customer,
46
- primaryKey: "id",
47
- live: webhook.queue,
48
- backfill: Stream.empty,
49
- }),
50
- ],
51
- events: [],
56
+ - `@useairfoil/connector-kit/auth`
57
+ - `@useairfoil/connector-kit/ingestion`
58
+ - `@useairfoil/connector-kit/connector-app`
59
+ - `@useairfoil/connector-kit/manifest`
60
+ - `@useairfoil/connector-kit/metrics`
61
+ - `@useairfoil/connector-kit/publisher`
62
+ - `@useairfoil/connector-kit/runtime-config`
63
+ - `@useairfoil/connector-kit/state-store`
64
+ - `@useairfoil/connector-kit/status`
65
+ - `@useairfoil/connector-kit/webhook`
66
+ - `@useairfoil/connector-kit/errors`
67
+
68
+ Core definition helpers and `Telemetry` are intentionally root-only.
69
+
70
+ ## Provider Credentials
71
+
72
+ `Auth.makeTokenCache(...)` wraps a provider token exchange with Effect's cache. Acquisition stays lazy, concurrent callers share one exchange, and failures are not cached. The default refresh point is halfway through the provider lifetime.
73
+
74
+ ```ts
75
+ import { Auth } from "@useairfoil/connector-kit";
76
+ import { Duration, Effect, Redacted } from "effect";
77
+
78
+ const tokenCache =
79
+ yield *
80
+ Auth.makeTokenCache({
81
+ acquire: exchangeCredentials.pipe(
82
+ Effect.map(({ accessToken, expiresInSeconds }) => ({
83
+ value: Redacted.make(accessToken),
84
+ expiresIn: Duration.seconds(expiresInSeconds),
85
+ })),
86
+ ),
52
87
  });
53
88
 
54
- yield* runConnector(connector, new Date());
55
- }).pipe(
56
- Effect.provide(StateStoreInMemory),
57
- Effect.provide(
58
- Layer.succeed(Publisher, {
59
- publish: () => Effect.succeed({ requestId: 1n }),
60
- }),
61
- ),
62
- Effect.provide(
63
- WebhookServerLayer({
64
- port: 8080,
65
- routes: [
66
- {
67
- path: "/webhook/customers",
68
- schema: Customer,
69
- dispatch: (payload) =>
70
- Effect.succeed([
71
- {
72
- queue: webhook.queue,
73
- batch: { cursor: new Date(), rows: [payload] },
74
- },
75
- ]),
76
- },
77
- ],
89
+ const accessToken = yield * tokenCache.get;
90
+ ```
91
+
92
+ The cache is process-local and does not use `StateStore`. It does not add retries or background refresh. The first request after the refresh point performs the next exchange.
93
+
94
+ ## Manifests
95
+
96
+ Connector manifests are pure metadata for UI, Wings deployment, and validation. Put user-facing connector config in `src/manifest.ts` and keep platform-owned runtime config, such as ports, Wings host, table names, and OTEL flags, as normal Effect `Config` in entrypoints.
97
+
98
+ ```ts
99
+ import * as Manifest from "@useairfoil/connector-kit/manifest";
100
+
101
+ export const ExampleConfigDef = Manifest.defineConfig({
102
+ apiBaseUrl: Manifest.string({
103
+ runtimeKey: "EXAMPLE_API_BASE_URL",
104
+ required: false,
105
+ default: "https://api.example.test",
106
+ }),
107
+ apiToken: Manifest.secret({ runtimeKey: "EXAMPLE_API_TOKEN" }),
108
+ maxRetries: Manifest.number({
109
+ runtimeKey: "EXAMPLE_MAX_RETRIES",
110
+ default: 5,
111
+ integer: true,
112
+ minimum: 0,
113
+ }),
114
+ webhookSecret: Manifest.optional(Manifest.secret({ runtimeKey: "EXAMPLE_WEBHOOK_SECRET" })),
115
+ });
116
+
117
+ export type ExampleConfig = Manifest.ConfigValuesOf<typeof ExampleConfigDef>;
118
+
119
+ export const manifest = Manifest.define({
120
+ name: "producer-example",
121
+ title: "Example",
122
+ config: ExampleConfigDef.spec,
123
+ resources: [{ name: "posts", capabilities: ["backfill", "webhook"] }],
124
+ });
125
+ ```
126
+
127
+ `ExampleConfigDef.config` is the runtime Effect config. `ExampleConfigDef.spec` is serializable manifest metadata. `required` defaults to `true`. Number fields may set `integer` and `minimum`; Effect Schema applies the same constraints to runtime and form values. Use `required: false` with a default when the form may omit a field but the runtime must always receive a concrete value. Use `Manifest.optional(...)` when the runtime result should be an `Option`. Secret fields cannot declare defaults, so optional secrets use `Manifest.optional(Manifest.secret(...))`.
128
+
129
+ Use `Manifest.configSchema(manifest)` for form validation and `Schema.toStandardSchemaV1(...)` for standard-schema form resolvers. The schema accepts normal JSON values and browser form-shaped values: number fields may arrive as strings, boolean fields may arrive as booleans or `"true"`/`"false"`, optional fields may be omitted or submitted as `""`, and required strings reject `""`.
130
+
131
+ Use `Manifest.decodeConfig(manifest, input)` as the canonical server-side decoder. It rejects undeclared fields, treats `""` on a declared optional field as not supplied, and then applies manifest defaults. Therefore clearing or omitting a defaulted optional control means “use the manifest default”; it does not disable that setting. Model disabling as an explicit select/boolean/nullable contract instead of overloading an empty string. An optional field without a default remains absent.
132
+
133
+ Frontend/backend validation example:
134
+
135
+ ```ts
136
+ import * as Manifest from "@useairfoil/connector-kit/manifest";
137
+ import { manifest as polarManifest } from "@useairfoil/producer-polar/manifest";
138
+ import { Schema } from "effect";
139
+
140
+ const configSchema = Manifest.configSchema(polarManifest);
141
+ const formSchema = Schema.toStandardSchemaV1(configSchema);
142
+
143
+ const result = await formSchema["~standard"].validate({
144
+ accessToken: "polar_oat_xxx",
145
+ apiBaseUrl: "https://api.polar.sh/v1/",
146
+ organizationId: "",
147
+ });
148
+
149
+ if ("issues" in result) {
150
+ // Show validation issues in your form.
151
+ } else {
152
+ // Store by manifest field name: accessToken, apiBaseUrl, organizationId.
153
+ // Secrets should be persisted server-side and not echoed back to the browser.
154
+ const values = result.value;
155
+ }
156
+ ```
157
+
158
+ Render fields from `manifest.config`: use `field.name` as the form/storage key, `field.description` for help text, `field.secret` for password inputs/redaction, `field.values` for selects, `field.default` for the documented fallback, `field.required` for required markers, and number `integer` and `minimum` values for input constraints. The UI may show a default as an initial value or clearly labelled placeholder, but clearing it still resolves to that default during canonical decoding. Decode submitted values with `Manifest.decodeConfig(...)`, then map the canonical logical object to its flat runtime document with `Manifest.toRuntimeDocument(...)`. Each `field.runtimeKey` is an Effect Config key, not an instruction to create one Pod environment variable.
159
+
160
+ Hosted connectors receive the runtime document as a read-only JSON file. `AIRFOIL_CONFIG_PATH` selects the file, and `RuntimeConfig.layerHosted()` adds the file beneath Effect's existing environment provider. The file is required and must contain valid JSON; each connector's Effect Config validates the fields it reads. Local sandboxes use Effect's default environment provider. Platform-owned config such as Wings host, namespace, table names, PostgreSQL settings, ports, and OTEL settings stays outside the manifest and outside the connector JSON.
161
+
162
+ ### Pre-provision Checks
163
+
164
+ The dashboard backend imports each connector package and runs `ConnectorApp.check(...)` after manifest decoding but before persisting secrets or creating database and Kubernetes resources. Validate submitted resource names against `manifest.resources` at the request boundary before calling the typed check API. Replace the backend process provider with the submitted runtime document so unrelated backend environment variables cannot satisfy connector configuration:
165
+
166
+ ```ts
167
+ import { ConnectorApp, Manifest } from "@useairfoil/connector-kit";
168
+ import { PolarConnector, manifest } from "@useairfoil/producer-polar";
169
+ import { ConfigProvider, Effect } from "effect";
170
+ import { FetchHttpClient } from "effect/unstable/http";
171
+
172
+ const values = yield * Manifest.decodeConfig(manifest, submittedConfig);
173
+ const runtimeDocument = Manifest.toRuntimeDocument(manifest, values);
174
+ const provider = ConfigProvider.fromUnknown(runtimeDocument, { preserveEmptyStrings: true });
175
+
176
+ const result =
177
+ yield *
178
+ ConnectorApp.check(
179
+ PolarConnector.PolarConnector,
180
+ PolarConnector.layerConfig(PolarConnector.PolarConfigDef.config),
181
+ { resources: ["customers", "orders"] },
182
+ ).pipe(Effect.provide(ConfigProvider.layer(provider)), Effect.provide(FetchHttpClient.layer));
183
+ ```
184
+
185
+ Every resource declares a required, read-only `check` effect. Layer/configuration failures are returned for every selected resource; resource-specific failures are returned only under that resource name. Expected failures are values (`{ _tag: "error", message }`), while defects and interruption remain Effect failures. Provision only when all selected results are `{ _tag: "ok" }`. Checks must never publish, checkpoint, or mutate the upstream provider.
186
+
187
+ `RuntimeConfig.PlatformRuntimeKey` is the canonical shared-key contract used by hosted config, StateStore, telemetry, Wings, and PostgreSQL bootstrap code. `Manifest.defineConfig` rejects only those exact shared values; it does not impose connector-specific naming, uniqueness, or metadata policy. Connector packages are first-party code, so their table, port, field, and resource naming remains the connector author's responsibility.
188
+
189
+ ## Resource Model
190
+
191
+ Resources emit mutations, not raw rows. Connector Kit currently supports `Resource.entity(...)` for Wings table-backed resources.
192
+
193
+ ```ts
194
+ const Posts = Resource.entity({
195
+ name: "posts",
196
+ schema: PostSchema,
197
+ key: "id",
198
+ version: "updatedAt",
199
+ check: api.fetchPosts({ page: 1, limit: 1 }).pipe(Effect.asVoid),
200
+ backfill: Fetch.page({
201
+ pageCursor: Cursor.number(),
202
+ cutoff: Cursor.isoDateTime(),
203
+ fetch: ({ pageCursor }) =>
204
+ api.fetchPosts({ page: typeof pageCursor === "number" ? pageCursor : 1 }).pipe(
205
+ Effect.map((page) => ({
206
+ mutations: page.items.map(Resource.upsert),
207
+ nextPageCursor: page.hasMore ? page.nextPage : page.page,
208
+ hasMore: page.hasMore,
209
+ })),
210
+ ),
211
+ }),
212
+ });
213
+ ```
214
+
215
+ `key` and `version` autocomplete from the decoded schema row type. Invalid field names are rejected at compile time.
216
+
217
+ Mutations are created with:
218
+
219
+ ```ts
220
+ Resource.upsert(row);
221
+
222
+ Resource.delete({
223
+ key: "post_123",
224
+ version: "2026-01-01T00:00:00.000Z",
225
+ });
226
+ ```
227
+
228
+ ## Fetches
229
+
230
+ `Fetch.page(...)` is for paginated backfill. It receives the stored page cursor and the resource cutoff.
231
+
232
+ `Fetch.changes(...)` is for polling incremental changes. It receives the stored changes cursor and can be configured with an interval.
233
+
234
+ Cursor helpers:
235
+
236
+ - `Cursor.string()`
237
+ - `Cursor.number()`
238
+ - `Cursor.isoDateTime()`
239
+ - `Cursor.nowIsoDateTime`
240
+
241
+ Date cursor values are accepted at API boundaries and normalized to ISO strings before checkpoint writes.
242
+
243
+ ## Webhooks
244
+
245
+ Webhooks are connector-level routes with schema-validated payloads. A route dispatches to resource-owned webhook handlers by calling `to(resource, payload)`.
246
+
247
+ ```ts
248
+ const Posts = Resource.entity({
249
+ name: "posts",
250
+ schema: PostSchema,
251
+ key: "id",
252
+ version: "updatedAt",
253
+ check: Effect.void,
254
+ webhook: Resource.webhook({
255
+ schema: PostEventSchema,
256
+ handler: ({ payload }) => Effect.succeed([Resource.upsert(payload.data)]),
257
+ }),
258
+ });
259
+
260
+ const route = Webhook.route({
261
+ path: "/webhooks/example",
262
+ ackMode: "after-publish",
263
+ schema: ProviderWebhookSchema,
264
+ handler: ({ request, rawBody, payload, to }) =>
265
+ Effect.gen(function* () {
266
+ yield* verifySignature({ request, rawBody });
267
+ yield* to(Posts, payload);
268
+ return HttpServerResponse.jsonUnsafe({ ok: true });
78
269
  }),
270
+ });
271
+ ```
272
+
273
+ Route behavior:
274
+
275
+ - reads the raw body once
276
+ - parses JSON once
277
+ - validates the route payload schema
278
+ - passes `request`, `rawBody`, typed `payload`, and `to(...)` to the handler
279
+ - returns `400` for invalid body reads, invalid JSON, or invalid route payloads
280
+ - returns `500` for unexpected handler/runtime/publisher failures
281
+
282
+ Signature verification is connector-owned and should use `rawBody`.
283
+
284
+ `ackMode: "after-publish"` publishes collected mutations before the response is completed. `ackMode: "after-enqueue"` enqueues collected mutations and lets the background webhook consumer publish them.
285
+
286
+ ## Connector Definition
287
+
288
+ ```ts
289
+ const connector = Connector.define({
290
+ name: "producer-example",
291
+ title: "Producer Example",
292
+ resources: [Posts],
293
+ webhooks: [route],
294
+ });
295
+ ```
296
+
297
+ ## Ingestion
298
+
299
+ `Ingestion.run(...)` contains the runtime engine. `ConnectorApp.start(...)` is the usual entrypoint for runnable producer CLIs.
300
+
301
+ Current runtime behavior:
302
+
303
+ - runs resource backfill, changes, and webhooks concurrently
304
+ - initializes the same initial cutoff for backfill and changes
305
+ - publishes through `Publisher.Publisher`
306
+ - checkpoints only after an accepted publish ACK
307
+ - does not checkpoint rejected publishes
308
+ - allows empty accepted batches to advance state
309
+ - stores `lastSuccessAt` with each durable checkpoint
310
+ - persists resource state through `StateStore.StateStore`
311
+ - parks a source when an expected failure reaches the ingestion engine, after any dependency retries
312
+ - keeps other sources, webhooks, and HTTP routes running when one source is parked
313
+
314
+ Parked sources resume after process restart or configuration redeployment. Defects and interruption are not isolated and still stop the runtime.
315
+
316
+ `Ingestion.run` depends only on the typed Airfoil `StateStore`; it does not expose the underlying Effect `KeyValueStore`. Provide `StateStore.layerMemory` for development/tests. Production entrypoints provide `StateStore.layerSql()`, which privately composes Effect's `KeyValueStore.layerSql` and scopes every key with the non-empty `AIRFOIL_CONNECTOR_INSTANCE_ID`. The platform ID is opaque and is not required to be a UUID.
317
+
318
+ State keys use plain colon-delimited segments and are intentionally inspectable; they are not escaped or encoded. The trusted backend must issue connector instance IDs without `:`, and connector authors must keep resource names free of `:`. Connector Kit currently relies on that naming contract rather than adding runtime validation.
319
+
320
+ The shared SQL table defaults to `_airfoil_connectors_state`. Set `AIRFOIL_STATE_TABLE` only to override that default. `POSTGRES_CONNECTION_STRING` is consumed by the PostgreSQL client layer, not by `StateStore` itself:
321
+
322
+ ```ts
323
+ import { PgClient } from "@effect/sql-pg";
324
+ import { RuntimeConfig, StateStore } from "@useairfoil/connector-kit";
325
+ import { Config, Layer, Schema } from "effect";
326
+
327
+ const PostgresLive = PgClient.layerConfig({
328
+ url: Config.schema(
329
+ Schema.Redacted(Schema.NonEmptyString),
330
+ RuntimeConfig.PlatformRuntimeKey.postgresConnectionString,
79
331
  ),
80
- );
332
+ maxConnections: Config.succeed(2),
333
+ });
81
334
 
82
- Effect.runPromise(program);
335
+ const StateStoreLive = StateStore.layerSql().pipe(Layer.provide(PostgresLive));
83
336
  ```
84
337
 
85
- ---
338
+ The platform injects the instance ID and Secret-backed PostgreSQL connection string used by `PgClient`, plus an optional table-name override. Connector business code receives `StateStore` but does not receive the connector instance ID, raw SQL client, or global clear/size operations.
339
+
340
+ ## Publisher
86
341
 
87
- ## Development (concepts and architecture)
342
+ `Publisher.Publisher` is the Effect service boundary for publishing resource mutation batches.
88
343
 
89
- ### Core concepts
344
+ `Publisher.layerConsole` accepts batches and logs them locally.
90
345
 
91
- - `defineConnector` describes your connector and its entities.
92
- - `defineEntity` wires live and backfill streams for each entity.
93
- - `Publisher` is the output boundary (where batches go).
94
- - `StateStore` tracks cursors and backfill state.
95
- - `WebhookServerLayer` turns webhook routes into an HTTP server.
346
+ `Publisher.layerWings(...)` publishes mutations to Wings tables:
96
347
 
97
- ### Layers and Effect services
348
+ ```ts
349
+ const publisherLayer = Publisher.layerWings({
350
+ connector,
351
+ tables: {
352
+ posts: "namespaces/default/tables/posts",
353
+ },
354
+ });
355
+ ```
98
356
 
99
- Connector-kit is designed around Effect services and Layers. Your application should provide:
357
+ The `tables` map is keyed by resource name. Values can be table names or objects with a table name and optional partition value.
100
358
 
101
- - a `Publisher` Layer
102
- - a `StateStore` Layer
103
- - an HTTP server Layer (if you use webhooks)
104
- - any custom services your connector needs (API clients, Effect Config)
359
+ ```ts
360
+ Publisher.layerWings({
361
+ connector,
362
+ tables: {
363
+ posts: {
364
+ name: "namespaces/default/tables/posts",
365
+ partitionValue: "account_123",
366
+ },
367
+ },
368
+ });
369
+ ```
105
370
 
106
- ### Testing with VCR
371
+ The Wings publisher resolves table metadata during layer construction, validates resource key/version/partition compatibility, sends upserts with full rows, and sends deletes with key/version-only rows.
107
372
 
108
- VCR is provided via `@useairfoil/effect-vcr` as an Effect `HttpClient` layer. This keeps HTTP recording out of connector logic.
373
+ ## Minimal Example
109
374
 
110
375
  ```ts
111
- import { FetchHttpClient } from "@effect/platform";
112
- import { NodeFileSystem } from "@effect/platform-node";
113
- import { FileSystemCassetteStore, VcrHttpClient } from "@useairfoil/effect-vcr";
114
- import { Layer } from "effect";
115
-
116
- const cassetteLayer = CassetteStoreLive.pipe(Layer.provide(NodeFileSystem.layer));
117
-
118
- const vcrLayer = VcrHttpClientLayer({
119
- cassetteDir: "cassettes",
120
- cassetteName: "example",
121
- mode: "auto",
122
- }).pipe(Layer.provide(Layer.mergeAll(FetchHttpClient.layer, cassetteLayer)));
376
+ import { NodeRuntime } from "@effect/platform-node";
377
+ import {
378
+ Connector,
379
+ ConnectorApp,
380
+ Cursor,
381
+ Fetch,
382
+ Publisher,
383
+ Resource,
384
+ StateStore,
385
+ Telemetry,
386
+ } from "@useairfoil/connector-kit";
387
+ import { Effect, Layer, Schema } from "effect";
388
+ import { FetchHttpClient } from "effect/unstable/http";
389
+
390
+ const PostSchema = Schema.Struct({
391
+ id: Schema.Number,
392
+ title: Schema.String,
393
+ updatedAt: Schema.String,
394
+ });
395
+
396
+ type Post = Schema.Schema.Type<typeof PostSchema>;
397
+
398
+ const Posts = Resource.entity({
399
+ name: "posts",
400
+ schema: PostSchema,
401
+ key: "id",
402
+ version: "updatedAt",
403
+ check: Effect.void,
404
+ backfill: Fetch.page({
405
+ pageCursor: Cursor.number(),
406
+ cutoff: Cursor.isoDateTime(),
407
+ fetch: () =>
408
+ Effect.succeed({
409
+ mutations: [
410
+ Resource.upsert({ id: 1, title: "Hello", updatedAt: "2026-01-01T00:00:00.000Z" }),
411
+ ],
412
+ nextPageCursor: 1,
413
+ hasMore: false,
414
+ }),
415
+ }),
416
+ });
417
+
418
+ const connector = Connector.define({
419
+ name: "producer-example",
420
+ resources: [Posts],
421
+ });
422
+
423
+ const BootstrapLayer = FetchHttpClient.layer;
424
+
425
+ const TelemetryLayer = Telemetry.layerOtlp().pipe(Layer.provide(BootstrapLayer));
426
+ const RuntimeLayer = Layer.mergeAll(
427
+ BootstrapLayer,
428
+ StateStore.layerMemory,
429
+ Publisher.layerConsole,
430
+ TelemetryLayer,
431
+ );
432
+
433
+ Effect.scoped(ConnectorApp.start(connector, { port: 8080 })).pipe(
434
+ Effect.provide(RuntimeLayer),
435
+ NodeRuntime.runMain,
436
+ );
123
437
  ```
438
+
439
+ ## Telemetry
440
+
441
+ `Telemetry` contains connector-kit span names, span attributes, error annotation helpers, OTLP tracing layers, and OTLP metrics layers. HTTP connector runtimes expose shallow process health at `GET /health`, Prometheus metrics at `GET /metrics`, and durable sync state at `GET /status` by default. Provider, Wings, and PostgreSQL failures do not make `/health` fail.
442
+
443
+ `/status` includes `lastSuccessAt` for each checkpointed backfill or changes source. Use `time() - airfoil_connector_last_success_timestamp_seconds` to monitor source freshness without interpreting provider cursors.
444
+
445
+ Common entry points:
446
+
447
+ - `Telemetry.layer(config, options?)`
448
+ - `Telemetry.layerConfig(config, options?)`
449
+ - `Telemetry.layerOtlpTracing(options?)` for OTLP traces
450
+ - `Telemetry.layerOtlpMetrics(options?)` for OTLP metrics
451
+ - `Telemetry.layerOtlp(options?)` for both traces and metrics
452
+ - `Telemetry.layerMetricsConsoleDump(interval?)`
453
+
454
+ Default redacted headers:
455
+
456
+ - `authorization`
457
+ - `cookie`
458
+ - `set-cookie`
459
+ - `x-api-key`
460
+ - `/api[-_]?key/i`
461
+ - `/secret/i`
462
+ - `/signature/i`
463
+ - `/token/i`
464
+
465
+ Telemetry environment variables:
466
+
467
+ | Variable | Read by | Description |
468
+ | ----------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
469
+ | `OTEL_ENABLED` | Connector Kit | Enables OTLP export when `true`. Defaults to `false`. |
470
+ | `OTEL_EXPORTER_OTLP_ENDPOINT` | Connector Kit | OTLP base URL, for example `http://localhost:4318`. Connector Kit appends `/v1/traces` and `/v1/metrics` as needed. Required when `OTEL_ENABLED=true`. |
471
+ | `OTEL_EXPORTER_OTLP_HEADERS` | Connector Kit | Optional comma-separated headers, for example `Authorization=Bearer <token>,X-Axiom-Dataset=<dataset>`. |
472
+ | `OTEL_SERVICE_NAME` | Effect | Service name resource attribute, for example `producer-shopify`. |
473
+ | `OTEL_SERVICE_VERSION` | Effect | Optional service version resource attribute. |
474
+ | `OTEL_RESOURCE_ATTRIBUTES` | Effect | Optional comma-separated resource attributes, for example `deployment.environment=production,team=data`. |
475
+
476
+ ## Testing
477
+
478
+ For tests, the most common setup is:
479
+
480
+ - `StateStore.layerMemory` for state
481
+ - a small in-memory `Publisher.Publisher` test layer
482
+ - `ConnectorApp.check(...)` with an in-memory `ConfigProvider` for pre-provision validation
483
+ - `Ingestion.run(...)` or `ConnectorApp.start(...)` inside `Effect.scoped`
484
+
485
+ Keep HTTP recording concerns outside connector logic by providing a VCR-backed `HttpClient` Layer.
@@ -0,0 +1,2 @@
1
+ import { i as makeTokenCache, n as ExpiringToken, r as TokenCache } from "../index-CTHVudvQ.js";
2
+ export { ExpiringToken, TokenCache, makeTokenCache };
@@ -0,0 +1,3 @@
1
+ import { n as makeTokenCache } from "../auth-DvU_CZ7C.js";
2
+
3
+ export { makeTokenCache };