@useairfoil/api 0.0.1 → 0.5.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/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 GNC Labs Limited
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
193
+ this file except in compliance with the License. You may obtain a copy of the
194
+ License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software distributed
199
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
200
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
201
+ specific language governing permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # Airfoil API
2
+
3
+ This package has the Effect clients for Wings catalogs and Arrow Flight
4
+ ingestion.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ pnpm add @useairfoil/api effect@^4
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ```ts
15
+ import { CatalogManager } from "@useairfoil/api";
16
+ import { Effect, Layer } from "effect";
17
+ import { FetchHttpClient } from "effect/http";
18
+
19
+ const catalog = CatalogManager.getCatalog("analytics").pipe(
20
+ Effect.provide(
21
+ CatalogManager.layer({ engineUrl: "http://localhost:7777" }).pipe(
22
+ Layer.provide(FetchHttpClient.layer),
23
+ ),
24
+ ),
25
+ );
26
+ ```
27
+
28
+ Use `CatalogManager.ingestor(...)` inside `Effect.scoped`. The first batch
29
+ sets the Arrow schema. Later batches on that stream must use the same schema.
30
+
31
+ `getIcebergCatalog(id)` connects directly to the registered catalog URI. The
32
+ caller needs network access to that URI. Requests use the registered `token`
33
+ and `header.*` properties for authentication and headers.
@@ -0,0 +1,2 @@
1
+ import { c as layerConfig, d as CatalogManager, f as CatalogManagerService, g as CatalogManagerError, h as RestCatalogConfig, i as getIcebergCatalog, l as make, m as CreateCatalogRequest, n as deleteCatalog, o as ingestor, p as Catalog, r as getCatalog, s as layer, t as createCatalog, u as CatalogManagerOptions } from "../index-0sDy5ImH.mjs";
2
+ export { Catalog, CatalogManager, CatalogManagerError, type CatalogManagerOptions, type CatalogManagerService, CreateCatalogRequest, RestCatalogConfig, createCatalog, deleteCatalog, getCatalog, getIcebergCatalog, ingestor, layer, layerConfig, make };
@@ -0,0 +1,2 @@
1
+ import { a as getIcebergCatalog, c as layerConfig, d as CreateCatalogRequest, f as RestCatalogConfig, h as CatalogManagerError, i as getCatalog, l as make, m as CatalogManager, n as createCatalog, o as ingestor, r as deleteCatalog, s as layer, u as Catalog } from "../catalog-manager-CMWpf4i3.mjs";
2
+ export { Catalog, CatalogManager, CatalogManagerError, CreateCatalogRequest, RestCatalogConfig, createCatalog, deleteCatalog, getCatalog, getIcebergCatalog, ingestor, layer, layerConfig, make };
@@ -0,0 +1,232 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { Config, Context, Data, Deferred, Effect, Layer, Queue, Ref, Schema, Scope, Semaphore, Stream } from "effect";
3
+ import { IcebergCatalog } from "@useairfoil/effect-iceberg";
4
+ import { Any, ArrowFlightClient, FlightDataEncoder, FlightDescriptor, FlightDescriptor_DescriptorType } from "@useairfoil/flight";
5
+ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
6
+ //#region src/catalog-manager/error.ts
7
+ /** Error returned by the module. */
8
+ var CatalogManagerError = class extends Data.TaggedError("CatalogManagerError") {};
9
+ //#endregion
10
+ //#region src/catalog-manager/service.ts
11
+ /** Effect service tag for the catalog management API. */
12
+ var CatalogManager = class extends Context.Service()("@useairfoil/api/CatalogManager") {};
13
+ //#endregion
14
+ //#region src/ingestor/error.ts
15
+ /** Error returned when ingestion fails. */
16
+ var IngestorError = class extends Data.TaggedError("IngestorError") {};
17
+ //#endregion
18
+ //#region src/ingestor/make.ts
19
+ const textEncoder = new TextEncoder();
20
+ const textDecoder = new TextDecoder();
21
+ const Acknowledgement = Schema.Struct({ request_id: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) });
22
+ const encodeJson = (value, message) => Effect.try({
23
+ try: () => textEncoder.encode(JSON.stringify(value)),
24
+ catch: (cause) => new IngestorError({
25
+ message,
26
+ cause
27
+ })
28
+ });
29
+ const decodeAcknowledgement = (result) => Effect.try({
30
+ try: () => JSON.parse(textDecoder.decode(result.appMetadata)),
31
+ catch: (cause) => new IngestorError({
32
+ message: "Ingestion acknowledgement was not valid JSON",
33
+ cause
34
+ })
35
+ }).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Acknowledgement)), Effect.mapError((cause) => cause instanceof IngestorError ? cause : new IngestorError({
36
+ message: "Ingestion acknowledgement was malformed",
37
+ cause
38
+ })));
39
+ /** Internal constructor used to inject a Flight client in tests. */
40
+ const make$1 = Effect.fnUntraced(function* (client, options) {
41
+ const requests = yield* Queue.unbounded();
42
+ const scope = yield* Scope.Scope;
43
+ yield* Scope.addFinalizer(scope, Queue.shutdown(requests));
44
+ const requestIterable = yield* Stream.toAsyncIterableEffect(Stream.fromQueue(requests));
45
+ const pending = yield* Ref.make(/* @__PURE__ */ new Map());
46
+ const nextRequestId = yield* Ref.make(1);
47
+ const schemaSent = yield* Ref.make(false);
48
+ const terminalError = yield* Ref.make(void 0);
49
+ const lock = yield* Semaphore.make(1);
50
+ const failPending = (error) => lock.withPermit(Effect.gen(function* () {
51
+ yield* Ref.set(terminalError, error);
52
+ const deferreds = yield* Ref.getAndSet(pending, /* @__PURE__ */ new Map());
53
+ yield* Effect.forEach(deferreds.values(), (deferred) => Deferred.fail(deferred, error), { discard: true });
54
+ }));
55
+ const acknowledge = Effect.fnUntraced(function* (result) {
56
+ const { request_id: requestId } = yield* decodeAcknowledgement(result);
57
+ if (requestId === 0) return;
58
+ const deferred = yield* Ref.modify(pending, (current) => {
59
+ const found = current.get(requestId);
60
+ if (found === void 0) return [void 0, current];
61
+ const updated = new Map(current);
62
+ updated.delete(requestId);
63
+ return [found, updated];
64
+ });
65
+ if (deferred !== void 0) yield* Deferred.succeed(deferred, void 0);
66
+ });
67
+ const controller = new AbortController();
68
+ const responseIterable = yield* Effect.try({
69
+ try: () => client.doPut(requestIterable, { signal: controller.signal }),
70
+ catch: (cause) => new IngestorError({
71
+ message: "Failed to start ingestion stream",
72
+ cause
73
+ })
74
+ });
75
+ const consumeResponses = Stream.fromAsyncIterable(responseIterable, (cause) => new IngestorError({
76
+ message: "Ingestion response stream failed",
77
+ cause
78
+ })).pipe(Stream.runForEach(acknowledge));
79
+ yield* Effect.forkScoped(consumeResponses.pipe(Effect.matchEffect({
80
+ onFailure: failPending,
81
+ onSuccess: () => failPending(new IngestorError({ message: "Ingestion response stream ended prematurely" }))
82
+ })));
83
+ yield* Scope.addFinalizer(scope, Effect.sync(() => controller.abort()));
84
+ return { push: Effect.fnUntraced(function* (batch) {
85
+ const deferred = yield* lock.withPermit(Effect.gen(function* () {
86
+ const terminal = yield* Ref.get(terminalError);
87
+ if (terminal !== void 0) return yield* Effect.fail(terminal);
88
+ if (!(yield* Ref.get(schemaSent))) {
89
+ const appMetadata = yield* encodeJson({
90
+ request_id: 0,
91
+ catalog: options.catalog,
92
+ namespace: options.namespace,
93
+ table_name: options.table
94
+ }, "Failed to encode ingestion schema metadata");
95
+ const descriptor = FlightDescriptor.create({
96
+ type: FlightDescriptor_DescriptorType.CMD,
97
+ cmd: Any.encode(Any.create({
98
+ typeUrl: "airfoil.v1.Ingest",
99
+ value: /* @__PURE__ */ new Uint8Array()
100
+ })).finish()
101
+ });
102
+ const schema = yield* Effect.try({
103
+ try: () => FlightDataEncoder.encodeSchema(batch.schema, {
104
+ flightDescriptor: descriptor,
105
+ appMetadata
106
+ }),
107
+ catch: (cause) => new IngestorError({
108
+ message: "Failed to encode ingestion schema",
109
+ cause
110
+ })
111
+ });
112
+ yield* Queue.offer(requests, schema);
113
+ yield* Ref.set(schemaSent, true);
114
+ }
115
+ const requestId = yield* Ref.getAndUpdate(nextRequestId, (current) => current + 1);
116
+ const appMetadata = yield* encodeJson({ request_id: requestId }, "Failed to encode ingestion batch metadata");
117
+ const messages = yield* Effect.try({
118
+ try: () => FlightDataEncoder.encodeBatch(batch, { appMetadata: () => appMetadata }),
119
+ catch: (cause) => new IngestorError({
120
+ message: "Failed to encode ingestion batch",
121
+ cause
122
+ })
123
+ });
124
+ const acknowledgement = yield* Deferred.make();
125
+ yield* Ref.update(pending, (current) => new Map(current).set(requestId, acknowledgement));
126
+ yield* Effect.forEach(messages, (message) => Queue.offer(requests, message), { discard: true });
127
+ return acknowledgement;
128
+ }));
129
+ yield* Deferred.await(deferred);
130
+ }) };
131
+ });
132
+ //#endregion
133
+ //#region src/catalog-manager/schema.ts
134
+ /** Configuration for an upstream Iceberg REST catalog. */
135
+ const RestCatalogConfig = Schema.Struct({
136
+ uri: Schema.String,
137
+ warehouse: Schema.optional(Schema.String),
138
+ properties: Schema.optional(Schema.Record(Schema.String, Schema.String))
139
+ });
140
+ /** Request body accepted by `POST /catalogs`. */
141
+ const CreateCatalogRequest = Schema.Struct({
142
+ id: Schema.String,
143
+ rest: RestCatalogConfig
144
+ });
145
+ /** A catalog managed by the Airfoil Storage Engine. */
146
+ const Catalog = Schema.Struct({
147
+ id: Schema.String,
148
+ rest: RestCatalogConfig
149
+ });
150
+ //#endregion
151
+ //#region src/catalog-manager/layer.ts
152
+ const ErrorResponse = Schema.Struct({ error: Schema.String });
153
+ /** Creates a CatalogManager service from concrete configuration. */
154
+ const make = Effect.fnUntraced(function* (config) {
155
+ const engineUri = config.engineUri.replace(/\/+$/, "");
156
+ const flightClient = yield* ArrowFlightClient.make({ host: (config.flightUri ?? engineUri).replace(/\/+$/, "") });
157
+ const client = (yield* HttpClient.HttpClient).pipe(HttpClient.mapRequest(HttpClientRequest.prependUrl(engineUri)), HttpClient.mapRequest(HttpClientRequest.acceptJson));
158
+ const catalogPath = (id) => `/catalogs/${encodeURIComponent(id)}`;
159
+ const execute = (request) => client.execute(request).pipe(Effect.mapError((cause) => new CatalogManagerError({
160
+ message: "Catalog request failed",
161
+ cause
162
+ })), Effect.flatMap((response) => {
163
+ if (response.status >= 200 && response.status < 300) return Effect.succeed(response);
164
+ return HttpClientResponse.schemaBodyJson(ErrorResponse)(response).pipe(Effect.map((body) => body.error), Effect.catch(() => Effect.succeed(`Catalog request failed with HTTP ${response.status}`)), Effect.flatMap((message) => Effect.fail(new CatalogManagerError({
165
+ message,
166
+ status: response.status
167
+ }))));
168
+ }));
169
+ const decodeCatalog = (request) => Effect.scoped(execute(request).pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(Catalog)), Effect.mapError((cause) => cause instanceof CatalogManagerError ? cause : new CatalogManagerError({
170
+ message: "Catalog response was not valid JSON",
171
+ cause
172
+ }))));
173
+ const getCatalog = (id) => decodeCatalog(HttpClientRequest.get(catalogPath(id)));
174
+ return CatalogManager.of({
175
+ ingestor: (options) => make$1(flightClient, options),
176
+ createCatalog: (request) => Effect.scoped(HttpClientRequest.post("/catalogs").pipe(HttpClientRequest.bodyJson(request), Effect.mapError((cause) => new CatalogManagerError({
177
+ message: "Failed to encode catalog request",
178
+ cause
179
+ })), Effect.flatMap(execute), Effect.asVoid)),
180
+ getCatalog,
181
+ deleteCatalog: (id) => Effect.scoped(execute(HttpClientRequest.delete(catalogPath(id))).pipe(Effect.as(void 0))),
182
+ getIcebergCatalog: (id) => getCatalog(id).pipe(Effect.map((catalog) => IcebergCatalog.make({
183
+ baseUrl: catalog.rest.uri,
184
+ warehouse: catalog.rest.warehouse,
185
+ fetch: (input, init) => {
186
+ const headers = new Headers(init?.headers);
187
+ for (const [key, value] of Object.entries(catalog.rest.properties ?? {})) if (key.startsWith("header.")) headers.set(key.slice(7), value);
188
+ const token = catalog.rest.properties?.token;
189
+ if (token !== void 0 && !headers.has("Authorization")) headers.set("Authorization", `Bearer ${token}`);
190
+ return fetch(input, {
191
+ ...init,
192
+ headers
193
+ });
194
+ }
195
+ })))
196
+ });
197
+ });
198
+ /** Creates a CatalogManager layer from concrete configuration. */
199
+ const layer = (config) => Layer.effect(CatalogManager)(make(config));
200
+ /** Creates a CatalogManager layer from Effect Config values. */
201
+ const layerConfig = (config) => Layer.effect(CatalogManager)(Config.unwrap(config).pipe(Effect.flatMap(make)));
202
+ //#endregion
203
+ //#region src/catalog-manager/index.ts
204
+ var catalog_manager_exports = /* @__PURE__ */ __exportAll({
205
+ Catalog: () => Catalog,
206
+ CatalogManager: () => CatalogManager,
207
+ CatalogManagerError: () => CatalogManagerError,
208
+ CreateCatalogRequest: () => CreateCatalogRequest,
209
+ RestCatalogConfig: () => RestCatalogConfig,
210
+ createCatalog: () => createCatalog,
211
+ deleteCatalog: () => deleteCatalog,
212
+ getCatalog: () => getCatalog,
213
+ getIcebergCatalog: () => getIcebergCatalog,
214
+ ingestor: () => ingestor,
215
+ layer: () => layer,
216
+ layerConfig: () => layerConfig,
217
+ make: () => make
218
+ });
219
+ /** Opens a scoped ingestor for a Iceberg table. */
220
+ const ingestor = (...args) => CatalogManager.use((service) => service.ingestor(...args));
221
+ /** Creates and validates a catalog. */
222
+ const createCatalog = (...args) => CatalogManager.use((service) => service.createCatalog(...args));
223
+ /** Gets a catalog by its bare ID. */
224
+ const getCatalog = (...args) => CatalogManager.use((service) => service.getCatalog(...args));
225
+ /** Deletes a catalog by its bare ID. */
226
+ const deleteCatalog = (...args) => CatalogManager.use((service) => service.deleteCatalog(...args));
227
+ /** Connects directly to the registered upstream catalog; the caller needs network access. */
228
+ const getIcebergCatalog = (...args) => CatalogManager.use((service) => service.getIcebergCatalog(...args));
229
+ //#endregion
230
+ export { getIcebergCatalog as a, layerConfig as c, CreateCatalogRequest as d, RestCatalogConfig as f, CatalogManagerError as h, getCatalog as i, make as l, CatalogManager as m, createCatalog as n, ingestor as o, IngestorError as p, deleteCatalog as r, layer as s, catalog_manager_exports as t, Catalog as u };
231
+
232
+ //# sourceMappingURL=catalog-manager-CMWpf4i3.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog-manager-CMWpf4i3.mjs","names":["make","makeIngestor"],"sources":["../src/catalog-manager/error.ts","../src/catalog-manager/service.ts","../src/ingestor/error.ts","../src/ingestor/make.ts","../src/catalog-manager/schema.ts","../src/catalog-manager/layer.ts","../src/catalog-manager/index.ts"],"sourcesContent":["import { Data } from \"effect\";\n\n/** Error returned by the module. */\nexport class CatalogManagerError extends Data.TaggedError(\"CatalogManagerError\")<{\n readonly message: string;\n readonly status?: number;\n readonly cause?: unknown;\n}> {}\n","import type { IcebergCatalog } from \"@useairfoil/effect-iceberg\";\n\nimport { Context, type Effect, type Scope } from \"effect\";\n\nimport type { Ingestor, IngestorError, IngestorOptions } from \"../ingestor\";\nimport type { CatalogManagerError } from \"./error\";\nimport type { Catalog, CreateCatalogRequest } from \"./schema\";\n\n/** Effect service for managing catalog registrations and ingestion. */\nexport interface CatalogManagerService {\n /** Opens a scoped ingestor for an Iceberg table. */\n readonly ingestor: (\n options: IngestorOptions,\n ) => Effect.Effect<Ingestor, IngestorError, Scope.Scope>;\n\n /** Creates and validates a catalog registration. */\n readonly createCatalog: (\n request: CreateCatalogRequest,\n ) => Effect.Effect<void, CatalogManagerError>;\n\n /** Gets a catalog by its bare ID. */\n readonly getCatalog: (id: string) => Effect.Effect<Catalog, CatalogManagerError>;\n\n /** Deletes a registration by its bare ID; upstream tables are kept. */\n readonly deleteCatalog: (id: string) => Effect.Effect<void, CatalogManagerError>;\n\n /**\n * Connects directly to the registered catalog. The caller needs network access.\n */\n readonly getIcebergCatalog: (\n id: string,\n ) => Effect.Effect<IcebergCatalog.Service, CatalogManagerError>;\n}\n\n/** Effect service tag for the catalog management API. */\nexport class CatalogManager extends Context.Service<CatalogManager, CatalogManagerService>()(\n \"@useairfoil/api/CatalogManager\",\n) {}\n","import { Data } from \"effect\";\n\n/** Error returned when ingestion fails. */\nexport class IngestorError extends Data.TaggedError(\"IngestorError\")<{\n readonly message: string;\n readonly cause?: unknown;\n}> {}\n","import {\n Any,\n type ArrowFlightClientService,\n FlightDataEncoder,\n FlightDescriptor,\n FlightDescriptor_DescriptorType,\n type PutResult,\n type RecordBatch,\n} from \"@useairfoil/flight\";\nimport { Deferred, Effect, Queue, Ref, Schema, Scope, Semaphore, Stream } from \"effect\";\n\nimport type { Ingestor, IngestorOptions } from \"./service\";\n\nimport { IngestorError } from \"./error\";\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nconst Acknowledgement = Schema.Struct({\n request_id: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nconst encodeJson = (value: unknown, message: string) =>\n Effect.try({\n try: () => textEncoder.encode(JSON.stringify(value)),\n catch: (cause) => new IngestorError({ message, cause }),\n });\n\nconst decodeAcknowledgement = (result: PutResult) =>\n Effect.try({\n try: () => JSON.parse(textDecoder.decode(result.appMetadata)),\n catch: (cause) =>\n new IngestorError({ message: \"Ingestion acknowledgement was not valid JSON\", cause }),\n }).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(Acknowledgement)),\n Effect.mapError((cause) =>\n cause instanceof IngestorError\n ? cause\n : new IngestorError({ message: \"Ingestion acknowledgement was malformed\", cause }),\n ),\n );\n\n/** Internal constructor used to inject a Flight client in tests. */\nexport const make = Effect.fnUntraced(function* (\n client: Pick<ArrowFlightClientService, \"doPut\">,\n options: IngestorOptions,\n): Effect.fn.Return<Ingestor, IngestorError, Scope.Scope> {\n const requests = yield* Queue.unbounded<ReturnType<typeof FlightDataEncoder.encodeSchema>>();\n const scope = yield* Scope.Scope;\n yield* Scope.addFinalizer(scope, Queue.shutdown(requests));\n\n const requestIterable = yield* Stream.toAsyncIterableEffect(Stream.fromQueue(requests));\n\n const pending = yield* Ref.make(new Map<number, Deferred.Deferred<void, IngestorError>>());\n const nextRequestId = yield* Ref.make(1);\n const schemaSent = yield* Ref.make(false);\n const terminalError = yield* Ref.make<IngestorError | undefined>(undefined);\n // Keeps the first schema and request registration ordered across concurrent pushes.\n const lock = yield* Semaphore.make(1);\n\n const failPending = (error: IngestorError) =>\n lock.withPermit(\n Effect.gen(function* () {\n yield* Ref.set(terminalError, error);\n const deferreds = yield* Ref.getAndSet(pending, new Map());\n yield* Effect.forEach(deferreds.values(), (deferred) => Deferred.fail(deferred, error), {\n discard: true,\n });\n }),\n );\n\n const acknowledge = Effect.fnUntraced(function* (result: PutResult) {\n const { request_id: requestId } = yield* decodeAcknowledgement(result);\n if (requestId === 0) return;\n\n const deferred = yield* Ref.modify(pending, (current) => {\n const found = current.get(requestId);\n if (found === undefined) return [undefined, current] as const;\n\n const updated = new Map(current);\n updated.delete(requestId);\n return [found, updated] as const;\n });\n\n if (deferred !== undefined) yield* Deferred.succeed(deferred, undefined);\n });\n\n const controller = new AbortController();\n const responseIterable = yield* Effect.try({\n try: () => client.doPut(requestIterable, { signal: controller.signal }),\n catch: (cause) => new IngestorError({ message: \"Failed to start ingestion stream\", cause }),\n });\n\n const consumeResponses = Stream.fromAsyncIterable(\n responseIterable,\n (cause) => new IngestorError({ message: \"Ingestion response stream failed\", cause }),\n ).pipe(Stream.runForEach(acknowledge));\n\n yield* Effect.forkScoped(\n consumeResponses.pipe(\n Effect.matchEffect({\n onFailure: failPending,\n onSuccess: () =>\n failPending(\n new IngestorError({ message: \"Ingestion response stream ended prematurely\" }),\n ),\n }),\n ),\n );\n // Finalizers run in reverse, so this cancels the call before the reader stops.\n // Stopping the reader waits for its pending read, which only ends with the call.\n yield* Scope.addFinalizer(\n scope,\n Effect.sync(() => controller.abort()),\n );\n\n const push = Effect.fnUntraced(function* (batch: RecordBatch) {\n const deferred = yield* lock.withPermit(\n Effect.gen(function* () {\n const terminal = yield* Ref.get(terminalError);\n if (terminal !== undefined) return yield* Effect.fail(terminal);\n\n if (!(yield* Ref.get(schemaSent))) {\n const appMetadata = yield* encodeJson(\n {\n request_id: 0,\n catalog: options.catalog,\n namespace: options.namespace,\n table_name: options.table,\n },\n \"Failed to encode ingestion schema metadata\",\n );\n const descriptor = FlightDescriptor.create({\n type: FlightDescriptor_DescriptorType.CMD,\n cmd: Any.encode(\n Any.create({ typeUrl: \"airfoil.v1.Ingest\", value: new Uint8Array() }),\n ).finish(),\n });\n const schema = yield* Effect.try({\n try: () =>\n FlightDataEncoder.encodeSchema(batch.schema, {\n flightDescriptor: descriptor,\n appMetadata,\n }),\n catch: (cause) =>\n new IngestorError({ message: \"Failed to encode ingestion schema\", cause }),\n });\n yield* Queue.offer(requests, schema);\n yield* Ref.set(schemaSent, true);\n }\n\n const requestId = yield* Ref.getAndUpdate(nextRequestId, (current) => current + 1);\n const appMetadata = yield* encodeJson(\n { request_id: requestId },\n \"Failed to encode ingestion batch metadata\",\n );\n const messages = yield* Effect.try({\n try: () =>\n FlightDataEncoder.encodeBatch(batch, {\n appMetadata: () => appMetadata,\n }),\n catch: (cause) =>\n new IngestorError({ message: \"Failed to encode ingestion batch\", cause }),\n });\n const acknowledgement = yield* Deferred.make<void, IngestorError>();\n yield* Ref.update(pending, (current) => new Map(current).set(requestId, acknowledgement));\n yield* Effect.forEach(messages, (message) => Queue.offer(requests, message), {\n discard: true,\n });\n return acknowledgement;\n }),\n );\n\n yield* Deferred.await(deferred);\n });\n\n return { push };\n});\n","import { Schema } from \"effect\";\n\n/** Configuration for an upstream Iceberg REST catalog. */\nexport const RestCatalogConfig = Schema.Struct({\n uri: Schema.String,\n warehouse: Schema.optional(Schema.String),\n properties: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n});\nexport type RestCatalogConfig = typeof RestCatalogConfig.Type;\n\n/** Request body accepted by `POST /catalogs`. */\nexport const CreateCatalogRequest = Schema.Struct({\n id: Schema.String,\n rest: RestCatalogConfig,\n});\nexport type CreateCatalogRequest = typeof CreateCatalogRequest.Type;\n\n/** A catalog managed by the Airfoil Storage Engine. */\nexport const Catalog = Schema.Struct({\n id: Schema.String,\n rest: RestCatalogConfig,\n});\nexport type Catalog = typeof Catalog.Type;\n","import { IcebergCatalog } from \"@useairfoil/effect-iceberg\";\nimport { ArrowFlightClient } from \"@useairfoil/flight\";\nimport { Config, Effect, Layer, Schema, Scope } from \"effect\";\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/http\";\n\nimport type { CatalogManagerOptions } from \"./config\";\n\nimport { make as makeIngestor } from \"../ingestor/make\";\nimport { CatalogManagerError } from \"./error\";\nimport { Catalog, type CreateCatalogRequest } from \"./schema\";\nimport { CatalogManager, type CatalogManagerService } from \"./service\";\n\nconst ErrorResponse = Schema.Struct({ error: Schema.String });\n\n/** Creates a CatalogManager service from concrete configuration. */\nexport const make = Effect.fnUntraced(function* (\n config: CatalogManagerOptions,\n): Effect.fn.Return<CatalogManagerService, never, HttpClient.HttpClient | Scope.Scope> {\n const engineUri = config.engineUri.replace(/\\/+$/, \"\");\n const flightClient = yield* ArrowFlightClient.make({\n host: (config.flightUri ?? engineUri).replace(/\\/+$/, \"\"),\n });\n\n const client = (yield* HttpClient.HttpClient).pipe(\n HttpClient.mapRequest(HttpClientRequest.prependUrl(engineUri)),\n HttpClient.mapRequest(HttpClientRequest.acceptJson),\n );\n const catalogPath = (id: string) => `/catalogs/${encodeURIComponent(id)}`;\n\n const execute = (request: HttpClientRequest.HttpClientRequest) =>\n client.execute(request).pipe(\n Effect.mapError(\n (cause) => new CatalogManagerError({ message: \"Catalog request failed\", cause }),\n ),\n Effect.flatMap((response) => {\n if (response.status >= 200 && response.status < 300) return Effect.succeed(response);\n\n return HttpClientResponse.schemaBodyJson(ErrorResponse)(response).pipe(\n Effect.map((body) => body.error),\n Effect.catch(() => Effect.succeed(`Catalog request failed with HTTP ${response.status}`)),\n Effect.flatMap((message) =>\n Effect.fail(new CatalogManagerError({ message, status: response.status })),\n ),\n );\n }),\n );\n\n const decodeCatalog = (request: HttpClientRequest.HttpClientRequest) =>\n Effect.scoped(\n execute(request).pipe(\n Effect.flatMap(HttpClientResponse.schemaBodyJson(Catalog)),\n Effect.mapError((cause) =>\n cause instanceof CatalogManagerError\n ? cause\n : new CatalogManagerError({\n message: \"Catalog response was not valid JSON\",\n cause,\n }),\n ),\n ),\n );\n\n const getCatalog = (id: string) => decodeCatalog(HttpClientRequest.get(catalogPath(id)));\n\n return CatalogManager.of({\n ingestor: (options) => makeIngestor(flightClient, options),\n\n createCatalog: (request: CreateCatalogRequest) =>\n Effect.scoped(\n HttpClientRequest.post(\"/catalogs\").pipe(\n HttpClientRequest.bodyJson(request),\n Effect.mapError(\n (cause) =>\n new CatalogManagerError({ message: \"Failed to encode catalog request\", cause }),\n ),\n Effect.flatMap(execute),\n Effect.asVoid,\n ),\n ),\n\n getCatalog,\n\n deleteCatalog: (id: string) =>\n Effect.scoped(execute(HttpClientRequest.delete(catalogPath(id))).pipe(Effect.as(undefined))),\n\n getIcebergCatalog: (id: string) =>\n getCatalog(id).pipe(\n Effect.map((catalog) =>\n IcebergCatalog.make({\n baseUrl: catalog.rest.uri,\n warehouse: catalog.rest.warehouse,\n fetch: (input, init) => {\n const headers = new Headers(init?.headers);\n for (const [key, value] of Object.entries(catalog.rest.properties ?? {})) {\n if (key.startsWith(\"header.\")) headers.set(key.slice(7), value);\n }\n const token = catalog.rest.properties?.token;\n if (token !== undefined && !headers.has(\"Authorization\")) {\n headers.set(\"Authorization\", `Bearer ${token}`);\n }\n return fetch(input, { ...init, headers });\n },\n }),\n ),\n ),\n });\n});\n\n/** Creates a CatalogManager layer from concrete configuration. */\nexport const layer = (\n config: CatalogManagerOptions,\n): Layer.Layer<CatalogManager, never, HttpClient.HttpClient> =>\n Layer.effect(CatalogManager)(make(config));\n\n/** Creates a CatalogManager layer from Effect Config values. */\nexport const layerConfig = (\n config: Config.Wrap<CatalogManagerOptions>,\n): Layer.Layer<CatalogManager, Config.ConfigError, HttpClient.HttpClient> =>\n Layer.effect(CatalogManager)(Config.unwrap(config).pipe(Effect.flatMap(make)));\n","import type { IcebergCatalog } from \"@useairfoil/effect-iceberg\";\nimport type { Effect } from \"effect\";\n\nimport { CatalogManagerError } from \"./error\";\nimport { CatalogManager, type CatalogManagerService } from \"./service\";\n\nexport type { CatalogManagerOptions } from \"./config\";\nexport { CatalogManagerError } from \"./error\";\nexport { layer, layerConfig, make } from \"./layer\";\nexport * from \"./schema\";\nexport { CatalogManager, type CatalogManagerService } from \"./service\";\n\ntype CatalogManagerFnParams<T extends keyof CatalogManagerService> = Parameters<\n CatalogManagerService[T]\n>;\n\n/** Opens a scoped ingestor for a Iceberg table. */\nexport const ingestor = (...args: CatalogManagerFnParams<\"ingestor\">) =>\n CatalogManager.use((service) => service.ingestor(...args));\n\n/** Creates and validates a catalog. */\nexport const createCatalog = (...args: CatalogManagerFnParams<\"createCatalog\">) =>\n CatalogManager.use((service) => service.createCatalog(...args));\n\n/** Gets a catalog by its bare ID. */\nexport const getCatalog = (...args: CatalogManagerFnParams<\"getCatalog\">) =>\n CatalogManager.use((service) => service.getCatalog(...args));\n\n/** Deletes a catalog by its bare ID. */\nexport const deleteCatalog = (...args: CatalogManagerFnParams<\"deleteCatalog\">) =>\n CatalogManager.use((service) => service.deleteCatalog(...args));\n\n/** Connects directly to the registered upstream catalog; the caller needs network access. */\nexport const getIcebergCatalog = (\n ...args: CatalogManagerFnParams<\"getIcebergCatalog\">\n): Effect.Effect<IcebergCatalog.Service, CatalogManagerError, CatalogManager> =>\n CatalogManager.use((service) => service.getIcebergCatalog(...args));\n"],"mappings":";;;;;;;AAGA,IAAa,sBAAb,cAAyC,KAAK,YAAY,qBAAqB,CAAC,CAI7E,CAAC;;;;AC4BJ,IAAa,iBAAb,cAAoC,QAAQ,QAA+C,CAAC,CAC1F,gCACF,CAAC,CAAC,CAAC;;;;AClCH,IAAa,gBAAb,cAAmC,KAAK,YAAY,eAAe,CAAC,CAGjE,CAAC;;;ACSJ,MAAM,cAAc,IAAI,YAAY;AACpC,MAAM,cAAc,IAAI,YAAY;AAEpC,MAAM,kBAAkB,OAAO,OAAO,EACpC,YAAY,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC,EAC/D,CAAC;AAED,MAAM,cAAc,OAAgB,YAClC,OAAO,IAAI;CACT,WAAW,YAAY,OAAO,KAAK,UAAU,KAAK,CAAC;CACnD,QAAQ,UAAU,IAAI,cAAc;EAAE;EAAS;CAAM,CAAC;AACxD,CAAC;AAEH,MAAM,yBAAyB,WAC7B,OAAO,IAAI;CACT,WAAW,KAAK,MAAM,YAAY,OAAO,OAAO,WAAW,CAAC;CAC5D,QAAQ,UACN,IAAI,cAAc;EAAE,SAAS;EAAgD;CAAM,CAAC;AACxF,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,CAAC;;AAG3D,MAAa,iBAAiB,GAAG,SAC/B,eAAe,KAAK,YAAY,QAAQ,cAAc,GAAG,IAAI,CAAC;;AAGhE,MAAa,cAAc,GAAG,SAC5B,eAAe,KAAK,YAAY,QAAQ,WAAW,GAAG,IAAI,CAAC;;AAG7D,MAAa,iBAAiB,GAAG,SAC/B,eAAe,KAAK,YAAY,QAAQ,cAAc,GAAG,IAAI,CAAC;;AAGhE,MAAa,qBACX,GAAG,SAEH,eAAe,KAAK,YAAY,QAAQ,kBAAkB,GAAG,IAAI,CAAC"}
@@ -0,0 +1,135 @@
1
+ import { Config, Context, Effect, Layer, Schema, Scope } from "effect";
2
+ import { IcebergCatalog } from "@useairfoil/effect-iceberg";
3
+ import { RecordBatch } from "@useairfoil/flight";
4
+ import { HttpClient } from "effect/http";
5
+ //#region src/ingestor/error.d.ts
6
+ declare const IngestorError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
7
+ readonly _tag: "IngestorError";
8
+ } & Readonly<A>;
9
+ /** Error returned when ingestion fails. */
10
+ declare class IngestorError extends IngestorError_base<{
11
+ readonly message: string;
12
+ readonly cause?: unknown;
13
+ }> {}
14
+ //#endregion
15
+ //#region src/ingestor/service.d.ts
16
+ /** The Iceberg table to ingest into. */
17
+ interface IngestorOptions {
18
+ readonly catalog: string;
19
+ readonly namespace: string[];
20
+ readonly table: string;
21
+ }
22
+ /** A scoped stream that sends batches to one Iceberg table. */
23
+ interface Ingestor {
24
+ /** Sends a batch and waits for its acknowledgement. */
25
+ readonly push: (batch: RecordBatch) => Effect.Effect<void, IngestorError>;
26
+ }
27
+ declare namespace index_d_exports$1 {
28
+ export { Ingestor, IngestorError, IngestorOptions };
29
+ }
30
+ //#endregion
31
+ //#region src/catalog-manager/error.d.ts
32
+ declare const CatalogManagerError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
33
+ readonly _tag: "CatalogManagerError";
34
+ } & Readonly<A>;
35
+ /** Error returned by the module. */
36
+ declare class CatalogManagerError extends CatalogManagerError_base<{
37
+ readonly message: string;
38
+ readonly status?: number;
39
+ readonly cause?: unknown;
40
+ }> {}
41
+ //#endregion
42
+ //#region src/catalog-manager/schema.d.ts
43
+ /** Configuration for an upstream Iceberg REST catalog. */
44
+ declare const RestCatalogConfig: Schema.Struct<{
45
+ readonly uri: Schema.String;
46
+ readonly warehouse: Schema.optional<Schema.String>;
47
+ readonly properties: Schema.optional<Schema.$Record<Schema.String, Schema.String>>;
48
+ }>;
49
+ type RestCatalogConfig = typeof RestCatalogConfig.Type;
50
+ /** Request body accepted by `POST /catalogs`. */
51
+ declare const CreateCatalogRequest: Schema.Struct<{
52
+ readonly id: Schema.String;
53
+ readonly rest: Schema.Struct<{
54
+ readonly uri: Schema.String;
55
+ readonly warehouse: Schema.optional<Schema.String>;
56
+ readonly properties: Schema.optional<Schema.$Record<Schema.String, Schema.String>>;
57
+ }>;
58
+ }>;
59
+ type CreateCatalogRequest = typeof CreateCatalogRequest.Type;
60
+ /** A catalog managed by the Airfoil Storage Engine. */
61
+ declare const Catalog: Schema.Struct<{
62
+ readonly id: Schema.String;
63
+ readonly rest: Schema.Struct<{
64
+ readonly uri: Schema.String;
65
+ readonly warehouse: Schema.optional<Schema.String>;
66
+ readonly properties: Schema.optional<Schema.$Record<Schema.String, Schema.String>>;
67
+ }>;
68
+ }>;
69
+ type Catalog = typeof Catalog.Type;
70
+ //#endregion
71
+ //#region src/catalog-manager/service.d.ts
72
+ /** Effect service for managing catalog registrations and ingestion. */
73
+ interface CatalogManagerService {
74
+ /** Opens a scoped ingestor for an Iceberg table. */
75
+ readonly ingestor: (options: IngestorOptions) => Effect.Effect<Ingestor, IngestorError, Scope.Scope>;
76
+ /** Creates and validates a catalog registration. */
77
+ readonly createCatalog: (request: CreateCatalogRequest) => Effect.Effect<void, CatalogManagerError>;
78
+ /** Gets a catalog by its bare ID. */
79
+ readonly getCatalog: (id: string) => Effect.Effect<Catalog, CatalogManagerError>;
80
+ /** Deletes a registration by its bare ID; upstream tables are kept. */
81
+ readonly deleteCatalog: (id: string) => Effect.Effect<void, CatalogManagerError>;
82
+ /**
83
+ * Connects directly to the registered catalog. The caller needs network access.
84
+ */
85
+ readonly getIcebergCatalog: (id: string) => Effect.Effect<IcebergCatalog.Service, CatalogManagerError>;
86
+ }
87
+ declare const CatalogManager_base: Context.ServiceClass<CatalogManager, "@useairfoil/api/CatalogManager", CatalogManagerService>;
88
+ /** Effect service tag for the catalog management API. */
89
+ declare class CatalogManager extends CatalogManager_base {}
90
+ //#endregion
91
+ //#region src/catalog-manager/config.d.ts
92
+ /** Configuration for the catalog management REST API. */
93
+ interface CatalogManagerOptions {
94
+ /**
95
+ * URI of the engine HTTP service.
96
+ * @example "http://localhost:7777"
97
+ */
98
+ readonly engineUri: string;
99
+ /** Arrow Flight endpoint. Defaults to engineUri. */
100
+ readonly flightUri?: string;
101
+ }
102
+ //#endregion
103
+ //#region src/catalog-manager/layer.d.ts
104
+ /** Creates a CatalogManager service from concrete configuration. */
105
+ declare const make: (config: CatalogManagerOptions) => Effect.Effect<CatalogManagerService, never, Scope.Scope | HttpClient.HttpClient>;
106
+ /** Creates a CatalogManager layer from concrete configuration. */
107
+ declare const layer: (config: CatalogManagerOptions) => Layer.Layer<CatalogManager, never, HttpClient.HttpClient>;
108
+ /** Creates a CatalogManager layer from Effect Config values. */
109
+ declare const layerConfig: (config: Config.Wrap<CatalogManagerOptions>) => Layer.Layer<CatalogManager, Config.ConfigError, HttpClient.HttpClient>;
110
+ declare namespace index_d_exports {
111
+ export { Catalog, CatalogManager, CatalogManagerError, CatalogManagerOptions, CatalogManagerService, CreateCatalogRequest, RestCatalogConfig, createCatalog, deleteCatalog, getCatalog, getIcebergCatalog, ingestor, layer, layerConfig, make };
112
+ }
113
+ type CatalogManagerFnParams<T extends keyof CatalogManagerService> = Parameters<CatalogManagerService[T]>;
114
+ /** Opens a scoped ingestor for a Iceberg table. */
115
+ declare const ingestor: (...args: CatalogManagerFnParams<"ingestor">) => Effect.Effect<Ingestor, IngestorError, CatalogManager | import("effect/Scope").Scope>;
116
+ /** Creates and validates a catalog. */
117
+ declare const createCatalog: (...args: CatalogManagerFnParams<"createCatalog">) => Effect.Effect<void, CatalogManagerError, CatalogManager>;
118
+ /** Gets a catalog by its bare ID. */
119
+ declare const getCatalog: (...args: CatalogManagerFnParams<"getCatalog">) => Effect.Effect<{
120
+ readonly id: string;
121
+ readonly rest: {
122
+ readonly uri: string;
123
+ readonly warehouse?: string | undefined;
124
+ readonly properties?: {
125
+ readonly [x: string]: string;
126
+ } | undefined;
127
+ };
128
+ }, CatalogManagerError, CatalogManager>;
129
+ /** Deletes a catalog by its bare ID. */
130
+ declare const deleteCatalog: (...args: CatalogManagerFnParams<"deleteCatalog">) => Effect.Effect<void, CatalogManagerError, CatalogManager>;
131
+ /** Connects directly to the registered upstream catalog; the caller needs network access. */
132
+ declare const getIcebergCatalog: (...args: CatalogManagerFnParams<"getIcebergCatalog">) => Effect.Effect<IcebergCatalog.Service, CatalogManagerError, CatalogManager>;
133
+ //#endregion
134
+ export { index_d_exports$1 as _, index_d_exports as a, layerConfig as c, CatalogManager as d, CatalogManagerService as f, CatalogManagerError as g, RestCatalogConfig as h, getIcebergCatalog as i, make as l, CreateCatalogRequest as m, deleteCatalog as n, ingestor as o, Catalog as p, getCatalog as r, layer as s, createCatalog as t, CatalogManagerOptions as u, IngestorError as v };
135
+ //# sourceMappingURL=index-0sDy5ImH.d.mts.map
@@ -0,0 +1,2 @@
1
+ import { _ as index_d_exports$1, a as index_d_exports, g as CatalogManagerError, v as IngestorError } from "./index-0sDy5ImH.mjs";
2
+ export { index_d_exports as CatalogManager, CatalogManagerError, index_d_exports$1 as Ingestor, IngestorError };
package/dist/index.mjs ADDED
@@ -0,0 +1,8 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { h as CatalogManagerError, p as IngestorError, t as catalog_manager_exports } from "./catalog-manager-CMWpf4i3.mjs";
3
+ //#region src/ingestor/index.ts
4
+ var ingestor_exports = /* @__PURE__ */ __exportAll({ IngestorError: () => IngestorError });
5
+ //#endregion
6
+ export { catalog_manager_exports as CatalogManager, CatalogManagerError, ingestor_exports as Ingestor, IngestorError };
7
+
8
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/ingestor/index.ts"],"sourcesContent":["export { IngestorError } from \"./error\";\nexport type { Ingestor, IngestorOptions } from \"./service\";\n"],"mappings":""}
@@ -0,0 +1,13 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __exportAll = (all, no_symbols) => {
4
+ let target = {};
5
+ for (var name in all) __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true
8
+ });
9
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
+ return target;
11
+ };
12
+ //#endregion
13
+ export { __exportAll as t };
package/package.json CHANGED
@@ -1,12 +1,43 @@
1
1
  {
2
2
  "name": "@useairfoil/api",
3
- "version": "0.0.1",
4
- "description": "",
5
- "license": "ISC",
6
- "author": "",
7
- "type": "commonjs",
8
- "main": "index.js",
3
+ "version": "0.5.0",
4
+ "repository": "useairfoil/connector-kit",
5
+ "files": [
6
+ "dist",
7
+ "src",
8
+ "README.md"
9
+ ],
10
+ "type": "module",
11
+ "main": "./dist/index.mjs",
12
+ "types": "./dist/index.d.mts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.mts",
16
+ "import": "./dist/index.mjs",
17
+ "default": "./dist/index.mjs"
18
+ }
19
+ },
20
+ "dependencies": {
21
+ "iceberg-js": "^1.0.0",
22
+ "@useairfoil/effect-iceberg": "0.0.8",
23
+ "@useairfoil/flight": "0.4.9"
24
+ },
25
+ "devDependencies": {
26
+ "@effect/vitest": "^4.1.0",
27
+ "@types/node": "^24.2.0",
28
+ "apache-arrow": "^21.2.0",
29
+ "effect": "^4.1.0",
30
+ "tsdown": "^0.23.0",
31
+ "vitest": "^5.0.3",
32
+ "@useairfoil/testing": "0.2.0"
33
+ },
34
+ "peerDependencies": {
35
+ "effect": "^4.1.0"
36
+ },
9
37
  "scripts": {
10
- "test": "echo \"Error: no test specified\" && exit 1"
38
+ "build": "tsdown",
39
+ "typecheck": "tsc --noEmit",
40
+ "test": "vitest",
41
+ "test:ci": "vitest run"
11
42
  }
12
- }
43
+ }
@@ -0,0 +1,10 @@
1
+ /** Configuration for the catalog management REST API. */
2
+ export interface CatalogManagerOptions {
3
+ /**
4
+ * URI of the engine HTTP service.
5
+ * @example "http://localhost:7777"
6
+ */
7
+ readonly engineUri: string;
8
+ /** Arrow Flight endpoint. Defaults to engineUri. */
9
+ readonly flightUri?: string;
10
+ }
@@ -0,0 +1,8 @@
1
+ import { Data } from "effect";
2
+
3
+ /** Error returned by the module. */
4
+ export class CatalogManagerError extends Data.TaggedError("CatalogManagerError")<{
5
+ readonly message: string;
6
+ readonly status?: number;
7
+ readonly cause?: unknown;
8
+ }> {}
@@ -0,0 +1,37 @@
1
+ import type { IcebergCatalog } from "@useairfoil/effect-iceberg";
2
+ import type { Effect } from "effect";
3
+
4
+ import { CatalogManagerError } from "./error";
5
+ import { CatalogManager, type CatalogManagerService } from "./service";
6
+
7
+ export type { CatalogManagerOptions } from "./config";
8
+ export { CatalogManagerError } from "./error";
9
+ export { layer, layerConfig, make } from "./layer";
10
+ export * from "./schema";
11
+ export { CatalogManager, type CatalogManagerService } from "./service";
12
+
13
+ type CatalogManagerFnParams<T extends keyof CatalogManagerService> = Parameters<
14
+ CatalogManagerService[T]
15
+ >;
16
+
17
+ /** Opens a scoped ingestor for a Iceberg table. */
18
+ export const ingestor = (...args: CatalogManagerFnParams<"ingestor">) =>
19
+ CatalogManager.use((service) => service.ingestor(...args));
20
+
21
+ /** Creates and validates a catalog. */
22
+ export const createCatalog = (...args: CatalogManagerFnParams<"createCatalog">) =>
23
+ CatalogManager.use((service) => service.createCatalog(...args));
24
+
25
+ /** Gets a catalog by its bare ID. */
26
+ export const getCatalog = (...args: CatalogManagerFnParams<"getCatalog">) =>
27
+ CatalogManager.use((service) => service.getCatalog(...args));
28
+
29
+ /** Deletes a catalog by its bare ID. */
30
+ export const deleteCatalog = (...args: CatalogManagerFnParams<"deleteCatalog">) =>
31
+ CatalogManager.use((service) => service.deleteCatalog(...args));
32
+
33
+ /** Connects directly to the registered upstream catalog; the caller needs network access. */
34
+ export const getIcebergCatalog = (
35
+ ...args: CatalogManagerFnParams<"getIcebergCatalog">
36
+ ): Effect.Effect<IcebergCatalog.Service, CatalogManagerError, CatalogManager> =>
37
+ CatalogManager.use((service) => service.getIcebergCatalog(...args));
@@ -0,0 +1,119 @@
1
+ import { IcebergCatalog } from "@useairfoil/effect-iceberg";
2
+ import { ArrowFlightClient } from "@useairfoil/flight";
3
+ import { Config, Effect, Layer, Schema, Scope } from "effect";
4
+ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
5
+
6
+ import type { CatalogManagerOptions } from "./config";
7
+
8
+ import { make as makeIngestor } from "../ingestor/make";
9
+ import { CatalogManagerError } from "./error";
10
+ import { Catalog, type CreateCatalogRequest } from "./schema";
11
+ import { CatalogManager, type CatalogManagerService } from "./service";
12
+
13
+ const ErrorResponse = Schema.Struct({ error: Schema.String });
14
+
15
+ /** Creates a CatalogManager service from concrete configuration. */
16
+ export const make = Effect.fnUntraced(function* (
17
+ config: CatalogManagerOptions,
18
+ ): Effect.fn.Return<CatalogManagerService, never, HttpClient.HttpClient | Scope.Scope> {
19
+ const engineUri = config.engineUri.replace(/\/+$/, "");
20
+ const flightClient = yield* ArrowFlightClient.make({
21
+ host: (config.flightUri ?? engineUri).replace(/\/+$/, ""),
22
+ });
23
+
24
+ const client = (yield* HttpClient.HttpClient).pipe(
25
+ HttpClient.mapRequest(HttpClientRequest.prependUrl(engineUri)),
26
+ HttpClient.mapRequest(HttpClientRequest.acceptJson),
27
+ );
28
+ const catalogPath = (id: string) => `/catalogs/${encodeURIComponent(id)}`;
29
+
30
+ const execute = (request: HttpClientRequest.HttpClientRequest) =>
31
+ client.execute(request).pipe(
32
+ Effect.mapError(
33
+ (cause) => new CatalogManagerError({ message: "Catalog request failed", cause }),
34
+ ),
35
+ Effect.flatMap((response) => {
36
+ if (response.status >= 200 && response.status < 300) return Effect.succeed(response);
37
+
38
+ return HttpClientResponse.schemaBodyJson(ErrorResponse)(response).pipe(
39
+ Effect.map((body) => body.error),
40
+ Effect.catch(() => Effect.succeed(`Catalog request failed with HTTP ${response.status}`)),
41
+ Effect.flatMap((message) =>
42
+ Effect.fail(new CatalogManagerError({ message, status: response.status })),
43
+ ),
44
+ );
45
+ }),
46
+ );
47
+
48
+ const decodeCatalog = (request: HttpClientRequest.HttpClientRequest) =>
49
+ Effect.scoped(
50
+ execute(request).pipe(
51
+ Effect.flatMap(HttpClientResponse.schemaBodyJson(Catalog)),
52
+ Effect.mapError((cause) =>
53
+ cause instanceof CatalogManagerError
54
+ ? cause
55
+ : new CatalogManagerError({
56
+ message: "Catalog response was not valid JSON",
57
+ cause,
58
+ }),
59
+ ),
60
+ ),
61
+ );
62
+
63
+ const getCatalog = (id: string) => decodeCatalog(HttpClientRequest.get(catalogPath(id)));
64
+
65
+ return CatalogManager.of({
66
+ ingestor: (options) => makeIngestor(flightClient, options),
67
+
68
+ createCatalog: (request: CreateCatalogRequest) =>
69
+ Effect.scoped(
70
+ HttpClientRequest.post("/catalogs").pipe(
71
+ HttpClientRequest.bodyJson(request),
72
+ Effect.mapError(
73
+ (cause) =>
74
+ new CatalogManagerError({ message: "Failed to encode catalog request", cause }),
75
+ ),
76
+ Effect.flatMap(execute),
77
+ Effect.asVoid,
78
+ ),
79
+ ),
80
+
81
+ getCatalog,
82
+
83
+ deleteCatalog: (id: string) =>
84
+ Effect.scoped(execute(HttpClientRequest.delete(catalogPath(id))).pipe(Effect.as(undefined))),
85
+
86
+ getIcebergCatalog: (id: string) =>
87
+ getCatalog(id).pipe(
88
+ Effect.map((catalog) =>
89
+ IcebergCatalog.make({
90
+ baseUrl: catalog.rest.uri,
91
+ warehouse: catalog.rest.warehouse,
92
+ fetch: (input, init) => {
93
+ const headers = new Headers(init?.headers);
94
+ for (const [key, value] of Object.entries(catalog.rest.properties ?? {})) {
95
+ if (key.startsWith("header.")) headers.set(key.slice(7), value);
96
+ }
97
+ const token = catalog.rest.properties?.token;
98
+ if (token !== undefined && !headers.has("Authorization")) {
99
+ headers.set("Authorization", `Bearer ${token}`);
100
+ }
101
+ return fetch(input, { ...init, headers });
102
+ },
103
+ }),
104
+ ),
105
+ ),
106
+ });
107
+ });
108
+
109
+ /** Creates a CatalogManager layer from concrete configuration. */
110
+ export const layer = (
111
+ config: CatalogManagerOptions,
112
+ ): Layer.Layer<CatalogManager, never, HttpClient.HttpClient> =>
113
+ Layer.effect(CatalogManager)(make(config));
114
+
115
+ /** Creates a CatalogManager layer from Effect Config values. */
116
+ export const layerConfig = (
117
+ config: Config.Wrap<CatalogManagerOptions>,
118
+ ): Layer.Layer<CatalogManager, Config.ConfigError, HttpClient.HttpClient> =>
119
+ Layer.effect(CatalogManager)(Config.unwrap(config).pipe(Effect.flatMap(make)));
@@ -0,0 +1,23 @@
1
+ import { Schema } from "effect";
2
+
3
+ /** Configuration for an upstream Iceberg REST catalog. */
4
+ export const RestCatalogConfig = Schema.Struct({
5
+ uri: Schema.String,
6
+ warehouse: Schema.optional(Schema.String),
7
+ properties: Schema.optional(Schema.Record(Schema.String, Schema.String)),
8
+ });
9
+ export type RestCatalogConfig = typeof RestCatalogConfig.Type;
10
+
11
+ /** Request body accepted by `POST /catalogs`. */
12
+ export const CreateCatalogRequest = Schema.Struct({
13
+ id: Schema.String,
14
+ rest: RestCatalogConfig,
15
+ });
16
+ export type CreateCatalogRequest = typeof CreateCatalogRequest.Type;
17
+
18
+ /** A catalog managed by the Airfoil Storage Engine. */
19
+ export const Catalog = Schema.Struct({
20
+ id: Schema.String,
21
+ rest: RestCatalogConfig,
22
+ });
23
+ export type Catalog = typeof Catalog.Type;
@@ -0,0 +1,38 @@
1
+ import type { IcebergCatalog } from "@useairfoil/effect-iceberg";
2
+
3
+ import { Context, type Effect, type Scope } from "effect";
4
+
5
+ import type { Ingestor, IngestorError, IngestorOptions } from "../ingestor";
6
+ import type { CatalogManagerError } from "./error";
7
+ import type { Catalog, CreateCatalogRequest } from "./schema";
8
+
9
+ /** Effect service for managing catalog registrations and ingestion. */
10
+ export interface CatalogManagerService {
11
+ /** Opens a scoped ingestor for an Iceberg table. */
12
+ readonly ingestor: (
13
+ options: IngestorOptions,
14
+ ) => Effect.Effect<Ingestor, IngestorError, Scope.Scope>;
15
+
16
+ /** Creates and validates a catalog registration. */
17
+ readonly createCatalog: (
18
+ request: CreateCatalogRequest,
19
+ ) => Effect.Effect<void, CatalogManagerError>;
20
+
21
+ /** Gets a catalog by its bare ID. */
22
+ readonly getCatalog: (id: string) => Effect.Effect<Catalog, CatalogManagerError>;
23
+
24
+ /** Deletes a registration by its bare ID; upstream tables are kept. */
25
+ readonly deleteCatalog: (id: string) => Effect.Effect<void, CatalogManagerError>;
26
+
27
+ /**
28
+ * Connects directly to the registered catalog. The caller needs network access.
29
+ */
30
+ readonly getIcebergCatalog: (
31
+ id: string,
32
+ ) => Effect.Effect<IcebergCatalog.Service, CatalogManagerError>;
33
+ }
34
+
35
+ /** Effect service tag for the catalog management API. */
36
+ export class CatalogManager extends Context.Service<CatalogManager, CatalogManagerService>()(
37
+ "@useairfoil/api/CatalogManager",
38
+ ) {}
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * as CatalogManager from "./catalog-manager";
2
+ export { CatalogManagerError } from "./catalog-manager";
3
+ export * as Ingestor from "./ingestor";
4
+ export { IngestorError } from "./ingestor";
@@ -0,0 +1,7 @@
1
+ import { Data } from "effect";
2
+
3
+ /** Error returned when ingestion fails. */
4
+ export class IngestorError extends Data.TaggedError("IngestorError")<{
5
+ readonly message: string;
6
+ readonly cause?: unknown;
7
+ }> {}
@@ -0,0 +1,2 @@
1
+ export { IngestorError } from "./error";
2
+ export type { Ingestor, IngestorOptions } from "./service";
@@ -0,0 +1,178 @@
1
+ import {
2
+ Any,
3
+ type ArrowFlightClientService,
4
+ FlightDataEncoder,
5
+ FlightDescriptor,
6
+ FlightDescriptor_DescriptorType,
7
+ type PutResult,
8
+ type RecordBatch,
9
+ } from "@useairfoil/flight";
10
+ import { Deferred, Effect, Queue, Ref, Schema, Scope, Semaphore, Stream } from "effect";
11
+
12
+ import type { Ingestor, IngestorOptions } from "./service";
13
+
14
+ import { IngestorError } from "./error";
15
+
16
+ const textEncoder = new TextEncoder();
17
+ const textDecoder = new TextDecoder();
18
+
19
+ const Acknowledgement = Schema.Struct({
20
+ request_id: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
21
+ });
22
+
23
+ const encodeJson = (value: unknown, message: string) =>
24
+ Effect.try({
25
+ try: () => textEncoder.encode(JSON.stringify(value)),
26
+ catch: (cause) => new IngestorError({ message, cause }),
27
+ });
28
+
29
+ const decodeAcknowledgement = (result: PutResult) =>
30
+ Effect.try({
31
+ try: () => JSON.parse(textDecoder.decode(result.appMetadata)),
32
+ catch: (cause) =>
33
+ new IngestorError({ message: "Ingestion acknowledgement was not valid JSON", cause }),
34
+ }).pipe(
35
+ Effect.flatMap(Schema.decodeUnknownEffect(Acknowledgement)),
36
+ Effect.mapError((cause) =>
37
+ cause instanceof IngestorError
38
+ ? cause
39
+ : new IngestorError({ message: "Ingestion acknowledgement was malformed", cause }),
40
+ ),
41
+ );
42
+
43
+ /** Internal constructor used to inject a Flight client in tests. */
44
+ export const make = Effect.fnUntraced(function* (
45
+ client: Pick<ArrowFlightClientService, "doPut">,
46
+ options: IngestorOptions,
47
+ ): Effect.fn.Return<Ingestor, IngestorError, Scope.Scope> {
48
+ const requests = yield* Queue.unbounded<ReturnType<typeof FlightDataEncoder.encodeSchema>>();
49
+ const scope = yield* Scope.Scope;
50
+ yield* Scope.addFinalizer(scope, Queue.shutdown(requests));
51
+
52
+ const requestIterable = yield* Stream.toAsyncIterableEffect(Stream.fromQueue(requests));
53
+
54
+ const pending = yield* Ref.make(new Map<number, Deferred.Deferred<void, IngestorError>>());
55
+ const nextRequestId = yield* Ref.make(1);
56
+ const schemaSent = yield* Ref.make(false);
57
+ const terminalError = yield* Ref.make<IngestorError | undefined>(undefined);
58
+ // Keeps the first schema and request registration ordered across concurrent pushes.
59
+ const lock = yield* Semaphore.make(1);
60
+
61
+ const failPending = (error: IngestorError) =>
62
+ lock.withPermit(
63
+ Effect.gen(function* () {
64
+ yield* Ref.set(terminalError, error);
65
+ const deferreds = yield* Ref.getAndSet(pending, new Map());
66
+ yield* Effect.forEach(deferreds.values(), (deferred) => Deferred.fail(deferred, error), {
67
+ discard: true,
68
+ });
69
+ }),
70
+ );
71
+
72
+ const acknowledge = Effect.fnUntraced(function* (result: PutResult) {
73
+ const { request_id: requestId } = yield* decodeAcknowledgement(result);
74
+ if (requestId === 0) return;
75
+
76
+ const deferred = yield* Ref.modify(pending, (current) => {
77
+ const found = current.get(requestId);
78
+ if (found === undefined) return [undefined, current] as const;
79
+
80
+ const updated = new Map(current);
81
+ updated.delete(requestId);
82
+ return [found, updated] as const;
83
+ });
84
+
85
+ if (deferred !== undefined) yield* Deferred.succeed(deferred, undefined);
86
+ });
87
+
88
+ const controller = new AbortController();
89
+ const responseIterable = yield* Effect.try({
90
+ try: () => client.doPut(requestIterable, { signal: controller.signal }),
91
+ catch: (cause) => new IngestorError({ message: "Failed to start ingestion stream", cause }),
92
+ });
93
+
94
+ const consumeResponses = Stream.fromAsyncIterable(
95
+ responseIterable,
96
+ (cause) => new IngestorError({ message: "Ingestion response stream failed", cause }),
97
+ ).pipe(Stream.runForEach(acknowledge));
98
+
99
+ yield* Effect.forkScoped(
100
+ consumeResponses.pipe(
101
+ Effect.matchEffect({
102
+ onFailure: failPending,
103
+ onSuccess: () =>
104
+ failPending(
105
+ new IngestorError({ message: "Ingestion response stream ended prematurely" }),
106
+ ),
107
+ }),
108
+ ),
109
+ );
110
+ // Finalizers run in reverse, so this cancels the call before the reader stops.
111
+ // Stopping the reader waits for its pending read, which only ends with the call.
112
+ yield* Scope.addFinalizer(
113
+ scope,
114
+ Effect.sync(() => controller.abort()),
115
+ );
116
+
117
+ const push = Effect.fnUntraced(function* (batch: RecordBatch) {
118
+ const deferred = yield* lock.withPermit(
119
+ Effect.gen(function* () {
120
+ const terminal = yield* Ref.get(terminalError);
121
+ if (terminal !== undefined) return yield* Effect.fail(terminal);
122
+
123
+ if (!(yield* Ref.get(schemaSent))) {
124
+ const appMetadata = yield* encodeJson(
125
+ {
126
+ request_id: 0,
127
+ catalog: options.catalog,
128
+ namespace: options.namespace,
129
+ table_name: options.table,
130
+ },
131
+ "Failed to encode ingestion schema metadata",
132
+ );
133
+ const descriptor = FlightDescriptor.create({
134
+ type: FlightDescriptor_DescriptorType.CMD,
135
+ cmd: Any.encode(
136
+ Any.create({ typeUrl: "airfoil.v1.Ingest", value: new Uint8Array() }),
137
+ ).finish(),
138
+ });
139
+ const schema = yield* Effect.try({
140
+ try: () =>
141
+ FlightDataEncoder.encodeSchema(batch.schema, {
142
+ flightDescriptor: descriptor,
143
+ appMetadata,
144
+ }),
145
+ catch: (cause) =>
146
+ new IngestorError({ message: "Failed to encode ingestion schema", cause }),
147
+ });
148
+ yield* Queue.offer(requests, schema);
149
+ yield* Ref.set(schemaSent, true);
150
+ }
151
+
152
+ const requestId = yield* Ref.getAndUpdate(nextRequestId, (current) => current + 1);
153
+ const appMetadata = yield* encodeJson(
154
+ { request_id: requestId },
155
+ "Failed to encode ingestion batch metadata",
156
+ );
157
+ const messages = yield* Effect.try({
158
+ try: () =>
159
+ FlightDataEncoder.encodeBatch(batch, {
160
+ appMetadata: () => appMetadata,
161
+ }),
162
+ catch: (cause) =>
163
+ new IngestorError({ message: "Failed to encode ingestion batch", cause }),
164
+ });
165
+ const acknowledgement = yield* Deferred.make<void, IngestorError>();
166
+ yield* Ref.update(pending, (current) => new Map(current).set(requestId, acknowledgement));
167
+ yield* Effect.forEach(messages, (message) => Queue.offer(requests, message), {
168
+ discard: true,
169
+ });
170
+ return acknowledgement;
171
+ }),
172
+ );
173
+
174
+ yield* Deferred.await(deferred);
175
+ });
176
+
177
+ return { push };
178
+ });
@@ -0,0 +1,17 @@
1
+ import type { RecordBatch } from "@useairfoil/flight";
2
+ import type { Effect } from "effect";
3
+
4
+ import type { IngestorError } from "./error";
5
+
6
+ /** The Iceberg table to ingest into. */
7
+ export interface IngestorOptions {
8
+ readonly catalog: string;
9
+ readonly namespace: string[];
10
+ readonly table: string;
11
+ }
12
+
13
+ /** A scoped stream that sends batches to one Iceberg table. */
14
+ export interface Ingestor {
15
+ /** Sends a batch and waits for its acknowledgement. */
16
+ readonly push: (batch: RecordBatch) => Effect.Effect<void, IngestorError>;
17
+ }