Open History to see the last commit
1import * as Duration from "effect/Duration";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import * as Stream from "effect/Stream";
6import * as HttpClient from "effect/http/HttpClient";
7import * as HttpClientRequest from "effect/http/HttpClientRequest";
8import * as HttpMethod from "effect/http/HttpMethod";
9import * as HttpTraceContext from "effect/http/HttpTraceContext";
10import type * as HttpClientResponse from "effect/http/HttpClientResponse";
11
12import { withoutRedirects } from "../environments/EnvironmentConnector.ts";
13
14const RELAY_DELIVERY_ID_HEADER = "x-t3-relay-delivery-id";
15const RELAY_RECEIVED_AT_HEADER = "x-t3-relay-received-at";
16const MAX_RESPONSE_BYTES = 64 * 1024;
17const RELAY_HOOK_UPSTREAM_TIMEOUT_MS = 8_000;
18// Cloudflare answers 530 when the tunnel for a hostname has no connected origin.
19export const TUNNEL_OFFLINE_STATUS = 530;
20
21export interface UpstreamHook {
22 readonly id: string;
23 readonly receivedAt: string;
24 readonly method: string;
25 /** Path segments exactly as the sender sent them; the environment decodes them. */
26 readonly rawHookId: string;
27 readonly rawToken: string;
28 /** Without the leading `?`. */
29 readonly query: string;
30 readonly headers: Readonly<Record<string, string>>;
31 readonly body: Uint8Array;
32}
33
34export interface UpstreamResponse {
35 readonly status: number;
36 readonly contentType: string | undefined;
37 readonly outcome: string | undefined;
38 readonly body: Uint8Array;
39}
40
41const OUTCOME_PATTERN = /^[a-z_]{1,32}$/;
42
43class ResponseTooLarge extends Schema.TaggedError<ResponseTooLarge>()("ResponseTooLarge", {}) {}
44
45/** Stands in for an HttpClientError, so a span records the failure reason and not the request URL. */
46class UpstreamRequestFailed extends Schema.TaggedError<UpstreamRequestFailed>()(
47 "UpstreamRequestFailed",
48 { reason: Schema.String },
49) {}
50
51const readCapped = (response: HttpClientResponse.HttpClientResponse) =>
52 Effect.suspend(() => {
53 const chunks: Array<Uint8Array> = [];
54 let total = 0;
55 return response.stream.pipe(
56 Stream.runForEach((chunk) => {
57 total += chunk.length;
58 if (total > MAX_RESPONSE_BYTES) return Effect.fail(new ResponseTooLarge());
59 chunks.push(chunk);
60 return Effect.void;
61 }),
62 Effect.map(() => {
63 const body = new Uint8Array(total);
64 let offset = 0;
65 for (const chunk of chunks) {
66 body.set(chunk, offset);
67 offset += chunk.length;
68 }
69 return body;
70 }),
71 Effect.catchIf(
72 (error) => error._tag === "HttpClientError" && error.reason._tag === "EmptyBodyError",
73 () => Effect.succeed(new Uint8Array(0)),
74 ),
75 );
76 });
77
78/**
79 * Sends a webhook request through the environment's tunnel. Fails when the
80 * environment cannot be reached, and succeeds with None on timeout.
81 */
82export const sendUpstream = Effect.fn("upstream.sendUpstream")(function* (
83 baseUrl: string,
84 hook: UpstreamHook,
85) {
86 const httpClient = yield* HttpClient.HttpClient;
87 const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
88 // The environment's span joins this trace. Set by hand: the client span
89 // that would propagate it is off, because it records the token in url.full.
90 const parent = yield* Effect.currentSpan.pipe(Effect.option);
91 const headers: Record<string, string> = {
92 ...hook.headers,
93 ...(Option.isSome(parent) ? HttpTraceContext.toHeaders(parent.value) : {}),
94 [RELAY_DELIVERY_ID_HEADER]: hook.id,
95 [RELAY_RECEIVED_AT_HEADER]: hook.receivedAt,
96 };
97 let request = HttpClientRequest.make(hook.method as "GET" | "POST" | "PUT" | "PATCH")(
98 `${base}api/hooks/${hook.rawHookId}/${hook.rawToken}${hook.query ? `?${hook.query}` : ""}`,
99 { headers },
100 );
101 if (HttpMethod.hasBody(request.method)) {
102 request = HttpClientRequest.bodyUint8Array(request, hook.body, headers["content-type"]);
103 }
104 return yield* httpClient.execute(request).pipe(
105 Effect.flatMap((response) =>
106 readCapped(response).pipe(
107 Effect.map((body): UpstreamResponse => {
108 const outcome = response.headers["x-t3-hook-outcome"];
109 return {
110 status: response.status,
111 contentType: response.headers["content-type"],
112 outcome: outcome !== undefined && OUTCOME_PATTERN.test(outcome) ? outcome : undefined,
113 body,
114 };
115 }),
116 ),
117 ),
118 withoutRedirects,
119 Effect.catchTags({
120 HttpClientError: (error) =>
121 Effect.fail(new UpstreamRequestFailed({ reason: error.reason._tag })),
122 }),
123 // The client span would record url.full, which carries the token.
124 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
125 Effect.timeoutOption(Duration.millis(RELAY_HOOK_UPSTREAM_TIMEOUT_MS)),
126 );
127});