-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.ts
More file actions
292 lines (263 loc) · 7.58 KB
/
worker.ts
File metadata and controls
292 lines (263 loc) · 7.58 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
import { encrypt, generateKey } from "@local/encryption";
import { getDatabaseClient } from "./repository/database";
import { calculatePatches, summarizePatches } from "./diff";
type ShadowingConfig = {
/**
* Absolute URL shadow request is sent to.
*
* Control request's query parameters will be appended to this.
*
* @example https://api.bwatkins.dev/new-service
*/
url: string;
/**
* Maximum number of seconds the shadow request may take.
*
* Request will be aborted if >=timeout elapses. Note, this
* may leave your server is an undefined state if it does
* not handle unexpectedly closed connections.
*
* @example 5
*/
timeout: number;
/**
* Percent of incoming requests to shadow.
*
* Unsampled requests will not be saved; including the control request.
*
* @example 100 -- all incoming requests will trigger a shadow
* @example 50 -- half of incoming requests will trigger a shadow
*/
percentSampleRate: number;
/**
* Set of HTTP status codes considered a successful shadow.
*
* If provided and a shadow request does not result in a response
* code listed it will be discarded. The control and shadow will not be saved.
*
* If unset, all status codes are considered successful.
*
* @example []
* @example [200, 404]
*/
statuses?: number[];
/**
* Generic metadata stored with the control/shadow request.
*
* You can filter by these tags in the UI and API.
*
* @example { env: 'production' }
* @example { env: 'develop' }
*/
tags?: Record<string, string>;
};
const getShadowingConfigForUrl = (url: URL): ShadowingConfig | undefined => {
// We don't need to check `url.hostname` as your Worker's `routes` configuration
// performs precursory filtering
if (url.pathname === "/jaja/a.json") {
return {
url: "https://bwatkins.dev/jaja/b.json",
percentSampleRate: 100,
timeout: 5,
tags: {
// you can use whatever logic works for your use-case here!
env: url.hostname === "bwatkins.dev" ? "production" : "develop",
app: "jaja",
},
};
}
return undefined;
};
const getResponseBody = (res: Response) => {
const type = res.headers.get("content-type") ?? "";
if (type.includes("application/json")) {
// Even though we'll be serializing this back to text
// soon we parse as JSON to perform the diff
return res.json();
} else {
return res.text();
}
};
const triggerAndProcessShadow = async (
config: ShadowingConfig,
env: Env,
request: Request,
control: Response,
controlStartedAt: number,
controlEndedAt: number,
parentId: string | null,
) => {
const to = new URL(config.url);
to.search = new URL(request.url).search;
console.log(`Shadowing to '${to}'`);
let shadowed: Response;
const ac = new AbortController();
const start = Date.now();
try {
shadowed = await Promise.race([
fetch(
new Request(to, {
signal: ac.signal,
body: request.body,
headers: request.headers,
method: request.method,
redirect: request.redirect,
}),
),
new Promise<never>((r, reject) =>
setTimeout(
() => reject(new Error("request did not complete")),
config.timeout * 1000,
),
),
]);
} catch (error) {
ac.abort();
console.error(`Failed to shadow '${to}'`, error);
return;
}
const end = Date.now();
console.log(`Shadowed to '${to}'`, {
duration: end - start,
status: shadowed.status,
});
if (config.statuses && !config.statuses.includes(shadowed.status)) {
console.error(
`Not saving as '${shadowed.status}' is not one of ${config.statuses.join(
", ",
)}`,
);
return;
}
// TODO: 204
const a = await getResponseBody(control);
const b = await getResponseBody(shadowed);
const patches = calculatePatches(a, b);
const patchesSummary = summarizePatches(patches);
console.log("Generating encryption key");
const cryptoKey = await generateKey(env.ENCRYPTION_SECRET);
console.log("Trying to save");
const databaseClientStart = Date.now();
const client = await getDatabaseClient(env.DATABASE_CONNECTION_STRING);
console.log("Opened database connection", {
duration: Date.now() - databaseClientStart,
});
const databaseStart = Date.now();
await client.query(
`INSERT INTO
requests
(
id,
parent_id,
tags,
diff_paths,
diff_added_count,
diff_removed_count,
diff_patches,
control_req_url,
control_req_method,
control_req_headers,
control_res_http_status,
control_res_body,
control_started_at,
control_ended_at,
shadow_req_url,
shadow_req_method,
shadow_res_headers,
shadow_res_http_status,
shadow_res_body,
shadow_started_at,
shadow_ended_at
)
VALUES
(gen_random_uuid(), $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20);
`,
[
parentId,
JSON.stringify(config.tags),
patches.length > 0 ? patches.map((p) => p.path) : null,
patchesSummary.added || null,
patchesSummary.removed || null,
JSON.stringify(await encrypt(JSON.stringify(patches), cryptoKey)),
control.url,
request.method.toLowerCase(),
JSON.stringify(
await encrypt(
JSON.stringify(Object.fromEntries(request.headers)),
cryptoKey,
),
),
control.status,
JSON.stringify(
await encrypt(typeof a === "string" ? a : JSON.stringify(a), cryptoKey),
),
new Date(controlStartedAt),
new Date(controlEndedAt),
shadowed.url,
request.method.toLowerCase(),
JSON.stringify(
await encrypt(
JSON.stringify(Object.fromEntries(shadowed.headers)),
cryptoKey,
),
),
shadowed.status,
JSON.stringify(
await encrypt(typeof b === "string" ? b : JSON.stringify(b), cryptoKey),
),
new Date(start),
new Date(end),
],
);
console.log("Saved to database", { duration: Date.now() - databaseStart });
const databaseCloseStart = Date.now();
await client.end();
console.log("Closed database connection", {
duration: Date.now() - databaseCloseStart,
});
};
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
const url = new URL(request.url);
const config = getShadowingConfigForUrl(url);
const parentId = request.headers.get("shadowing-parent-id");
// It wouldn't hurt much but I don't want to encourage/end up
// supporting underlying services acting on this header. So, let's
// not leak it in the first place.
const headers = new Headers(request.headers);
headers.delete("shadowing-parent-id");
request = new Request(request, {
headers,
});
const start = Date.now();
const res = await fetch(request);
const end = Date.now();
// We don't support shadowing pre-flight requests for now.
if (request.method === "OPTIONS") {
return res;
}
if (config) {
if (
config.percentSampleRate !== 100 &&
Math.random() * 100 < config.percentSampleRate
) {
console.log(
`Skipping shadow due to sample rate (${config.percentSampleRate}%)`,
);
return res;
}
ctx.waitUntil(
triggerAndProcessShadow(
config,
env,
request.clone(),
res.clone(),
start,
end,
parentId,
),
);
}
return res;
},
};