-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathdispatcher.ts
More file actions
404 lines (331 loc) · 9.65 KB
/
Copy pathdispatcher.ts
File metadata and controls
404 lines (331 loc) · 9.65 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
import { mediaTypes } from "@hapi/accept";
import createDebugger from "debug";
import fetch, { Headers } from "node-fetch";
import type { ContextRegistry } from "./context-registry.js";
import type {
HttpMethods,
CounterfactResponseObject,
Registry,
} from "./registry.js";
import { createResponseBuilder } from "./response-builder.js";
import { validateRequest } from "./request-validator.js";
import { validateResponse } from "./response-validator.js";
import { Tools } from "./tools.js";
import type {
OpenApiOperation,
OpenApiParameters,
} from "../counterfact-types/index.js";
import type { Config } from "./config.js";
const debug = createDebugger("counterfact:server:dispatcher");
function parseCookies(cookieHeader: string): Record<string, string> {
const cookies: Record<string, string> = {};
for (const part of cookieHeader.split(";")) {
const eqIndex = part.indexOf("=");
if (eqIndex === -1) {
continue;
}
const key = part.slice(0, eqIndex).trim();
const value = part.slice(eqIndex + 1).trim();
if (key && !(key in cookies)) {
try {
cookies[key] = decodeURIComponent(value);
} catch (error) {
debug("could not decode cookie value for key %s: %o", key, error);
cookies[key] = value;
}
}
}
return cookies;
}
interface ParameterTypes {
body: Map<string, string>;
cookie: Map<string, string>;
formData: Map<string, string>;
header: Map<string, string>;
path: Map<string, string>;
query: Map<string, string>;
}
export interface OpenApiDocument {
basePath?: string;
paths: {
[key: string]: {
[key in Lowercase<HttpMethods>]?: OpenApiOperation;
};
};
produces?: string[];
}
export type DispatcherRequest = {
auth?: {
password?: string;
username?: string;
};
body: unknown;
headers: {
[key: string]: string;
};
method: HttpMethods;
path: string;
query: {
[key: string]: string;
};
rawBody?: string;
req: {
path?: string;
};
};
export class Dispatcher {
public registry: Registry;
public contextRegistry: ContextRegistry;
public openApiDocument: OpenApiDocument | undefined;
public fetch: typeof fetch;
public config?: Config; // Add config property
public constructor(
registry: Registry,
contextRegistry: ContextRegistry,
openApiDocument?: OpenApiDocument,
config?: Config,
) {
this.registry = registry;
this.contextRegistry = contextRegistry;
this.openApiDocument = openApiDocument;
this.fetch = fetch;
this.config = config;
}
private parameterTypes(
parameters: OpenApiParameters[] | undefined,
): ParameterTypes {
const types: ParameterTypes = {
body: new Map(),
cookie: new Map(),
formData: new Map(),
header: new Map(),
path: new Map(),
query: new Map(),
};
if (!parameters) {
return types;
}
for (const parameter of parameters) {
const type = parameter?.type;
if (type !== undefined) {
types[parameter.in].set(
parameter.name,
type === "integer" ? "number" : type,
);
}
}
return types;
}
private findOperation(
path: string,
method: HttpMethods,
): OpenApiOperation | undefined {
if (this.openApiDocument) {
for (const key in this.openApiDocument.paths) {
if (key.toLowerCase() === path.toLowerCase()) {
return this.openApiDocument.paths[key]?.[
method.toLowerCase() as Lowercase<HttpMethods>
];
}
}
}
return undefined;
}
public operationForPathAndMethod(
path: string,
method: HttpMethods,
): OpenApiOperation | undefined {
const operation = this.findOperation(path, method);
if (operation === undefined) {
return undefined;
}
if (this.openApiDocument?.produces) {
return {
produces: this.openApiDocument.produces,
...operation,
};
}
return operation;
}
private normalizeResponse(
response: CounterfactResponseObject,
acceptHeader: string,
): CounterfactResponseObject {
if (response.content !== undefined) {
const content = this.selectContent(acceptHeader, response.content);
if (content === undefined) {
return {
body: `Not Acceptable: could not produce a response matching any of the following content types: ${acceptHeader}`,
contentType: "text/plain",
status: 406,
};
}
const normalizedResponse = {
...response,
body: content.body as Uint8Array | string | undefined,
contentType: content.type,
};
delete normalizedResponse.content;
return normalizedResponse;
}
return {
...response,
contentType:
response.headers?.["content-type"]?.toString() ??
response.contentType ??
"unknown/unknown",
};
}
public selectContent(
acceptHeader: string,
content: { body: unknown; type: string }[],
) {
const preferredMediaTypes = mediaTypes(acceptHeader);
for (const mediaType of preferredMediaTypes) {
const contentItem = content.find((item) =>
this.isMediaType(item.type, mediaType),
);
if (contentItem) {
return contentItem;
}
}
return undefined;
}
private isMediaType(type: string, pattern: string) {
if (pattern === "*/*") {
return true;
}
const [baseType, subType] = type.split("/");
const [patternType, patternSubType] = pattern.split("/");
if (baseType === patternType) {
return subType === patternSubType || patternSubType === "*";
}
if (subType === patternSubType) {
return baseType === patternType || patternType === "*";
}
return false;
}
public async request({
auth,
body,
headers = {},
method,
path,
query,
rawBody,
req,
}: DispatcherRequest): Promise<CounterfactResponseObject> {
debug(`request: ${method} ${path}`);
debug(`headers: ${JSON.stringify(headers)}`);
debug(`body: ${JSON.stringify(body)}`);
// If the incoming path includes the base path, remove it
if (
this.openApiDocument?.basePath !== undefined &&
path.toLowerCase().startsWith(this.openApiDocument.basePath.toLowerCase())
) {
path = path.slice(this.openApiDocument.basePath.length);
}
const { matchedPath } = this.registry.handler(path, method);
if (
!this.registry.exists(method, path) &&
this.registry.pathExistsWithAnyMethod(path, method)
) {
return {
body: `The ${method} method is not allowed for ${path}\n`,
contentType: "text/plain",
headers: { allow: this.registry.allowedMethods(path) },
status: 405,
};
}
const operation = this.operationForPathAndMethod(matchedPath, method);
if (this.config?.validateRequests !== false) {
const validation = validateRequest(operation, { body, headers, query });
if (!validation.valid) {
return {
body: `Request validation failed:\n${validation.errors.join("\n")}`,
contentType: "text/plain",
status: 400,
};
}
}
const continuousDistribution = (min: number, max: number) => {
return min + Math.random() * (max - min);
};
const response = await this.registry.endpoint(
method,
path,
this.parameterTypes(operation?.parameters),
)({
auth,
body,
context: this.contextRegistry.find(matchedPath),
async delay(milliseconds = 0, maxMilliseconds = 0) {
const delayInMs =
maxMilliseconds - milliseconds <= 0
? milliseconds
: continuousDistribution(milliseconds, maxMilliseconds);
return new Promise((resolve) => setTimeout(resolve, delayInMs));
},
cookie: parseCookies(headers.cookie ?? headers.Cookie ?? ""),
headers,
proxy: async (url: string) => {
delete headers.host;
const fetchResponse = await this.fetch(`${url}${req.path ?? ""}`, {
body: body === undefined ? undefined : rawBody,
headers: new Headers(headers),
method,
});
const responseHeaders = Object.fromEntries(
fetchResponse.headers.entries(),
);
return {
body: await fetchResponse.text(),
contentType: responseHeaders["content-type"] ?? "unknown/unknown",
headers: responseHeaders,
status: fetchResponse.status,
};
},
query,
// @ts-expect-error - Might be pushing the limits of what TypeScript can do here
response: createResponseBuilder(
operation ?? { responses: {} },
this.config,
), // Pass config
tools: new Tools({ headers }),
});
if (response === undefined) {
return {
body: `The ${method} function did not return anything. Did you forget a return statement?`,
status: 500,
};
}
const normalizedResponse = this.normalizeResponse(
response,
headers.accept ?? "*/*",
);
if (
normalizedResponse.body !== undefined &&
!mediaTypes(headers.accept ?? "*/*").some((type) =>
this.isMediaType(normalizedResponse.contentType ?? "", type),
)
) {
return {
body: JSON.stringify(mediaTypes(headers.accept ?? "*/*")),
status: 406,
};
}
if (this.config?.validateResponses !== false) {
const validation = validateResponse(operation, normalizedResponse);
if (!validation.valid) {
return {
...normalizedResponse,
headers: {
...normalizedResponse.headers,
"response-type-error": validation.errors,
},
};
}
}
return normalizedResponse;
}
}