-
Notifications
You must be signed in to change notification settings - Fork 200
/
index.ts
1497 lines (1375 loc) 路 51.1 KB
/
index.ts
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import assert from "assert";
import crypto from "crypto";
import { Abortable } from "events";
import fs from "fs";
import http from "http";
import net from "net";
import os from "os";
import path from "path";
import { Duplex, Transform, Writable } from "stream";
import { ReadableStream } from "stream/web";
import util from "util";
import zlib from "zlib";
import type {
CacheStorage,
D1Database,
DurableObjectNamespace,
KVNamespace,
Queue,
R2Bucket,
} from "@cloudflare/workers-types/experimental";
import exitHook from "exit-hook";
import { $ as colors$ } from "kleur/colors";
import stoppable from "stoppable";
import { Dispatcher, Pool } from "undici";
import SCRIPT_MINIFLARE_SHARED from "worker:shared/index";
import SCRIPT_MINIFLARE_ZOD from "worker:shared/zod";
import { WebSocketServer } from "ws";
import { z } from "zod";
import { fallbackCf, setupCf } from "./cf";
import {
DispatchFetch,
Headers,
Request,
RequestInit,
Response,
configureEntrySocket,
coupleWebSocket,
fetch,
getAccessibleHosts,
registerAllowUnauthorizedDispatcher,
} from "./http";
import {
D1_PLUGIN_NAME,
DURABLE_OBJECTS_PLUGIN_NAME,
DurableObjectClassNames,
HEADER_CF_BLOB,
KV_PLUGIN_NAME,
PLUGIN_ENTRIES,
PluginServicesOptions,
Plugins,
ProxyClient,
QUEUES_PLUGIN_NAME,
QueueConsumers,
QueuesError,
R2_PLUGIN_NAME,
ReplaceWorkersTypes,
SOCKET_ENTRY,
SharedOptions,
WorkerOptions,
getDirectSocketName,
getGlobalServices,
kProxyNodeBinding,
maybeGetSitesManifestModule,
normaliseDurableObject,
} from "./plugins";
import {
CUSTOM_SERVICE_KNOWN_OUTBOUND,
CustomServiceKind,
JsonErrorSchema,
NameSourceOptions,
ServiceDesignatorSchema,
getUserServiceName,
handlePrettyErrorRequest,
reviveError,
} from "./plugins/core";
import {
Config,
Extension,
Runtime,
RuntimeOptions,
Service,
Socket,
SocketIdentifier,
SocketPorts,
Worker_Binding,
Worker_Module,
kInspectorSocket,
serializeConfig,
} from "./runtime";
import {
Log,
MiniflareCoreError,
NoOpLog,
OptionalZodTypeOf,
stripAnsi,
} from "./shared";
import {
CoreBindings,
CoreHeaders,
LogLevel,
Mutex,
SharedHeaders,
} from "./workers";
import { _formatZodError } from "./zod-format";
const DEFAULT_HOST = "127.0.0.1";
function getURLSafeHost(host: string) {
return net.isIPv6(host) ? `[${host}]` : host;
}
function getAccessibleHost(host: string) {
const accessibleHost =
host === "*" || host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
return getURLSafeHost(accessibleHost);
}
function getServerPort(server: http.Server) {
const address = server.address();
// Note address would be string with unix socket
assert(address !== null && typeof address === "object");
return address.port;
}
// ===== `Miniflare` User Options =====
export type MiniflareOptions = SharedOptions &
(WorkerOptions | { workers: WorkerOptions[] });
// ===== `Miniflare` Validated Options =====
type PluginWorkerOptions = {
[Key in keyof Plugins]: z.infer<Plugins[Key]["options"]>;
};
type PluginSharedOptions = {
[Key in keyof Plugins]: OptionalZodTypeOf<Plugins[Key]["sharedOptions"]>;
};
function hasMultipleWorkers(opts: unknown): opts is { workers: unknown[] } {
return (
typeof opts === "object" &&
opts !== null &&
"workers" in opts &&
Array.isArray(opts.workers)
);
}
function validateOptions(
opts: unknown
): [PluginSharedOptions, PluginWorkerOptions[]] {
// Normalise options into shared and worker-specific
const sharedOpts = opts;
const multipleWorkers = hasMultipleWorkers(opts);
const workerOpts = multipleWorkers ? opts.workers : [opts];
if (workerOpts.length === 0) {
throw new MiniflareCoreError("ERR_NO_WORKERS", "No workers defined");
}
// Initialise return values
const pluginSharedOpts = {} as PluginSharedOptions;
const pluginWorkerOpts = Array.from(Array(workerOpts.length)).map(
() => ({} as PluginWorkerOptions)
);
// Validate all options
try {
for (const [key, plugin] of PLUGIN_ENTRIES) {
// @ts-expect-error types of individual plugin options are unknown
pluginSharedOpts[key] = plugin.sharedOptions?.parse(sharedOpts);
for (let i = 0; i < workerOpts.length; i++) {
// Make sure paths are correct in validation errors
const path = multipleWorkers ? ["workers", i] : undefined;
// @ts-expect-error types of individual plugin options are unknown
pluginWorkerOpts[i][key] = plugin.options.parse(workerOpts[i], {
path,
});
}
}
} catch (e) {
if (e instanceof z.ZodError) {
let formatted: string | undefined;
try {
formatted = _formatZodError(e, opts);
} catch (formatError) {
// If formatting failed for some reason, we'd like to know, so log a
// bunch of debugging information, including the full validation error
// so users at least know what was wrong.
const title = "[Miniflare] Validation Error Format Failure";
const message = [
"### Input",
"```",
util.inspect(opts, { depth: null }),
"```",
"",
"### Validation Error",
"```",
e.stack,
"```",
"",
"### Format Error",
"```",
typeof formatError === "object" &&
formatError !== null &&
"stack" in formatError &&
typeof formatError.stack === "string"
? formatError.stack
: String(formatError),
"```",
].join("\n");
const githubIssueUrl = new URL(
"https://github.com/cloudflare/miniflare/issues/new"
);
githubIssueUrl.searchParams.set("title", title);
githubIssueUrl.searchParams.set("body", message);
formatted = [
"Unable to format validation error.",
"Please open the following URL in your browser to create a GitHub issue:",
githubIssueUrl,
"",
message,
"",
].join("\n");
}
const error = new MiniflareCoreError(
"ERR_VALIDATION",
`Unexpected options passed to \`new Miniflare()\` constructor:\n${formatted}`
);
// Add the `cause` as a getter, so it isn't logged automatically with the
// error, but can still be accessed if needed
Object.defineProperty(error, "cause", { get: () => e });
throw error;
}
throw e;
}
// Validate names unique
const names = new Set<string>();
for (const opts of pluginWorkerOpts) {
const name = opts.core.name ?? "";
if (names.has(name)) {
throw new MiniflareCoreError(
"ERR_DUPLICATE_NAME",
name === ""
? "Multiple workers defined without a `name`"
: `Multiple workers defined with the same \`name\`: "${name}"`
);
}
names.add(name);
}
return [pluginSharedOpts, pluginWorkerOpts];
}
// When creating user worker services, we need to know which Durable Objects
// they export. Rather than parsing JavaScript to search for class exports
// (which would have to be recursive because of `export * from ...`), we collect
// all Durable Object bindings, noting that bindings may be defined for objects
// in other services.
function getDurableObjectClassNames(
allWorkerOpts: PluginWorkerOptions[]
): DurableObjectClassNames {
const serviceClassNames: DurableObjectClassNames = new Map();
for (const workerOpts of allWorkerOpts) {
const workerServiceName = getUserServiceName(workerOpts.core.name);
for (const designator of Object.values(
workerOpts.do.durableObjects ?? {}
)) {
const {
className,
// Fallback to current worker service if name not defined
serviceName = workerServiceName,
unsafeUniqueKey,
} = normaliseDurableObject(designator);
// Get or create `Map` mapping class name to optional unsafe unique key
let classNames = serviceClassNames.get(serviceName);
if (classNames === undefined) {
classNames = new Map();
serviceClassNames.set(serviceName, classNames);
}
if (classNames.has(className)) {
// If we've already seen this class in this service, make sure the
// unsafe unique keys match
const existingUnsafeUniqueKey = classNames.get(className);
if (existingUnsafeUniqueKey !== unsafeUniqueKey) {
throw new MiniflareCoreError(
"ERR_DIFFERENT_UNIQUE_KEYS",
`Multiple unsafe unique keys defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify(
unsafeUniqueKey
)} and ${JSON.stringify(existingUnsafeUniqueKey)}`
);
}
} else {
// Otherwise, just add it
classNames.set(className, unsafeUniqueKey);
}
}
}
return serviceClassNames;
}
function getQueueConsumers(
allWorkerOpts: PluginWorkerOptions[]
): QueueConsumers {
const queueConsumers: QueueConsumers = new Map();
for (const workerOpts of allWorkerOpts) {
const workerName = workerOpts.core.name ?? "";
let workerConsumers = workerOpts.queues.queueConsumers;
if (workerConsumers !== undefined) {
// De-sugar array consumer options to record mapping to empty options
if (Array.isArray(workerConsumers)) {
workerConsumers = Object.fromEntries(
workerConsumers.map((queueName) => [queueName, {}])
);
}
for (const [queueName, opts] of Object.entries(workerConsumers)) {
// Validate that each queue has at most one consumer...
const existingConsumer = queueConsumers.get(queueName);
if (existingConsumer !== undefined) {
throw new QueuesError(
"ERR_MULTIPLE_CONSUMERS",
`Multiple consumers defined for queue "${queueName}": "${existingConsumer.workerName}" and "${workerName}"`
);
}
// ...then store the consumer
queueConsumers.set(queueName, { workerName, ...opts });
}
}
}
for (const [queueName, consumer] of queueConsumers) {
// Check the dead letter queue isn't configured to be the queue itself
// (NOTE: Queues *does* permit DLQ cycles between multiple queues,
// i.e. if Q2 is DLQ for Q1, but Q1 is DLQ for Q2)
if (consumer.deadLetterQueue === queueName) {
throw new QueuesError(
"ERR_DEAD_LETTER_QUEUE_CYCLE",
`Dead letter queue for queue "${queueName}" cannot be itself`
);
}
}
return queueConsumers;
}
// Collects all routes from all worker services
function getWorkerRoutes(
allWorkerOpts: PluginWorkerOptions[]
): Map<string, string[]> {
const allRoutes = new Map<string, string[]>();
for (const workerOpts of allWorkerOpts) {
const name = workerOpts.core.name ?? "";
assert(!allRoutes.has(name)); // Validated unique names earlier
allRoutes.set(name, workerOpts.core.routes ?? []);
}
return allRoutes;
}
// Get the name of a binding in the `ProxyServer`'s `env`
function getProxyBindingName(plugin: string, worker: string, binding: string) {
return [
CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY,
plugin,
worker,
binding,
].join(":");
}
// Get whether a binding will need a proxy to be supported in Node (i.e. is
// the implementation of this binding in `workerd`?). If this returns `false`,
// there's no need to bind the binding to the `ProxyServer`.
function isNativeTargetBinding(binding: Worker_Binding) {
return !(
"json" in binding ||
"wasmModule" in binding ||
"text" in binding ||
"data" in binding
);
}
// Converts a regular worker binding to binding suitable for the `ProxyServer`.
function buildProxyBinding(
plugin: string,
worker: string,
binding: Worker_Binding
): Worker_Binding {
assert(binding.name !== undefined);
const name = getProxyBindingName(plugin, worker, binding.name);
const proxyBinding = { ...binding, name };
// If this is a Durable Object namespace binding to the current worker,
// make sure it continues to point to that worker when bound elsewhere
if (
"durableObjectNamespace" in proxyBinding &&
proxyBinding.durableObjectNamespace !== undefined
) {
proxyBinding.durableObjectNamespace.serviceName ??=
getUserServiceName(worker);
}
return proxyBinding;
}
// Gets an array of proxy bindings for internal Durable Objects, only used in
// testing for accessing internal methods
function getInternalDurableObjectProxyBindings(
plugin: string,
service: Service
): Worker_Binding[] | undefined {
if (!("worker" in service)) return;
assert(service.worker !== undefined);
const serviceName = service.name;
assert(serviceName !== undefined);
return service.worker.durableObjectNamespaces?.map(({ className }) => {
assert(className !== undefined);
return {
name: getProxyBindingName(`${plugin}-internal`, serviceName, className),
durableObjectNamespace: { serviceName, className },
};
});
}
type StoppableServer = http.Server & stoppable.WithStop;
const restrictedUndiciHeaders = [
// From Miniflare 2:
// https://github.com/cloudflare/miniflare/blob/9c135599dc21fe69080ada17fce6153692793bf1/packages/core/src/standards/http.ts#L129-L132
"transfer-encoding",
"connection",
"keep-alive",
"expect",
];
const restrictedWebSocketUpgradeHeaders = [
"upgrade",
"connection",
"sec-websocket-accept",
];
export function _transformsForContentEncoding(encoding?: string): Transform[] {
const encoders: Transform[] = [];
if (!encoding) return encoders;
// Reverse of https://github.com/nodejs/undici/blob/48d9578f431cbbd6e74f77455ba92184f57096cf/lib/fetch/index.js#L1660
const codings = encoding
.toLowerCase()
.split(",")
.map((x) => x.trim());
for (const coding of codings) {
if (/(x-)?gzip/.test(coding)) {
encoders.push(zlib.createGzip());
} else if (/(x-)?deflate/.test(coding)) {
encoders.push(zlib.createDeflate());
} else if (coding === "br") {
encoders.push(zlib.createBrotliCompress());
} else {
// Unknown encoding, don't do any encoding at all
encoders.length = 0;
break;
}
}
return encoders;
}
async function writeResponse(response: Response, res: http.ServerResponse) {
// Convert headers into Node-friendly format
const headers: http.OutgoingHttpHeaders = {};
for (const entry of response.headers) {
const key = entry[0].toLowerCase();
const value = entry[1];
if (key === "set-cookie") {
headers[key] = response.headers.getSetCookie();
} else {
headers[key] = value;
}
}
// If a `Content-Encoding` header is set, we'll need to encode the body
// (likely only set by custom service bindings)
const encoding = headers["content-encoding"]?.toString();
const encoders = _transformsForContentEncoding(encoding);
if (encoders.length > 0) {
// `Content-Length` if set, will be wrong as it's for the decoded length
delete headers["content-length"];
}
res.writeHead(response.status, response.statusText, headers);
// `initialStream` is the stream we'll write the response to. It
// should end up as the first encoder, piping to the next encoder,
// and finally piping to the response:
//
// encoders[0] (initialStream) -> encoders[1] -> res
//
// Not using `pipeline(passThrough, ...encoders, res)` here as that
// gives a premature close error with server sent events. This also
// avoids creating an extra stream even when we're not encoding.
let initialStream: Writable = res;
for (let i = encoders.length - 1; i >= 0; i--) {
encoders[i].pipe(initialStream);
initialStream = encoders[i];
}
// Response body may be null if empty
if (response.body) {
for await (const chunk of response.body) {
if (chunk) initialStream.write(chunk);
}
}
initialStream.end();
}
function safeReadableStreamFrom(iterable: AsyncIterable<Uint8Array>) {
// Adapted from `undici`, catches errors from `next()` to avoid unhandled
// rejections from aborted request body streams:
// https://github.com/nodejs/undici/blob/dfaec78f7a29f07bb043f9006ed0ceb0d5220b55/lib/core/util.js#L369-L392
let iterator: AsyncIterator<Uint8Array>;
return new ReadableStream<Uint8Array>(
{
async start() {
iterator = iterable[Symbol.asyncIterator]();
},
// @ts-expect-error `pull` may return anything
async pull(controller): Promise<boolean> {
try {
const { done, value } = await iterator.next();
if (done) {
queueMicrotask(() => controller.close());
} else {
const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
controller.enqueue(new Uint8Array(buf));
}
} catch {
queueMicrotask(() => controller.close());
}
// @ts-expect-error `pull` may return anything
return controller.desiredSize > 0;
},
async cancel() {
await iterator.return?.();
},
},
0
);
}
// Maps `Miniflare` instances to stack traces for their construction. Used to identify un-`dispose()`d instances.
let maybeInstanceRegistry:
| Map<Miniflare, string /* constructionStack */>
| undefined;
/** @internal */
export function _initialiseInstanceRegistry() {
return (maybeInstanceRegistry = new Map());
}
export class Miniflare {
#previousSharedOpts?: PluginSharedOptions;
#sharedOpts: PluginSharedOptions;
#workerOpts: PluginWorkerOptions[];
#log: Log;
readonly #runtime?: Runtime;
readonly #removeRuntimeExitHook?: () => void;
#runtimeEntryURL?: URL;
#socketPorts?: SocketPorts;
#runtimeDispatcher?: Dispatcher;
#proxyClient?: ProxyClient;
// Path to temporary directory for use as scratch space/"in-memory" Durable
// Object storage. Note this may not exist, it's up to the consumers to
// create this if needed. Deleted on `dispose()`.
readonly #tmpPath: string;
readonly #removeTmpPathExitHook: () => void;
// Mutual exclusion lock for runtime operations (i.e. initialisation and
// updating config). This essentially puts initialisation and future updates
// in a queue, ensuring they're performed in calling order.
readonly #runtimeMutex: Mutex;
// Store `#init()` `Promise`, so we can propagate initialisation errors in
// `ready`. We would have no way of catching these otherwise.
readonly #initPromise: Promise<void>;
// Aborted when dispose() is called
readonly #disposeController: AbortController;
#loopbackServer?: StoppableServer;
#loopbackHost?: string;
readonly #liveReloadServer: WebSocketServer;
readonly #webSocketServer: WebSocketServer;
readonly #webSocketExtraHeaders: WeakMap<http.IncomingMessage, Headers>;
constructor(opts: MiniflareOptions) {
// Split and validate options
const [sharedOpts, workerOpts] = validateOptions(opts);
this.#sharedOpts = sharedOpts;
this.#workerOpts = workerOpts;
// Add to registry after initial options validation, before any servers/
// child processes are started
if (maybeInstanceRegistry !== undefined) {
const object = { name: "Miniflare", stack: "" };
Error.captureStackTrace(object, Miniflare);
maybeInstanceRegistry.set(this, object.stack);
}
this.#log = this.#sharedOpts.core.log ?? new NoOpLog();
this.#liveReloadServer = new WebSocketServer({ noServer: true });
this.#webSocketServer = new WebSocketServer({
noServer: true,
// Disable automatic handling of `Sec-WebSocket-Protocol` header,
// Cloudflare Workers require users to include this header themselves in
// `Response`s: https://github.com/cloudflare/miniflare/issues/179
handleProtocols: () => false,
});
// Add custom headers included in response to WebSocket upgrade requests
this.#webSocketExtraHeaders = new WeakMap();
this.#webSocketServer.on("headers", (headers, req) => {
const extra = this.#webSocketExtraHeaders.get(req);
this.#webSocketExtraHeaders.delete(req);
if (extra) {
for (const [key, value] of extra) {
if (!restrictedWebSocketUpgradeHeaders.includes(key.toLowerCase())) {
headers.push(`${key}: ${value}`);
}
}
}
});
// Build path for temporary directory. We don't actually want to create this
// unless it's needed (i.e. we have Durable Objects enabled). This means we
// can't use `fs.mkdtemp()`, as that always creates the directory.
this.#tmpPath = path.join(
os.tmpdir(),
`miniflare-${crypto.randomBytes(16).toString("hex")}`
);
this.#removeTmpPathExitHook = exitHook(() => {
fs.rmSync(this.#tmpPath, { force: true, recursive: true });
});
// Setup runtime
this.#runtime = new Runtime();
this.#removeRuntimeExitHook = exitHook(() => void this.#runtime?.dispose());
this.#disposeController = new AbortController();
this.#runtimeMutex = new Mutex();
this.#initPromise = this.#runtimeMutex
.runWith(() => this.#assembleAndUpdateConfig())
.catch((e) => {
// If initialisation failed, attempting to `dispose()` this instance
// will too. Therefore, remove from the instance registry now, so we
// can still test async initialisation failures, without test failures
// telling us to `dispose()` the instance.
maybeInstanceRegistry?.delete(this);
throw e;
});
}
#handleReload() {
// Reload all connected live reload clients
for (const ws of this.#liveReloadServer.clients) {
ws.close(1012, "Service Restart");
}
// Close all existing web sockets on reload
for (const ws of this.#webSocketServer.clients) {
ws.close(1012, "Service Restart");
}
}
async #handleLoopbackCustomService(
request: Request,
customService: string
): Promise<Response> {
const slashIndex = customService.indexOf("/");
// TODO: technically may want to keep old versions around so can always
// recover this in case of setOptions()?
const workerIndex = parseInt(customService.substring(0, slashIndex));
const serviceKind = customService[slashIndex + 1] as CustomServiceKind;
const serviceName = customService.substring(slashIndex + 2);
let service: z.infer<typeof ServiceDesignatorSchema> | undefined;
if (serviceKind === CustomServiceKind.UNKNOWN) {
service =
this.#workerOpts[workerIndex]?.core.serviceBindings?.[serviceName];
} else if (serviceName === CUSTOM_SERVICE_KNOWN_OUTBOUND) {
service = this.#workerOpts[workerIndex]?.core.outboundService;
}
// Should only define custom service bindings if `service` is a function
assert(typeof service === "function");
try {
const response = await service(request);
// Validate return type as `service` is a user defined function
// TODO: should we validate outside this try/catch?
return z.instanceof(Response).parse(response);
} catch (e: any) {
// TODO: do we need to add `CF-Exception` header or something here?
// check what runtime does
return new Response(e?.stack ?? e, { status: 500 });
}
}
get #workerSrcOpts(): NameSourceOptions[] {
return this.#workerOpts.map<NameSourceOptions>(({ core }) => core);
}
#handleLoopback = async (
req: http.IncomingMessage,
res?: http.ServerResponse
): Promise<Response | undefined> => {
// Extract headers from request
const headers = new Headers();
for (const [name, values] of Object.entries(req.headers)) {
// These headers are unsupported in undici fetch requests, they're added
// automatically. For custom service bindings, we may pass this request
// straight through to another fetch so strip them now.
if (restrictedUndiciHeaders.includes(name)) continue;
if (Array.isArray(values)) {
for (const value of values) headers.append(name, value);
} else if (values !== undefined) {
headers.append(name, values);
}
}
// Extract cf blob (if any) from headers
const cfBlob = headers.get(HEADER_CF_BLOB);
headers.delete(HEADER_CF_BLOB);
assert(!Array.isArray(cfBlob)); // Only `Set-Cookie` headers are arrays
const cf = cfBlob ? JSON.parse(cfBlob) : undefined;
// Extract original URL passed to `fetch`
const url = new URL(
headers.get(CoreHeaders.ORIGINAL_URL) ?? req.url ?? "",
"http://localhost"
);
headers.delete(CoreHeaders.ORIGINAL_URL);
const noBody = req.method === "GET" || req.method === "HEAD";
const body = noBody ? undefined : safeReadableStreamFrom(req);
const request = new Request(url, {
method: req.method,
headers,
body,
duplex: "half",
cf,
});
let response: Response | undefined;
try {
const customService = request.headers.get(CoreHeaders.CUSTOM_SERVICE);
if (customService !== null) {
request.headers.delete(CoreHeaders.CUSTOM_SERVICE);
response = await this.#handleLoopbackCustomService(
request,
customService
);
} else if (url.pathname === "/core/error") {
response = await handlePrettyErrorRequest(
this.#log,
this.#workerSrcOpts,
request
);
} else if (url.pathname === "/core/log") {
// Safety of `!`: `parseInt(null)` is `NaN`
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const level = parseInt(request.headers.get(SharedHeaders.LOG_LEVEL)!);
assert(
LogLevel.NONE <= level && level <= LogLevel.VERBOSE,
`Expected ${SharedHeaders.LOG_LEVEL} header to be log level, got ${level}`
);
const logLevel = level as LogLevel;
let message = await request.text();
if (!colors$.enabled) message = stripAnsi(message);
this.#log.logWithLevel(logLevel, message);
response = new Response(null, { status: 204 });
}
} catch (e: any) {
this.#log.error(e);
res?.writeHead(500);
res?.end(e?.stack ?? String(e));
return;
}
if (res !== undefined) {
if (response === undefined) {
res.writeHead(404);
res.end();
} else {
await writeResponse(response, res);
}
}
return response;
};
#handleLoopbackUpgrade = async (
req: http.IncomingMessage,
socket: Duplex,
head: Buffer
) => {
// Only interested in pathname so base URL doesn't matter
const { pathname } = new URL(req.url ?? "", "http://localhost");
// If this is the path for live-reload, handle the request
if (pathname === "/cdn-cgi/mf/reload") {
this.#liveReloadServer.handleUpgrade(req, socket, head, (ws) => {
this.#liveReloadServer.emit("connection", ws, req);
});
return;
}
// Otherwise, try handle the request in a worker
const response = await this.#handleLoopback(req);
// Check web socket response was returned
const webSocket = response?.webSocket;
if (response?.status === 101 && webSocket) {
// Accept and couple the Web Socket
this.#webSocketExtraHeaders.set(req, response.headers);
this.#webSocketServer.handleUpgrade(req, socket, head, (ws) => {
void coupleWebSocket(ws, webSocket);
this.#webSocketServer.emit("connection", ws, req);
});
return;
}
// Otherwise, we'll be returning a regular HTTP response
const res = new http.ServerResponse(req);
// `socket` is guaranteed to be an instance of `net.Socket`:
// https://nodejs.org/api/http.html#event-upgrade_1
assert(socket instanceof net.Socket);
res.assignSocket(socket);
// If no response was provided, or it was an "ok" response, log an error
if (!response || response.ok) {
res.writeHead(500);
res.end();
this.#log.error(
new TypeError(
"Web Socket request did not return status 101 Switching Protocols response with Web Socket"
)
);
return;
}
// Otherwise, send the response as is (e.g. unauthorised)
await writeResponse(response, res);
};
async #getLoopbackPort(): Promise<number> {
// This function must be run with `#runtimeMutex` held
// Start loopback server (how the runtime accesses Node.js) using the same
// host as the main runtime server. This means we can use the loopback
// server for live reload updates too.
const loopbackHost = this.#sharedOpts.core.host ?? DEFAULT_HOST;
// If we've already started the loopback server...
if (this.#loopbackServer !== undefined) {
// ...and it's using the correct host, reuse it
if (this.#loopbackHost === loopbackHost) {
return getServerPort(this.#loopbackServer);
}
// Otherwise, stop it, and create a new one
await this.#stopLoopbackServer();
}
this.#loopbackServer = await this.#startLoopbackServer(loopbackHost);
this.#loopbackHost = loopbackHost;
return getServerPort(this.#loopbackServer);
}
#startLoopbackServer(hostname: string): Promise<StoppableServer> {
if (hostname === "*") hostname = "::";
return new Promise((resolve) => {
const server = stoppable(
http.createServer(this.#handleLoopback),
/* grace */ 0
);
server.on("upgrade", this.#handleLoopbackUpgrade);
server.listen(0, hostname, () => resolve(server));
});
}
#stopLoopbackServer(): Promise<void> {
return new Promise((resolve, reject) => {
assert(this.#loopbackServer !== undefined);
this.#loopbackServer.stop((err) => (err ? reject(err) : resolve()));
});
}
#getSocketAddress(
id: SocketIdentifier,
previousRequestedPort: number | undefined,
host = DEFAULT_HOST,
requestedPort?: number
) {
// If `port` is set to `0`, was previously set to `0`, and we previously had
// a port for this socket, reuse that random port
if (requestedPort === 0 && previousRequestedPort === 0) {
requestedPort = this.#socketPorts?.get(id);
}
// Otherwise, default to a new random port
return `${host}:${requestedPort ?? 0}`;
}
async #assembleConfig(loopbackPort: number): Promise<Config> {
const allWorkerOpts = this.#workerOpts;
const sharedOpts = this.#sharedOpts;
sharedOpts.core.cf = await setupCf(this.#log, sharedOpts.core.cf);
const durableObjectClassNames = getDurableObjectClassNames(allWorkerOpts);
const queueConsumers = getQueueConsumers(allWorkerOpts);
const allWorkerRoutes = getWorkerRoutes(allWorkerOpts);
const workerNames = [...allWorkerRoutes.keys()];
// Use Map to dedupe services by name
const services = new Map<string, Service>();
const sockets: Socket[] = [await configureEntrySocket(sharedOpts.core)];
// Bindings for `ProxyServer` Durable Object
const proxyBindings: Worker_Binding[] = [];
for (let i = 0; i < allWorkerOpts.length; i++) {
const workerOpts = allWorkerOpts[i];
const workerName = workerOpts.core.name ?? "";
// Collect all bindings from this worker
const workerBindings: Worker_Binding[] = [];
const additionalModules: Worker_Module[] = [];
for (const [key, plugin] of PLUGIN_ENTRIES) {
// @ts-expect-error `CoreOptionsSchema` has required options which are
// missing in other plugins' options.
const pluginBindings = await plugin.getBindings(workerOpts[key], i);
if (pluginBindings !== undefined) {
for (const binding of pluginBindings) {
workerBindings.push(binding);
// Only `workerd` native bindings need to be proxied, the rest are
// already supported by Node.js (e.g. json, text/data blob, wasm)
if (isNativeTargetBinding(binding)) {
proxyBindings.push(buildProxyBinding(key, workerName, binding));
}
}
if (key === "kv") {
// Add "__STATIC_CONTENT_MANIFEST" module if sites enabled
const module = maybeGetSitesManifestModule(pluginBindings);
if (module !== undefined) additionalModules.push(module);
}
}
}
// Collect all services required by this worker
const pluginServicesOptionsBase: Omit<
PluginServicesOptions<z.ZodTypeAny, undefined>,
"options" | "sharedOptions"
> = {
log: this.#log,
workerBindings,
workerIndex: i,
additionalModules,
tmpPath: this.#tmpPath,
workerNames,
durableObjectClassNames,
queueConsumers,
};
for (const [key, plugin] of PLUGIN_ENTRIES) {
const pluginServices = await plugin.getServices({
...pluginServicesOptionsBase,
// @ts-expect-error `CoreOptionsSchema` has required options which are
// missing in other plugins' options.
options: workerOpts[key],
// @ts-expect-error `QueuesPlugin` doesn't define shared options
sharedOptions: sharedOpts[key],
});
if (pluginServices !== undefined) {
for (const service of pluginServices) {
if (service.name !== undefined && !services.has(service.name)) {
services.set(service.name, service);
if (key !== DURABLE_OBJECTS_PLUGIN_NAME) {
const maybeBindings = getInternalDurableObjectProxyBindings(
key,
service
);
if (maybeBindings !== undefined) {
proxyBindings.push(...maybeBindings);
}
}
}
}
}
}
// Allow additional sockets to be opened directly to specific workers,
// bypassing Miniflare's entry worker.
const { unsafeDirectHost, unsafeDirectPort } = workerOpts.core;
if (unsafeDirectHost !== undefined || unsafeDirectPort !== undefined) {
const name = getDirectSocketName(i);
const address = this.#getSocketAddress(
name,
// We don't attempt to reuse allocated ports for `unsafeDirectPort: 0`
// as there's not always a clear mapping between current/previous
// worker options. We could do it by index, names, script, etc.
// This is an unsafe option primarily intended for Wrangler's
// inspector proxy, which will usually set this value to `9229`.
// We could consider changing this in the future.
/* previousRequestedPort */ undefined,
unsafeDirectHost,
unsafeDirectPort