Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

RepositoryEventSource.ts

180 lines6.2 KB

1import type { WebhookEvents } from "@distilled.cloud/github/webhooks";
2import { sanitizeKey } from "alchemy/RuntimeContext";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import type * as Redacted from "effect/Redacted";
6import type { Providers } from "./Providers.ts";
7​
8/**
9 * A reference to the GitHub repository whose events you want to receive.
10 */
11export interface RepositoryRef {
12 /**
13 * Repository owner (user or organization).
14 */
15 owner: string;
16​
17 /**
18 * Repository name.
19 */
20 repository: string;
22​
23/**
24 * The GitHub webhook event names (e.g. `push`, `pull_request`): the values of
25 * the `X-GitHub-Event` header. Webhooks are configured by these names.
26 */
27export type GitHubEventName = keyof WebhookEvents;
28​
29/**
30 * Names selectable in {@link RepositoryEventSourceProps.events}: every bare
31 * GitHub event name plus `"*"` to subscribe to all of them.
32 *
33 * @see {@link https://docs.github.com/en/webhooks/webhook-events-and-payloads | GitHub webhook events and payloads}
34 */
35export type WebhookEventName = GitHubEventName | "*";
36​
37/**
38 * A single GitHub webhook delivery: a discriminated union of
39 * `{ id, name, payload }` keyed on `name`, with a fully-typed `payload` per
40 * event. `Name` narrows the union to the events the subscriber selected, so
41 * `switch (event.name)` exhaustively narrows `event.payload`.
42 */
43export type WebhookEvent<Name extends GitHubEventName = GitHubEventName> = {
44 [N in Name]: {
45 /** The delivery's `X-GitHub-Delivery` id. */
46 readonly id: string;
47 readonly name: N;
48 readonly payload: WebhookEvents[N];
49 };
50}[Name];
51​
52/**
53 * The set of event names a handler can observe given the `events` it
54 * selected. Selecting `"*"` (or omitting `events`) widens back to every
55 * {@link GitHubEventName}; otherwise it's the union of the chosen literals.
56 */
57export type SelectedEvent<E extends readonly WebhookEventName[]> = "*" extends E[number]
58 ? GitHubEventName
59 : Exclude<E[number], "*">;
60​
61export interface RepositoryEventSourceProps<
62 E extends readonly WebhookEventName[] = readonly WebhookEventName[],
63> extends RepositoryRef {
64 /**
65 * GitHub event names to subscribe to (e.g. `["push", "pull_request"]`).
66 * Use `["*"]` to receive every event GitHub emits.
67 * @default ["push"]
68 */
69 events?: E;
70​
71 /**
72 * Secret used to verify each delivery's `HMAC-SHA256` signature. The event
73 * source provisions the webhook with this secret and the runtime rejects
74 * deliveries whose `X-Hub-Signature-256` header doesn't match. When omitted,
75 * a random secret is generated at deploy and bound onto the host.
76 */
77 secret?: Redacted.Redacted<string>;
78​
79 /**
80 * Path on the host that GitHub delivers to. Defaults to a deterministic
81 * per-repository path so deliveries don't collide with your application
82 * routes. Override only if you need a fixed, well-known path.
83 */
84 path?: string;
86​
87/**
88 * Subscribe to events emitted by a GitHub repository.
89 *
90 * Call it in the init phase of a host (e.g. a Cloudflare Worker) and pass a
91 * `process` function that receives each {@link WebhookEvent} and returns an
92 * `Effect`. The handler runs once per webhook delivery.
93 *
94 * Wiring the webhook (delivery URL, secret) is handled by
95 * `GitHub.RepositoryEventSourceLive`, over the host's `WebhookHost`.
96 *
97 * **Example:** Example
98 * ```typescript
99 * // `event.name` is narrowed to "push" | "pull_request"
100 * yield* GitHub.consumeRepositoryEvents(
101 * {
102 * owner: "my-org",
103 * repository: "my-repo",
104 * events: ["push", "pull_request"],
105 * secret,
106 * },
107 * (event) => Effect.log(`received ${event.name} (${event.id})`),
108 * );
109 * ```
110 *
111 * **Example:** Example
112 * ```typescript
113 * // When you don't need to pass any options, the handler is the only argument.
114 * yield* GitHub.consumeRepositoryEvents((event) =>
115 * Effect.log(`received ${event.name} (${event.id})`),
116 * );
117 * ```
118 *
119 * @binding
120 */
121export function consumeRepositoryEvents<Req = never>(
122 process: (
123 event: WebhookEvent<SelectedEvent<readonly WebhookEventName[]>>,
124 ) => Effect.Effect<void, never, Req | Providers>,
125): Effect.Effect<void, never, RepositoryEventSource>;
126export function consumeRepositoryEvents<
127 const E extends readonly WebhookEventName[] = readonly WebhookEventName[],
128 Req = never,
129>(
130 props: RepositoryEventSourceProps<E>,
131 process: (event: WebhookEvent<SelectedEvent<E>>) => Effect.Effect<void, never, Req | Providers>,
132): Effect.Effect<void, never, RepositoryEventSource>;
133export function consumeRepositoryEvents<
134 const E extends readonly WebhookEventName[] = readonly WebhookEventName[],
135 Req = never,
136>(
137 propsOrProcess:
138 | RepositoryEventSourceProps<E>
139 | ((event: WebhookEvent<SelectedEvent<E>>) => Effect.Effect<void, never, Req | Providers>),
140 maybeProcess?: (
141 event: WebhookEvent<SelectedEvent<E>>,
142 ) => Effect.Effect<void, never, Req | Providers>,
143) {
144 const [props, process] =
145 typeof propsOrProcess === "function"
146 ? [{} as RepositoryEventSourceProps<E>, propsOrProcess]
147 : [propsOrProcess, maybeProcess!];
148 return RepositoryEventSource.use((source) => source(props, process));
150​
151export type RepositoryEventSourceService = <
152 E extends readonly WebhookEventName[] = readonly WebhookEventName[],
153 Req = never,
154>(
155 props: RepositoryEventSourceProps<E>,
156 process: (event: WebhookEvent<SelectedEvent<E>>) => Effect.Effect<void, never, Req>,
157) => Effect.Effect<void, never, never>;
158​
159export class RepositoryEventSource extends Context.Service<
160 RepositoryEventSource,
161 RepositoryEventSourceService
162>()("GitHub.RepositoryEventSource") {}
163​
164/**
165 * Deterministic delivery path for a repository's webhook. Shared by the
166 * deploy-time policy (which registers the webhook URL) and the runtime
167 * (which only claims requests on this path), so both sides agree.
168 */
169export const webhookPath = (props: RepositoryRef & { path?: string }): string =>
170 props.path ?? `/__alchemy/github/${props.owner}/${props.repository}`;
171​
172/**
173 * Deterministic env var name under which the deploy-time policy stores the
174 * webhook secret on the host, so the runtime can read it back to verify
175 * signatures.
176 */
177export const webhookSecretEnvName = (repository: RepositoryRef): string =>
178 `ALCHEMY_GITHUB_WEBHOOK_SECRET_${sanitizeKey(repository.owner)}_${sanitizeKey(
179 repository.repository,
180 )}`;