|
| 1 | +import { RecordBatchReader, tableFromIPC } from 'apache-arrow' |
| 2 | +import { create, toBinary } from "@bufbuild/protobuf" |
| 3 | +import { anyPack, AnySchema } from "@bufbuild/protobuf/wkt" |
| 4 | +import { type Client, createClient, type Transport as ConnectTransport } from "@connectrpc/connect" |
| 5 | +import * as Context from "effect/Context" |
| 6 | +import * as Effect from "effect/Effect" |
| 7 | +import * as Layer from "effect/Layer" |
| 8 | +import * as Schema from "effect/Schema" |
| 9 | +import * as Stream from "effect/Stream" |
| 10 | +import { |
| 11 | + type FlightData, |
| 12 | + FlightDescriptor_DescriptorType, |
| 13 | + FlightDescriptorSchema, |
| 14 | + FlightService |
| 15 | +} from "./proto/Flight_pb.ts" |
| 16 | +import { CommandStatementQuerySchema } from "./proto/FlightSql_pb.ts" |
| 17 | + |
| 18 | +/** |
| 19 | + * A service which abstracts the underlying transport for a given client. |
| 20 | + * |
| 21 | + * A transport implements a protocol, such as Connect or gRPC-web, and allows |
| 22 | + * for the concrete clients to be independent of the protocol. |
| 23 | + */ |
| 24 | +export class Transport extends Context.Tag("@edgeandnode/amp/Transport")< |
| 25 | + Transport, |
| 26 | + ConnectTransport |
| 27 | +>() {} |
| 28 | + |
| 29 | +/** |
| 30 | + * Represents the possible errors that can occur when executing an Arrow Flight |
| 31 | + * query. |
| 32 | + */ |
| 33 | +export type ArrowFlightQueryError = |
| 34 | + | RpcError |
| 35 | + | NoEndpointsError |
| 36 | + | MultipleEndpointsError |
| 37 | + | TicketNotFoundError |
| 38 | + |
| 39 | +/** |
| 40 | + * Represents an Arrow Flight RPC request that failed. |
| 41 | + */ |
| 42 | +export class RpcError extends Schema.TaggedError<RpcError>( |
| 43 | + "@edgeandnode/amp/RpcError" |
| 44 | +)("RpcError", { |
| 45 | + method: Schema.String, |
| 46 | + /** |
| 47 | + * The underlying reason for the failed RPC request. |
| 48 | + */ |
| 49 | + cause: Schema.Defect |
| 50 | +}) {} |
| 51 | + |
| 52 | +/** |
| 53 | + * Represents an error that occurred as a result of a `FlightInfo` request |
| 54 | + * returning an empty list of endpoints from which data can be acquired. |
| 55 | + */ |
| 56 | +export class NoEndpointsError extends Schema.TaggedError<NoEndpointsError>( |
| 57 | + "@edgeandnode/amp/NoEndpointsError" |
| 58 | +)("NoEndpointsError", { |
| 59 | + /** |
| 60 | + * The SQL query that was requested. |
| 61 | + */ |
| 62 | + query: Schema.String |
| 63 | +}) {} |
| 64 | + |
| 65 | +// TODO: determine if this is _really_ a logical error case |
| 66 | +/** |
| 67 | + * Represents an error that occured as a result of a `FlightInfo` request |
| 68 | + * returning multiple endpoints from which data can be acquired. |
| 69 | + * |
| 70 | + * For Amp queries, there should only ever be **one** authoritative source |
| 71 | + * of data. |
| 72 | + */ |
| 73 | +export class MultipleEndpointsError extends Schema.TaggedError<MultipleEndpointsError>( |
| 74 | + "@edgeandnode/amp/MultipleEndpointsError" |
| 75 | +)("MultipleEndpointsError", { |
| 76 | + /** |
| 77 | + * The SQL query that was requested. |
| 78 | + */ |
| 79 | + query: Schema.String |
| 80 | +}) {} |
| 81 | + |
| 82 | +/** |
| 83 | + * Represents an error that occurred as a result of a `FlightInfo` request |
| 84 | + * whose endpoint did not have a ticket. |
| 85 | + */ |
| 86 | +export class TicketNotFoundError extends Schema.TaggedError<TicketNotFoundError>( |
| 87 | + "@edgeandnode/amp/TicketNotFoundError" |
| 88 | +)("TicketNotFoundError", { |
| 89 | + /** |
| 90 | + * The SQL query that was requested. |
| 91 | + */ |
| 92 | + query: Schema.String |
| 93 | +}) {} |
| 94 | + |
| 95 | +/** |
| 96 | + * A service which can be used to execute queries against an Arrow Flight API. |
| 97 | + */ |
| 98 | +export class ArrowFlight extends Context.Tag("@edgeandnode/amp/ArrowFlight")<ArrowFlight, { |
| 99 | + /** |
| 100 | + * The Connect `Client` that will be used to execute Arrow Flight queries. |
| 101 | + */ |
| 102 | + readonly client: Client<typeof FlightService> |
| 103 | +}>() {} |
| 104 | + |
| 105 | +const make = Effect.gen(function*() { |
| 106 | + const transport = yield* Transport |
| 107 | + const client = createClient(FlightService, transport) |
| 108 | + |
| 109 | + const request = Effect.fn("ArrowFlight.request")(function*(query: string) { |
| 110 | + const cmd = create(CommandStatementQuerySchema, { query }) |
| 111 | + const any = anyPack(CommandStatementQuerySchema, cmd) |
| 112 | + const desc = create(FlightDescriptorSchema, { |
| 113 | + type: FlightDescriptor_DescriptorType.CMD, |
| 114 | + cmd: toBinary(AnySchema, any) |
| 115 | + }) |
| 116 | + |
| 117 | + const flightInfo = yield* Effect.tryPromise({ |
| 118 | + try: (signal) => client.getFlightInfo(desc, { signal }), |
| 119 | + catch: (cause) => new RpcError({ cause, method: "getFlightInfo" }) |
| 120 | + }) |
| 121 | + |
| 122 | + if (flightInfo.endpoint.length !== 1) { |
| 123 | + return yield* flightInfo.endpoint.length <= 0 |
| 124 | + ? new NoEndpointsError({ query }) |
| 125 | + : new MultipleEndpointsError({ query }) |
| 126 | + } |
| 127 | + |
| 128 | + const { ticket } = flightInfo.endpoint[0]! |
| 129 | + |
| 130 | + if (ticket === undefined) { |
| 131 | + return yield* new TicketNotFoundError({ query }) |
| 132 | + } |
| 133 | + |
| 134 | + const flightDataStream = Stream.unwrapScoped(Effect.gen(function*() { |
| 135 | + const controller = yield* Effect.acquireRelease( |
| 136 | + Effect.sync(() => new AbortController()), |
| 137 | + (controller) => Effect.sync(() => controller.abort()) |
| 138 | + ) |
| 139 | + return Stream.fromAsyncIterable( |
| 140 | + client.doGet(ticket, { signal: controller.signal }), |
| 141 | + (cause) => new RpcError({ cause, method: "doGet" }) |
| 142 | + ) |
| 143 | + })).pipe(Stream.map(flightDataToIPC)) |
| 144 | + |
| 145 | + yield* flightDataStream.pipe( |
| 146 | + Stream.runForEach((table) => |
| 147 | + Effect.sync(() => { |
| 148 | + console.dir(table, { depth: null, colors: true }) |
| 149 | + }) |
| 150 | + ) |
| 151 | + ) |
| 152 | + }) |
| 153 | + |
| 154 | + // Test code |
| 155 | + yield* Effect.orDie(request("SELECT * FROM intTable")) |
| 156 | + |
| 157 | + return { |
| 158 | + client |
| 159 | + } as const |
| 160 | +}) |
| 161 | + |
| 162 | +/** |
| 163 | + * A layer which constructs a concrete implementation of an `ArrowFlight` |
| 164 | + * service and depends upon some implementation of a `Transport`. |
| 165 | + */ |
| 166 | +export const layer: Layer.Layer<ArrowFlight, never, Transport> = Layer.effect(ArrowFlight, make) |
| 167 | + |
| 168 | +/** |
| 169 | + * Converts a `FlightData` payload into Apache Arrow IPC format. |
| 170 | + */ |
| 171 | +const flightDataToIPC = (flightData: FlightData): Uint8Array => { |
| 172 | + // Arrow IPC Stream format requires: |
| 173 | + // 1. Continuation indicator (4 bytes): 0xFFFFFFFF |
| 174 | + // 2. Metadata length (4 bytes, little-endian) |
| 175 | + // 3. Metadata (padded to 8-byte boundary) |
| 176 | + // 4. Body data (already 8-byte aligned) |
| 177 | + |
| 178 | + const continuationToken = new Uint8Array([0xFF, 0xFF, 0xFF, 0xFF]) |
| 179 | + |
| 180 | + // Get metadata length |
| 181 | + const metadataLength = flightData.dataHeader.length |
| 182 | + const metadataLengthBytes = new Uint8Array(4) |
| 183 | + new DataView(metadataLengthBytes.buffer).setUint32(0, metadataLength, true) // little-endian |
| 184 | + |
| 185 | + // Calculate padding needed to align to 8 bytes |
| 186 | + const paddingSize = (8 - ((8 + metadataLength) % 8)) % 8 |
| 187 | + const padding = new Uint8Array(paddingSize) |
| 188 | + |
| 189 | + // Combine all parts |
| 190 | + const totalLength = continuationToken.length + // 4 bytes |
| 191 | + metadataLengthBytes.length + // 4 bytes |
| 192 | + metadataLength + // variable |
| 193 | + paddingSize + // 0-7 bytes |
| 194 | + flightData.dataBody.length // variable |
| 195 | + |
| 196 | + const ipcMessage = new Uint8Array(totalLength) |
| 197 | + let offset = 0 |
| 198 | + |
| 199 | + // Write continuation token |
| 200 | + ipcMessage.set(continuationToken, offset) |
| 201 | + offset += continuationToken.length |
| 202 | + |
| 203 | + // Write metadata length |
| 204 | + ipcMessage.set(metadataLengthBytes, offset) |
| 205 | + offset += metadataLengthBytes.length |
| 206 | + |
| 207 | + // Write metadata |
| 208 | + ipcMessage.set(flightData.dataHeader, offset) |
| 209 | + offset += metadataLength |
| 210 | + |
| 211 | + // Write padding |
| 212 | + ipcMessage.set(padding, offset) |
| 213 | + offset += paddingSize |
| 214 | + |
| 215 | + // Write body |
| 216 | + ipcMessage.set(flightData.dataBody, offset) |
| 217 | + |
| 218 | + return ipcMessage |
| 219 | +} |
0 commit comments