Repository navigation
Expand file tree
/
Copy pathclient-runtime.ts
More file actions
694 lines (650 loc) · 22.2 KB
/
Copy pathclient-runtime.ts
File metadata and controls
694 lines (650 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
import * as HttpClient from "@effect/platform/HttpClient";
import type * as HttpBody from "@effect/platform/HttpBody";
import type * as HttpClientError from "@effect/platform/HttpClientError";
import * as HttpClientRequest from "@effect/platform/HttpClientRequest";
import type * as HttpClientResponse from "@effect/platform/HttpClientResponse";
import { Data, Effect, Option, ParseResult, Schema, Stream } from "effect";
type AnySchema = Schema.Schema.AnyNoContext;
export interface GeneratedClientOptions {
readonly baseUrl: string | URL;
readonly headers?: Readonly<Record<string, string>>;
readonly maxFrameBytes?: number;
}
export interface GeneratedClientConnection {
readonly baseUrl: URL;
readonly headers: Readonly<Record<string, string>>;
readonly maxFrameBytes: number;
}
interface RequestOperationDescriptor {
readonly operationId: string;
readonly method:
| "GET"
| "POST"
| "PUT"
| "PATCH"
| "DELETE"
| "HEAD"
| "OPTIONS";
readonly path: string;
readonly pathParameters?: AnySchema;
readonly queryParameters?: AnySchema;
readonly headers?: AnySchema;
readonly payload?: AnySchema;
readonly payloadRequired?: boolean;
readonly payloadMediaType?: string;
readonly errors: ReadonlyArray<{
readonly status: number;
readonly schema: AnySchema;
readonly mediaType?: string;
}>;
}
export interface HttpOperationDescriptor extends RequestOperationDescriptor {
readonly transport: "http";
readonly successes: ReadonlyArray<{
readonly status: number;
readonly schema: AnySchema;
readonly mediaType?: string;
}>;
}
export interface StreamOperationDescriptor extends RequestOperationDescriptor {
readonly transport: "sse" | "ndjson";
readonly mediaType: string;
readonly responseStatus: number;
readonly eventSchema: AnySchema;
readonly termination:
| { readonly type: "sentinel"; readonly value: string }
| { readonly type: "eof" }
| { readonly type: "long-lived" };
readonly reconnect:
| { readonly type: "none" }
| { readonly type: "last-event-id" };
}
type SchemaType<A> = A extends AnySchema ? Schema.Schema.Type<A> : never;
type ErrorBody<A extends RequestOperationDescriptor> = SchemaType<
A["errors"][number]["schema"]
>;
type FieldIfPresent<
A,
Key extends PropertyKey,
OutputKey extends PropertyKey
> = Key extends keyof A
? A[Key] extends AnySchema
? { readonly [K in OutputKey]: SchemaType<A[Key]> }
: Record<never, never>
: Record<never, never>;
type PayloadIfPresent<A> = "payload" extends keyof A
? A["payload"] extends AnySchema
? A extends { readonly payloadRequired: false }
? { readonly payload?: SchemaType<A["payload"]> }
: { readonly payload: SchemaType<A["payload"]> }
: Record<never, never>
: Record<never, never>;
export type OperationInput<A extends RequestOperationDescriptor> =
FieldIfPresent<A, "pathParameters", "path"> &
FieldIfPresent<A, "queryParameters", "urlParams"> &
FieldIfPresent<A, "headers", "headers"> &
PayloadIfPresent<A>;
export type StreamOperationInput<A extends StreamOperationDescriptor> =
OperationInput<A>;
export type HttpOperationInput<A extends HttpOperationDescriptor> =
OperationInput<A>;
export type StreamOperationEvent<A extends StreamOperationDescriptor> =
Exclude<SchemaType<A["eventSchema"]>, ErrorBody<A>>;
export interface GeneratedStreamResponse<
Event,
Error,
> {
readonly status: number;
readonly headers: HttpClientResponse.HttpClientResponse["headers"];
readonly events: Stream.Stream<Event, Error>;
}
export class GeneratedClientInputError extends Data.TaggedError(
"GeneratedClientInputError"
)<{
readonly operationId: string;
readonly location: "path" | "query" | "headers" | "payload";
readonly cause: ParseResult.ParseError;
}> {}
export class GeneratedClientTransportError extends Data.TaggedError(
"GeneratedClientTransportError"
)<{
readonly operationId: string;
readonly cause:
| HttpClientError.HttpClientError
| HttpBody.HttpBodyError
| Error;
}> {}
export class GeneratedClientRemoteError<
Body = unknown
> extends Data.TaggedError("GeneratedClientRemoteError")<{
readonly operationId: string;
readonly status: number;
readonly headers: HttpClientResponse.HttpClientResponse["headers"];
readonly body: Body;
}> {}
export class GeneratedClientInvalidResponseError extends Data.TaggedError(
"GeneratedClientInvalidResponseError"
)<{
readonly operationId: string;
readonly status: number;
readonly message: string;
readonly cause: Option.Option<unknown>;
}> {}
export class GeneratedClientIncompleteStreamError extends Data.TaggedError(
"GeneratedClientIncompleteStreamError"
)<{
readonly operationId: string;
readonly termination: "sentinel" | "long-lived";
}> {}
export type GeneratedClientError<RemoteBody = unknown> =
| GeneratedClientInputError
| GeneratedClientTransportError
| GeneratedClientRemoteError<RemoteBody>
| GeneratedClientInvalidResponseError
| GeneratedClientIncompleteStreamError;
export type StreamOperationError<A extends StreamOperationDescriptor> =
GeneratedClientError<ErrorBody<A>>;
export type HttpOperationSuccess<A extends HttpOperationDescriptor> =
SchemaType<A["successes"][number]["schema"]>;
export type HttpOperationError<A extends HttpOperationDescriptor> = Exclude<
GeneratedClientError<ErrorBody<A>>,
GeneratedClientIncompleteStreamError
>;
export const makeGeneratedClientConnection = (
options: GeneratedClientOptions
): GeneratedClientConnection => ({
baseUrl: new URL(options.baseUrl),
headers: options.headers ?? {},
maxFrameBytes: options.maxFrameBytes ?? 1024 * 1024,
});
const encode = (
operationId: string,
location: GeneratedClientInputError["location"],
schema: AnySchema,
value: unknown
): Effect.Effect<unknown, GeneratedClientInputError> =>
Schema.encodeUnknown(schema)(value).pipe(
Effect.mapError(
(cause) => new GeneratedClientInputError({ operationId, location, cause })
)
);
const record = (value: unknown): Readonly<Record<string, unknown>> =>
typeof value === "object" && value !== null && !Array.isArray(value)
? (value as Readonly<Record<string, unknown>>)
: {};
const scalar = (value: unknown): string =>
typeof value === "string" ? value : String(value);
const requestFor = <A extends RequestOperationDescriptor>(
operation: A,
connection: GeneratedClientConnection,
input: OperationInput<A>
): Effect.Effect<
HttpClientRequest.HttpClientRequest,
GeneratedClientInputError | GeneratedClientTransportError
> =>
Effect.gen(function* () {
const raw = input as Readonly<Record<string, unknown>>;
let pathname = operation.path;
if (operation.pathParameters !== undefined) {
const encoded = record(
yield* encode(
operation.operationId,
"path",
operation.pathParameters,
raw.path
)
);
for (const [name, value] of Object.entries(encoded))
pathname = pathname.replaceAll(
`{${name}}`,
encodeURIComponent(scalar(value))
);
}
if (/\{[^{}]+\}/.test(pathname)) {
return yield* new GeneratedClientTransportError({
operationId: operation.operationId,
cause: new Error(`Unresolved path parameter in ${pathname}`),
});
}
const baseUrl = new URL(connection.baseUrl);
if (!baseUrl.pathname.endsWith("/")) baseUrl.pathname += "/";
const url = new URL(pathname.replace(/^\/+/, ""), baseUrl);
if (operation.queryParameters !== undefined) {
const encoded = record(
yield* encode(
operation.operationId,
"query",
operation.queryParameters,
raw.urlParams
)
);
for (const [name, value] of Object.entries(encoded)) {
if (value === undefined || value === null) continue;
if (Array.isArray(value)) {
for (const member of value)
url.searchParams.append(name, scalar(member));
} else url.searchParams.set(name, scalar(value));
}
}
let request = HttpClientRequest.make(operation.method)(url).pipe(
HttpClientRequest.setHeaders(connection.headers)
);
if (operation.headers !== undefined) {
const encoded = record(
yield* encode(
operation.operationId,
"headers",
operation.headers,
raw.headers
)
);
request = HttpClientRequest.setHeaders(
request,
Object.fromEntries(
Object.entries(encoded)
.filter((entry) => entry[1] !== undefined && entry[1] !== null)
.map(([name, value]) => [name, scalar(value)])
)
);
}
if (operation.payload !== undefined && raw.payload !== undefined) {
const payload = yield* encode(
operation.operationId,
"payload",
operation.payload,
raw.payload
);
const mediaType = operation.payloadMediaType ?? "application/json";
if (mediaType === "application/json") {
request = yield* HttpClientRequest.bodyJson(request, payload).pipe(
Effect.mapError(
(cause) =>
new GeneratedClientTransportError({
operationId: operation.operationId,
cause,
})
)
);
} else if (mediaType === "text/plain") {
request = HttpClientRequest.bodyText(
request,
scalar(payload),
mediaType
);
} else {
request = HttpClientRequest.bodyUint8Array(
request,
payload as Uint8Array,
mediaType
);
}
}
return request;
});
const remoteFailure = <A extends RequestOperationDescriptor>(
operation: A,
response: HttpClientResponse.HttpClientResponse
): Effect.Effect<never, GeneratedClientError<ErrorBody<A>>> => {
const declared = operation.errors.find(
({ status }) => status === response.status
);
if (declared === undefined)
return Effect.fail(
new GeneratedClientInvalidResponseError({
operationId: operation.operationId,
status: response.status,
message: `Undeclared HTTP response status ${response.status} for ${operation.operationId} (${response.request.url})`,
cause: Option.none(),
})
);
const body =
declared.mediaType === undefined
? Effect.void
: declared.mediaType === "application/json"
? response.json
: declared.mediaType === "text/plain"
? response.text
: response.arrayBuffer.pipe(Effect.map((value) => new Uint8Array(value)));
return body.pipe(
Effect.mapError(
(cause) =>
new GeneratedClientInvalidResponseError({
operationId: operation.operationId,
status: response.status,
message: "Unable to read the declared error response",
cause: Option.some(cause),
})
),
Effect.flatMap((body) => Schema.decodeUnknown(declared.schema)(body)),
Effect.mapError((cause) =>
cause instanceof GeneratedClientInvalidResponseError
? cause
: new GeneratedClientInvalidResponseError({
operationId: operation.operationId,
status: response.status,
message: "The declared error response did not match its schema",
cause: Option.some(cause),
})
),
Effect.flatMap((body) =>
Effect.fail(
new GeneratedClientRemoteError({
operationId: operation.operationId,
status: response.status,
headers: response.headers,
body: body as ErrorBody<A>,
})
)
)
);
};
interface WireEvent {
readonly data: string;
readonly id: Option.Option<string>;
readonly event: Option.Option<string>;
}
const utf8Bytes = (value: string): number =>
new TextEncoder().encode(value).byteLength;
class SseFramer {
private buffer = "";
constructor(private readonly maxFrameBytes: number) {}
push(chunk: string): ReadonlyArray<WireEvent> {
this.buffer += chunk;
const events: WireEvent[] = [];
let match = /\r\n\r\n|\n\n|\r\r/.exec(this.buffer);
while (match !== null) {
const block = this.buffer.slice(0, match.index);
if (utf8Bytes(block) > this.maxFrameBytes)
throw new Error(`SSE frame exceeds ${this.maxFrameBytes} bytes`);
this.buffer = this.buffer.slice(match.index + match[0].length);
const event = parseSseBlock(block);
if (Option.isSome(event)) events.push(event.value);
match = /\r\n\r\n|\n\n|\r\r/.exec(this.buffer);
}
if (utf8Bytes(this.buffer) > this.maxFrameBytes)
throw new Error(`SSE frame exceeds ${this.maxFrameBytes} bytes`);
return events;
}
finish(): ReadonlyArray<WireEvent> {
if (this.buffer.length === 0) return [];
const block = this.buffer;
this.buffer = "";
return Option.toArray(parseSseBlock(block));
}
}
const parseSseBlock = (block: string): Option.Option<WireEvent> => {
const data: string[] = [];
let id = Option.none<string>();
let event = Option.none<string>();
for (const line of block.split(/\r\n|\r|\n/)) {
if (line.startsWith(":")) continue;
const separator = line.indexOf(":");
const field = separator < 0 ? line : line.slice(0, separator);
const rawValue = separator < 0 ? "" : line.slice(separator + 1);
const value = rawValue.startsWith(" ") ? rawValue.slice(1) : rawValue;
if (field === "data") data.push(value);
else if (field === "id" && !value.includes("\0")) id = Option.some(value);
else if (field === "event") event = Option.some(value);
}
return data.length === 0
? Option.none()
: Option.some({ data: data.join("\n"), id, event });
};
class NdjsonFramer {
private buffer = "";
constructor(private readonly maxFrameBytes: number) {}
push(chunk: string): ReadonlyArray<WireEvent> {
this.buffer += chunk;
const events: WireEvent[] = [];
while (true) {
const newline = this.buffer.indexOf("\n");
if (newline < 0) break;
const line = this.buffer.slice(0, newline).replace(/\r$/, "");
this.buffer = this.buffer.slice(newline + 1);
if (utf8Bytes(line) > this.maxFrameBytes)
throw new Error(`NDJSON frame exceeds ${this.maxFrameBytes} bytes`);
if (line.trim().length > 0)
events.push({ data: line, id: Option.none(), event: Option.none() });
}
if (utf8Bytes(this.buffer) > this.maxFrameBytes)
throw new Error(`NDJSON frame exceeds ${this.maxFrameBytes} bytes`);
return events;
}
finish(): ReadonlyArray<WireEvent> {
const line = this.buffer.replace(/\r$/, "");
this.buffer = "";
return line.trim().length === 0
? []
: [{ data: line, id: Option.none(), event: Option.none() }];
}
}
const responseStream = <A extends StreamOperationDescriptor>(
operation: A,
connection: GeneratedClientConnection,
response: HttpClientResponse.HttpClientResponse,
onEventId: (id: string) => void
): Stream.Stream<StreamOperationEvent<A>, StreamOperationError<A>> => {
const framer =
operation.transport === "sse"
? new SseFramer(connection.maxFrameBytes)
: new NdjsonFramer(connection.maxFrameBytes);
let terminated = false;
const framed = response.stream.pipe(
Stream.decodeText(),
Stream.mapConcat((chunk) => framer.push(chunk)),
Stream.concat(
Stream.sync(() => framer.finish()).pipe(Stream.flattenIterables)
),
Stream.mapError(
(cause) =>
new GeneratedClientTransportError({
operationId: operation.operationId,
cause,
})
),
Stream.tap(({ id }) =>
Option.match(id, {
onNone: () => Effect.void,
onSome: (value) => Effect.sync(() => onEventId(value)),
})
),
Stream.takeUntil(({ data }) => {
if (
operation.termination.type === "sentinel" &&
data === operation.termination.value
) {
terminated = true;
return true;
}
return false;
}),
Stream.filter(
({ data }) =>
operation.termination.type !== "sentinel" ||
data !== operation.termination.value
),
Stream.mapEffect(({ data, event }) => {
if (Option.getOrUndefined(event) === "error") {
const declared = operation.errors[0]
if (declared === undefined) {
return Effect.fail(new GeneratedClientInvalidResponseError({
operationId: operation.operationId,
status: response.status,
message: "Stream emitted an undeclared error event",
cause: Option.none(),
}))
}
return Schema.decodeUnknown(Schema.parseJson(declared.schema))(data).pipe(
Effect.mapError((cause) => new GeneratedClientInvalidResponseError({
operationId: operation.operationId,
status: response.status,
message: "Stream error event did not match the declared error schema",
cause: Option.some(cause),
})),
Effect.flatMap((body) => Effect.fail(new GeneratedClientRemoteError({
operationId: operation.operationId,
status: response.status,
headers: response.headers,
body,
}))),
)
}
return Schema.decodeUnknown(Schema.parseJson(operation.eventSchema))(data).pipe(
Effect.mapError(
(cause) =>
new GeneratedClientInvalidResponseError({
operationId: operation.operationId,
status: response.status,
message: "Stream event did not match the declared schema",
cause: Option.some(cause),
})
)
)
})
);
const verify = Stream.fromEffect(
Effect.suspend(() => {
if (operation.termination.type === "eof" || terminated)
return Effect.void;
return Effect.fail(
new GeneratedClientIncompleteStreamError({
operationId: operation.operationId,
termination: operation.termination.type,
})
);
})
).pipe(Stream.drain);
return framed.pipe(Stream.concat(verify)) as Stream.Stream<
StreamOperationEvent<A>,
StreamOperationError<A>
>;
};
export const makeHttpOperation = <A extends HttpOperationDescriptor>(
http: HttpClient.HttpClient,
options: GeneratedClientOptions,
operation: A
): ((
input: HttpOperationInput<A>
) => Effect.Effect<HttpOperationSuccess<A>, HttpOperationError<A>>) => {
const connection = makeGeneratedClientConnection(options);
return (input) =>
Effect.gen(function* () {
const request = yield* requestFor(operation, connection, input);
const response = yield* http.execute(request).pipe(
Effect.mapError(
(cause) =>
new GeneratedClientTransportError({
operationId: operation.operationId,
cause,
})
)
);
const success = operation.successes.find(
({ status }) => status === response.status
);
if (success === undefined)
return yield* remoteFailure(operation, response);
const body =
success.mediaType === undefined
? Effect.void
: success.mediaType === "application/json"
? response.json
: success.mediaType === "text/plain"
? response.text
: response.arrayBuffer.pipe(
Effect.map((value) => new Uint8Array(value))
);
const value = yield* body.pipe(
Effect.mapError(
(cause) =>
new GeneratedClientInvalidResponseError({
operationId: operation.operationId,
status: response.status,
message: "Unable to read the declared success response",
cause: Option.some(cause),
})
)
);
return yield* Schema.decodeUnknown(success.schema)(value).pipe(
Effect.mapError(
(cause) =>
new GeneratedClientInvalidResponseError({
operationId: operation.operationId,
status: response.status,
message: "The declared success response did not match its schema",
cause: Option.some(cause),
})
)
);
}) as Effect.Effect<HttpOperationSuccess<A>, HttpOperationError<A>>;
};
export const makeStreamOperation = <A extends StreamOperationDescriptor>(
http: HttpClient.HttpClient,
options: GeneratedClientOptions,
operation: A
): ((
input: StreamOperationInput<A>
) => Effect.Effect<
GeneratedStreamResponse<StreamOperationEvent<A>, StreamOperationError<A>>,
StreamOperationError<A>
>) => {
const connection = makeGeneratedClientConnection(options);
return (input) => {
let lastEventId: string | undefined;
const admit = (): Effect.Effect<
GeneratedStreamResponse<StreamOperationEvent<A>, StreamOperationError<A>>,
StreamOperationError<A>
> => Effect.gen(function* () {
let request = yield* requestFor(operation, connection, input);
if (
operation.reconnect.type === "last-event-id" &&
lastEventId !== undefined
)
request = HttpClientRequest.setHeader(
request,
"last-event-id",
lastEventId
);
const response = yield* http.execute(request).pipe(
Effect.mapError(
(cause) =>
new GeneratedClientTransportError({
operationId: operation.operationId,
cause,
})
)
);
if (response.status !== operation.responseStatus)
return yield* remoteFailure(operation, response);
const first = responseStream(
operation,
connection,
response,
(id) => (lastEventId = id)
);
const reconnect = (events: Stream.Stream<StreamOperationEvent<A>, StreamOperationError<A>>): Stream.Stream<
StreamOperationEvent<A>,
StreamOperationError<A>
> => events.pipe(
Stream.catchAll((error) =>
operation.reconnect.type === "last-event-id" &&
(error instanceof GeneratedClientIncompleteStreamError ||
error instanceof GeneratedClientTransportError)
? Stream.fromEffect(Effect.sleep("100 millis")).pipe(
Stream.drain,
Stream.concat(Stream.unwrap(admit().pipe(
Effect.map((next) => reconnect(next.events)),
)))
)
: Stream.fail(error)
)
);
return {
status: response.status,
headers: response.headers,
events: reconnect(first),
};
});
return admit();
};
};