-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntimeSupport.ts
More file actions
289 lines (258 loc) · 8.69 KB
/
runtimeSupport.ts
File metadata and controls
289 lines (258 loc) · 8.69 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
import { Hono } from "hono";
import { retry } from "@std/async/retry";
import {
type AccessTokenCredential,
type ApiKeyCredential,
type CredentialFetcherBackendConfig,
type Registrations,
TriggerEvent,
} from "./backendTypes.ts";
export type { AccessTokenCredential, ApiKeyCredential };
import { type Log, patchConsoleGlobal, runInLoggingContext } from "./logging.ts";
import type { CommonTriggerBackendConfig, CommonTriggerOptions } from "./common.ts";
patchConsoleGlobal();
interface TriggerEventResponse {
logs: Log[];
error: string | undefined;
}
interface RegisteredEvent {
fn: (event: unknown) => void | Promise<void>;
config: unknown;
}
interface RegisteredCredentialFetcher {
config: CredentialFetcherBackendConfig;
}
const eventListenersByType = new Map<string, Map<string, RegisteredEvent>>();
const credentialFetchersByType = new Map<
string,
Map<string, RegisteredCredentialFetcher>
>();
let nextAutomaticLabel = 0;
/**
* @internal
* Registers an event listener for a specific event type. This function is used
* internally by event source implementations.
* @param eventName The name of the event source in glue-backend.
* @param callback The user's callback function.
* @param commonTriggerOptions Common trigger options. This should be passed in
* from the user as-is. Extra properties will be ignored.
* @param backendConfig The backend config for this trigger. This generally
* should be of a type that extends {@link CommonTriggerBackendConfig} specific
* to the event source. The caller should ensure this object only includes the
* properties that are expected by glue-backend. Properties that are part of
* {@link CommonTriggerOptions} do not need to be included here, as they will be
* taken from the `commonTriggerOptions` parameter automatically.
*/
export function registerEventListener<T>(
eventName: string,
callback: (event: T) => void,
commonTriggerOptions: CommonTriggerOptions | undefined,
backendConfig: CommonTriggerBackendConfig,
) {
scheduleInit();
let specificEventListeners = eventListenersByType.get(eventName);
if (!specificEventListeners) {
specificEventListeners = new Map();
eventListenersByType.set(eventName, specificEventListeners);
}
const resolvedLabel = String(nextAutomaticLabel++);
if (specificEventListeners.has(resolvedLabel)) {
throw new Error(
`Event listener with label ${JSON.stringify(resolvedLabel)} already registered`,
);
}
const fullBackendConfig: CommonTriggerBackendConfig = {
...backendConfig,
description: commonTriggerOptions?.description,
};
const typedCallback = callback as RegisteredEvent["fn"];
const effectiveCallback: RegisteredEvent["fn"] = commonTriggerOptions?.retryOnFailure
? async (event: unknown) => await retry(() => typedCallback(event))
: typedCallback;
specificEventListeners.set(resolvedLabel, {
fn: effectiveCallback,
config: fullBackendConfig,
});
}
/**
* Used to fetch an account credential or client at runtime.
*/
export interface CredentialFetcher<T> {
/**
* Fetches the account credential or client. This must only be called within
* an event handler.
*
* @throws If called outside of an event handler, or if there is an error
* fetching the credential.
*/
get(): Promise<T>;
}
/**
* @internal
* Registers a credential fetcher for a specific service type. This function is
* used internally by event source implementations.
*/
export function registerCredentialFetcher<T extends AccessTokenCredential | ApiKeyCredential>(
type: string,
config: CredentialFetcherBackendConfig,
): CredentialFetcher<T> {
scheduleInit();
let credentialFetchersOfType = credentialFetchersByType.get(type);
if (!credentialFetchersOfType) {
credentialFetchersOfType = new Map();
credentialFetchersByType.set(type, credentialFetchersOfType);
}
const resolvedLabel = String(nextAutomaticLabel++);
if (credentialFetchersOfType.has(resolvedLabel)) {
throw new Error(
`Credential fetcher with label ${
JSON.stringify(
resolvedLabel,
)
} already registered`,
);
}
credentialFetchersOfType.set(resolvedLabel, {
config,
});
return {
async get() {
if (!glueDeploymentId || !glueAuthHeader) {
throw new Error(
"Credential fetcher must not be used before any trigger events have been received.",
);
}
const glueDeploymentId_ = glueDeploymentId;
const glueAuthHeader_ = glueAuthHeader;
// retry on connection errors
const res = await retry(async () => {
const res = await fetch(
`${Deno.env.get("GLUE_API_SERVER")}/glueInternal/deployments/${
encodeURIComponent(glueDeploymentId_)
}/accountInjections/${encodeURIComponent(type)}/${encodeURIComponent(resolvedLabel)}`,
{
headers: {
"Authorization": glueAuthHeader_,
},
},
);
// retry on 5xx errors from backend, which may be transient
if (res.status >= 500 && res.status < 600) {
throw new Error(
`Failed to fetch credential: ${res.status} ${res.statusText}`,
);
}
return res;
});
if (!res.ok) {
throw new Error(
`Failed to fetch credential: ${res.status} ${res.statusText}`,
);
}
const body = await res.json() as T;
return body;
},
};
}
function getRegistrations(): Registrations {
return {
triggers: Array.from(
eventListenersByType.entries()
.flatMap(([type, listeners]) =>
listeners.entries().map(([label, { config }]) => ({
type,
label,
config,
}))
),
),
accountInjections: Array.from(
credentialFetchersByType.entries()
.flatMap(([type, requests]) =>
requests.entries().map(([label, { config }]) => ({
type,
label,
config,
}))
),
),
};
}
async function handleTrigger(event: TriggerEvent) {
const specificEventListeners = eventListenersByType.get(event.type);
const eventListener = specificEventListeners?.get(event.label);
if (!eventListener) {
throw new Error(`Unknown trigger: ${event.type} ${event.label}`);
}
await eventListener.fn(event.data);
}
let hasScheduledInit = false;
let hasInited = false;
let glueDeploymentId: string | undefined;
let glueAuthHeader: string | undefined;
/**
* This function needs to be called when any triggers are registered. It
* schedules a microtask to initialize listening for the triggers, and throws an
* error if that initialization has already happened.
*/
function scheduleInit() {
if (hasInited) {
throw new Error(
"Attempted to register a trigger after initialization. All triggers must be registered at the top level.",
);
}
if (hasScheduledInit) {
// This is hit when there are multiple registrations (triggers and account
// injections) on startup. We don't need to do anything more after the first
// time.
return;
}
hasScheduledInit = true;
Promise.resolve().then(() => {
hasInited = true;
const GLUE_DEV_PORT = Deno.env.get("GLUE_DEV_PORT");
const serveOptions: Deno.ServeTcpOptions = GLUE_DEV_PORT
? { hostname: "127.0.0.1", port: Number(GLUE_DEV_PORT) }
: {};
serveOptions.onListen = () => {};
const app = new Hono();
app.get("/__glue__/getRegistrations", (c) => {
return c.json(getRegistrations());
});
app.get("/__glue__/getRegisteredTriggers", (c) => {
return c.json(getRegistrations().triggers);
});
app.post("/__glue__/triggerEvent", async (c) => {
// TODO need to authenticate the request as coming from glue-backend.
glueDeploymentId = c.req.header("X-Glue-Deployment-Id");
glueAuthHeader = c.req.header("X-Glue-API-Auth-Header");
const body = TriggerEvent.parse(await c.req.json());
const { logs, error } = await runInLoggingContext(() => handleTrigger(body));
const response: TriggerEventResponse = { logs, error };
return c.json(response);
});
Deno.serve(serveOptions, app.fetch);
// Connect the lifeline once we're ready
if (GLUE_DEV_PORT) {
const cliWebsocketAddr = Deno.env.get("GLUE_CLI_WS_ADDR");
if (cliWebsocketAddr) {
startLifeline(cliWebsocketAddr);
}
}
});
}
/**
* Open a websocket connection to the CLI runner so we can exit if the runner
* dies.
*/
function startLifeline(cliWebsocketAddr: string) {
const ws = new WebSocket(cliWebsocketAddr);
ws.onclose = (_event) => {
// runner died so exit
Deno.exit(5); // arbitrary non-default error exit code
};
ws.onerror = (event) => {
console.error((event as ErrorEvent).error);
Deno.exit(5);
};
}