-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathDevServer.zig
7657 lines (6804 loc) · 318 KB
/
DevServer.zig
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
//! Instance of the development server. Attaches to an instance of `Bun.serve`,
//! controlling bundler, routing, and hot module reloading.
//!
//! Reprocessing files that did not change is banned; by having perfect
//! incremental tracking over the project, editing a file's contents (asides
//! adjusting imports) must always rebundle only that one file.
//!
//! All work is held in-memory, using manually managed data-oriented design.
//! For questions about DevServer, please consult the delusional @paperclover
pub const DevServer = @This();
pub const debug = bun.Output.Scoped(.DevServer, false);
pub const igLog = bun.Output.scoped(.IncrementalGraph, false);
const DebugHTTPServer = @import("../bun.js/api/server.zig").DebugHTTPServer;
pub const Options = struct {
/// Arena must live until DevServer.deinit()
arena: Allocator,
root: [:0]const u8,
vm: *VirtualMachine,
framework: bake.Framework,
bundler_options: bake.SplitBundlerOptions,
// Debugging features
dump_sources: ?[]const u8 = if (Environment.isDebug) ".bake-debug" else null,
dump_state_on_crash: ?bool = null,
};
// The fields `client_graph`, `server_graph`, `directory_watchers`, and `assets`
// all use `@fieldParentPointer` to access DevServer's state. This pattern has
// made it easier to group related fields together, but one must remember those
// structures still depend on the DevServer pointer.
/// Used for all server-wide allocations. In debug, is is backed by a scope. Thread-safe.
allocator: Allocator,
/// All methods are no-op in release builds.
allocation_scope: AllocationScope,
/// Absolute path to project root directory. For the HMR
/// runtime, its module IDs are strings relative to this.
root: []const u8,
/// Hex string generated by hashing the framework config and bun revision.
/// Emebedding in client bundles and sent when the HMR Socket is opened;
/// When the value mismatches the page is forcibly reloaded.
configuration_hash_key: [16]u8,
/// The virtual machine (global object) to execute code in.
vm: *VirtualMachine,
/// May be `null` if not attached to an HTTP server yet. When no server is
/// available, functions taking in requests and responses are unavailable.
/// However, a lot of testing in this mode is missing, so it may hit assertions.
server: ?bun.JSC.API.AnyServer,
/// Contains the tree of routes. This structure contains FileIndex
router: FrameworkRouter,
/// Every navigatable route has bundling state here.
route_bundles: ArrayListUnmanaged(RouteBundle),
/// All access into IncrementalGraph is guarded by a DebugThreadLock. This is
/// only a debug assertion as contention to this is always a bug; If a bundle is
/// active and a file is changed, that change is placed into the next bundle.
graph_safety_lock: bun.DebugThreadLock,
client_graph: IncrementalGraph(.client),
server_graph: IncrementalGraph(.server),
/// State populated during bundling and hot updates. Often cleared
incremental_result: IncrementalResult,
/// Quickly retrieve a framework route's index from its entry point file. These
/// are populated as the routes are discovered. The route may not be bundled OR
/// navigatable, such as the case where a layout's index is looked up.
route_lookup: AutoArrayHashMapUnmanaged(IncrementalGraph(.server).FileIndex, RouteIndexAndRecurseFlag),
/// This acts as a duplicate of the lookup table in uws, but only for HTML routes
/// Used to identify what route a connected WebSocket is on, so that only
/// the active pages are notified of a hot updates.
html_router: HTMLRouter,
/// Assets are accessible via `/_bun/asset/<key>`
/// This store is not thread safe.
assets: Assets,
/// Similar to `assets`, specialized for the additional needs of source mappings.
source_maps: SourceMapStore,
// /// Allocations that require a reference count.
// ref_strings: RefString.Store,
/// All bundling failures are stored until a file is saved and rebuilt.
/// They are stored in the wire format the HMR runtime expects so that
/// serialization only happens once.
bundling_failures: std.ArrayHashMapUnmanaged(
SerializedFailure,
void,
SerializedFailure.ArrayHashContextViaOwner,
false,
) = .{},
/// When set, nothing is ever bundled for the server-side,
/// and DevSever acts purely as a frontend bundler.
frontend_only: bool,
/// The Plugin API is missing a way to attach filesystem watchers (addWatchFile)
/// This special case makes `bun-plugin-tailwind` work, which is a requirement
/// to ship initial incremental bundling support for HTML files.
has_tailwind_plugin_hack: ?bun.StringArrayHashMapUnmanaged(void) = null,
// These values are handles to the functions in `hmr-runtime-server.ts`.
// For type definitions, see `./bake.private.d.ts`
server_fetch_function_callback: JSC.Strong,
server_register_update_callback: JSC.Strong,
// Watching
bun_watcher: *bun.Watcher,
directory_watchers: DirectoryWatchStore,
watcher_atomics: WatcherAtomics,
testing_batch_events: union(enum) {
disabled,
enable_after_bundle,
enabled: TestingBatch,
},
/// Number of bundles that have been executed. This is currently not read, but
/// will be used later to determine when to invoke graph garbage collection.
generation: usize = 0,
/// Displayed in the HMR success indicator
bundles_since_last_error: usize = 0,
framework: bake.Framework,
bundler_options: bake.SplitBundlerOptions,
// Each logical graph gets its own bundler configuration
server_transpiler: Transpiler,
client_transpiler: Transpiler,
ssr_transpiler: Transpiler,
/// The log used by all `server_transpiler`, `client_transpiler` and `ssr_transpiler`.
/// Note that it is rarely correct to write messages into it. Instead, associate
/// messages with the IncrementalGraph file or Route using `SerializedFailure`
log: Log,
plugin_state: enum {
/// Should ask server for plugins. Once plugins are loaded, the plugin
/// pointer is written into `server_transpiler.options.plugin`
unknown,
// These two states mean that `server.getOrLoadPlugins()` was called.
pending,
loaded,
/// Currently, this represents a degraded state where no bundle can
/// be correctly executed because the plugins did not load successfully.
err,
},
/// There is only ever one bundle executing at the same time, since all bundles
/// inevitably share state. This bundle is asynchronous, storing its state here
/// while in-flight. All allocations held by `.bv2.graph.heap`'s arena
current_bundle: ?struct {
bv2: *BundleV2,
/// Information BundleV2 needs to finalize the bundle
start_data: bun.bundle_v2.DevServerInput,
/// Started when the bundle was queued
timer: std.time.Timer,
/// If any files in this bundle were due to hot-reloading, some extra work
/// must be done to inform clients to reload routes. When this is false,
/// all entry points do not have bundles yet.
had_reload_event: bool,
/// After a bundle finishes, these requests will be continued, either
/// calling their handler on success or sending the error page on failure.
/// Owned by `deferred_request_pool` in DevServer.
requests: DeferredRequest.List,
/// Resolution failures are grouped by incremental graph file index.
/// Unlike parse failures (`handleParseTaskFailure`), the resolution
/// failures can be created asynchronously, and out of order.
resolution_failure_entries: AutoArrayHashMapUnmanaged(SerializedFailure.Owner.Packed, bun.logger.Log),
},
/// When `current_bundle` is non-null and new requests to bundle come in,
/// those are temporaried here. When the current bundle is finished, it
/// will immediately enqueue this.
next_bundle: struct {
/// A list of `RouteBundle`s which have active requests to bundle it.
route_queue: AutoArrayHashMapUnmanaged(RouteBundle.Index, void),
/// If a reload event exists and should be drained. The information
/// for this watch event is in one of the `watch_events`
reload_event: ?*HotReloadEvent,
/// The list of requests that are blocked on this bundle.
requests: DeferredRequest.List,
},
deferred_request_pool: bun.HiveArray(DeferredRequest.Node, DeferredRequest.max_preallocated).Fallback,
/// UWS can handle closing the websocket connections themselves
active_websocket_connections: std.AutoHashMapUnmanaged(*HmrSocket, void),
relative_path_buf_lock: bun.DebugThreadLock,
relative_path_buf: bun.PathBuffer,
// Debugging
dump_dir: if (bun.FeatureFlags.bake_debugging_features) ?std.fs.Dir else void,
/// Reference count to number of active sockets with the visualizer enabled.
emit_visualizer_events: u32,
has_pre_crash_handler: bool,
/// Perfect incremental bundling implies that there are zero bugs in the
/// code that bundles, watches, and rebuilds routes and client side code.
///
/// More specifically, when this is false, DevServer will run a full rebundle
/// when a user force-refreshes an error page. In a perfect system, a rebundle
/// could not possibly fix the build. But since builds are NOT perfect, this
/// could very well be the case.
///
/// DISABLED in releases, ENABLED in debug.
/// Can be enabled with env var `BUN_ASSUME_PERFECT_INCREMENTAL=1`
assume_perfect_incremental_bundling: bool = false,
pub const internal_prefix = "/_bun";
/// Assets which are routed to the `Assets` storage.
pub const asset_prefix = internal_prefix ++ "/asset";
/// Client scripts are available at `/_bun/client/{name}-{rbi}{generation}.js`
/// where:
/// - `name` is the display name of the route, such as "index" or
/// "about". It is ignored when routing.
/// - `rbi` is the route bundle index, in padded hex (e.g. `00000001`)
/// - `generation` which is initialized to a random value. This value is
/// re-randomized whenever `client_bundle` is invalidated.
///
/// Example: `/_bun/client/index-00000000f209a20e.js`
pub const client_prefix = internal_prefix ++ "/client";
pub const RouteBundle = struct {
pub const Index = bun.GenericIndex(u30, RouteBundle);
server_state: State,
/// There are two distinct types of route bundles.
data: union(enum) {
/// FrameworkRouter provided route
framework: Framework,
/// HTMLBundle provided route
html: HTML,
},
/// Generated lazily when the client JS is requested.
/// Invalidated when a downstream client module updates.
client_bundle: ?*StaticRoute,
/// If the client tries to load a script with the wrong generation, it will
/// receive a bundle that instantly reloads the page, implying a bundle
/// change has occurred while fetching the script.
client_script_generation: u32,
/// Reference count of how many HmrSockets say they are on this route. This
/// allows hot-reloading events to reduce the amount of times it traces the
/// graph.
active_viewers: u32,
pub const Framework = struct {
route_index: Route.Index,
/// Cached to avoid re-creating the array every request.
/// TODO: Invalidated when a layout is added or removed from this route.
cached_module_list: JSC.Strong,
/// Cached to avoid re-creating the string every request.
/// TODO: Invalidated when any client file associated with the route is updated.
cached_client_bundle_url: JSC.Strong,
/// Cached to avoid re-creating the array every request.
/// Invalidated when the list of CSS files changes.
cached_css_file_array: JSC.Strong,
/// When state == .evaluation_failure, this is populated with the route
/// evaluation error mirrored in the dev server hash map
evaluate_failure: ?SerializedFailure,
};
pub const HTML = struct {
/// DevServer increments the ref count of this bundle
html_bundle: *HTMLBundle.HTMLBundleRoute,
bundled_file: IncrementalGraph(.client).FileIndex,
/// Invalidated when the HTML file is modified, but not it's imports.
/// The style tag is injected here.
script_injection_offset: ByteOffset.Optional,
/// The HTML file bundled, from the bundler.
bundled_html_text: ?[]const u8,
/// Derived from `bundled_html_text` + `client_script_generation`
/// and css information. Invalidated when:
/// - The HTML file itself modified.
/// - The list of CSS files changes.
/// - Any downstream file is rebundled.
cached_response: ?*StaticRoute,
const ByteOffset = bun.GenericIndex(u32, u8);
};
/// A union is not used so that `bundler_failure_logs` can re-use memory, as
/// this state frequently changes between `loaded` and the failure variants.
pub const State = enum {
/// In development mode, routes are lazily built. This state implies a
/// build of this route has never been run. It is possible to bundle the
/// route entry point and still have an unqueued route if another route
/// imports this one. This state is implied if `FrameworkRouter.Route`
/// has no bundle index assigned.
unqueued,
/// A bundle associated with this route is happening
bundling,
/// This route was flagged for bundling failures. There are edge cases
/// where a route can be disconnected from its failures, so the route
/// imports has to be traced to discover if possible failures still
/// exist.
possible_bundling_failures,
/// Loading the module at runtime had a failure. The error can be
/// cleared by editing any file in the same hot-reloading boundary.
evaluation_failure,
/// Calling the request function may error, but that error will not be
/// at fault of bundling, nor would re-bundling change anything.
loaded,
};
pub const UnresolvedIndex = union(enum) {
/// FrameworkRouter provides a fullstack server-side route
framework: FrameworkRouter.Route.Index,
/// HTMLBundle provides a frontend-only route, SPA-style
html: *HTMLBundle.HTMLBundleRoute,
};
pub fn deinit(rb: *RouteBundle, allocator: Allocator) void {
if (rb.client_bundle) |blob| blob.deref();
switch (rb.data) {
.framework => |*fw| {
fw.cached_client_bundle_url.deinit();
fw.cached_css_file_array.deinit();
fw.cached_module_list.deinit();
},
.html => |*html| {
if (html.bundled_html_text) |text| {
allocator.free(text);
}
if (html.cached_response) |cached_response| {
cached_response.deref();
}
html.html_bundle.deref();
},
}
}
pub fn invalidateClientBundle(self: *RouteBundle) void {
if (self.client_bundle) |bundle| {
bundle.deref();
self.client_bundle = null;
}
self.client_script_generation = std.crypto.random.int(u32);
switch (self.data) {
.framework => |*fw| fw.cached_client_bundle_url.clearWithoutDeallocation(),
.html => |*html| if (html.cached_response) |cached_response| {
cached_response.deref();
html.cached_response = null;
},
}
}
pub fn memoryCost(self: *const RouteBundle) usize {
var cost: usize = @sizeOf(RouteBundle);
if (self.client_bundle) |bundle| cost += bundle.memoryCost();
switch (self.data) {
.framework => {
// the JSC.Strong children do not support memoryCost. likely not needed
// .evaluate_failure is not owned
},
.html => |*html| {
if (html.bundled_html_text) |text| cost += text.len;
if (html.cached_response) |cached_response| cost += cached_response.memoryCost();
},
}
return cost;
}
};
/// DevServer is stored on the heap, storing its allocator.
pub fn init(options: Options) bun.JSOOM!*DevServer {
const unchecked_allocator = bun.default_allocator;
bun.analytics.Features.dev_server +|= 1;
var dump_dir = if (bun.FeatureFlags.bake_debugging_features)
if (options.dump_sources) |dir|
std.fs.cwd().makeOpenPath(dir, .{}) catch |err| dir: {
bun.handleErrorReturnTrace(err, @errorReturnTrace());
Output.warn("Could not open directory for dumping sources: {}", .{err});
break :dir null;
}
else
null;
errdefer if (bun.FeatureFlags.bake_debugging_features) if (dump_dir) |*dir| dir.close();
const separate_ssr_graph = if (options.framework.server_components) |sc| sc.separate_ssr_graph else false;
const dev = bun.new(DevServer, .{
.allocator = undefined,
// 'init' is a no-op in release
.allocation_scope = AllocationScope.init(unchecked_allocator),
.root = options.root,
.vm = options.vm,
.server = null,
.directory_watchers = .empty,
.server_fetch_function_callback = .empty,
.server_register_update_callback = .empty,
.generation = 0,
.graph_safety_lock = .unlocked,
.dump_dir = dump_dir,
.framework = options.framework,
.bundler_options = options.bundler_options,
.emit_visualizer_events = 0,
.has_pre_crash_handler = bun.FeatureFlags.bake_debugging_features and
options.dump_state_on_crash orelse
bun.getRuntimeFeatureFlag("BUN_DUMP_STATE_ON_CRASH"),
.frontend_only = options.framework.file_system_router_types.len == 0,
.client_graph = .empty,
.server_graph = .empty,
.incremental_result = .empty,
.route_lookup = .empty,
.route_bundles = .empty,
.html_router = .empty,
.active_websocket_connections = .empty,
.current_bundle = null,
.next_bundle = .{
.route_queue = .empty,
.reload_event = null,
.requests = .{},
},
.assets = .{
.path_map = .empty,
.files = .empty,
.refs = .empty,
},
.source_maps = .empty,
.plugin_state = .unknown,
.bundling_failures = .{},
.assume_perfect_incremental_bundling = if (bun.Environment.isDebug)
if (bun.getenvZ("BUN_ASSUME_PERFECT_INCREMENTAL")) |env|
!bun.strings.eqlComptime(env, "0")
else
true
else
bun.getRuntimeFeatureFlag("BUN_ASSUME_PERFECT_INCREMENTAL"),
.relative_path_buf_lock = .unlocked,
.testing_batch_events = .disabled,
.server_transpiler = undefined,
.client_transpiler = undefined,
.ssr_transpiler = undefined,
.bun_watcher = undefined,
.configuration_hash_key = undefined,
.router = undefined,
.watcher_atomics = undefined,
.log = undefined,
.deferred_request_pool = undefined,
.relative_path_buf = undefined,
});
errdefer bun.destroy(dev);
const allocator = dev.allocation_scope.allocator();
dev.allocator = allocator;
dev.log = .init(allocator);
dev.deferred_request_pool = .init(allocator);
const global = dev.vm.global;
assert(dev.server_graph.owner() == dev);
assert(dev.client_graph.owner() == dev);
assert(dev.directory_watchers.owner() == dev);
dev.graph_safety_lock.lock();
defer dev.graph_safety_lock.unlock();
const generic_action = "while initializing development server";
const fs = bun.fs.FileSystem.init(options.root) catch |err|
return global.throwError(err, generic_action);
dev.bun_watcher = Watcher.init(DevServer, dev, fs, bun.default_allocator) catch |err|
return global.throwError(err, "while initializing file watcher for development server");
errdefer dev.bun_watcher.deinit(false);
dev.bun_watcher.start() catch |err|
return global.throwError(err, "while initializing file watcher thread for development server");
dev.watcher_atomics = WatcherAtomics.init(dev);
// This causes a memory leak, but the allocator is otherwise used on multiple threads.
const transpiler_allocator = bun.default_allocator;
dev.framework.initTranspiler(transpiler_allocator, &dev.log, .development, .server, &dev.server_transpiler, &dev.bundler_options.server) catch |err|
return global.throwError(err, generic_action);
dev.server_transpiler.options.dev_server = dev;
dev.framework.initTranspiler(
transpiler_allocator,
&dev.log,
.development,
.client,
&dev.client_transpiler,
&dev.bundler_options.client,
) catch |err|
return global.throwError(err, generic_action);
dev.client_transpiler.options.dev_server = dev;
dev.server_transpiler.resolver.watcher = dev.bun_watcher.getResolveWatcher();
dev.client_transpiler.resolver.watcher = dev.bun_watcher.getResolveWatcher();
if (separate_ssr_graph) {
dev.framework.initTranspiler(transpiler_allocator, &dev.log, .development, .ssr, &dev.ssr_transpiler, &dev.bundler_options.ssr) catch |err|
return global.throwError(err, generic_action);
dev.ssr_transpiler.options.dev_server = dev;
dev.ssr_transpiler.resolver.watcher = dev.bun_watcher.getResolveWatcher();
}
assert(dev.server_transpiler.resolver.opts.target != .browser);
assert(dev.client_transpiler.resolver.opts.target == .browser);
dev.framework = dev.framework.resolve(&dev.server_transpiler.resolver, &dev.client_transpiler.resolver, options.arena) catch {
if (dev.framework.is_built_in_react)
try bake.Framework.addReactInstallCommandNote(&dev.log);
return global.throwValue(dev.log.toJSAggregateError(global, bun.String.static("Framework is missing required files!")));
};
errdefer dev.route_lookup.clearAndFree(allocator);
errdefer dev.client_graph.deinit(allocator);
errdefer dev.server_graph.deinit(allocator);
dev.configuration_hash_key = hash_key: {
var hash = std.hash.Wyhash.init(128);
if (bun.Environment.isDebug) {
const stat = bun.sys.stat(bun.selfExePath() catch |e|
Output.panic("unhandled {}", .{e})).unwrap() catch |e|
Output.panic("unhandled {}", .{e});
bun.writeAnyToHasher(&hash, stat.mtime());
hash.update(bake.getHmrRuntime(.client).code);
hash.update(bake.getHmrRuntime(.server).code);
} else {
hash.update(bun.Environment.git_sha_short);
}
for (dev.framework.file_system_router_types) |fsr| {
bun.writeAnyToHasher(&hash, fsr.allow_layouts);
bun.writeAnyToHasher(&hash, fsr.ignore_underscores);
hash.update(fsr.entry_server);
hash.update(&.{0});
hash.update(fsr.entry_client orelse "");
hash.update(&.{0});
hash.update(fsr.prefix);
hash.update(&.{0});
hash.update(fsr.root);
hash.update(&.{0});
for (fsr.extensions) |ext| {
hash.update(ext);
hash.update(&.{0});
}
hash.update(&.{0});
for (fsr.ignore_dirs) |dir| {
hash.update(dir);
hash.update(&.{0});
}
hash.update(&.{0});
}
if (dev.framework.server_components) |sc| {
bun.writeAnyToHasher(&hash, true);
bun.writeAnyToHasher(&hash, sc.separate_ssr_graph);
hash.update(sc.client_register_server_reference);
hash.update(&.{0});
hash.update(sc.server_register_client_reference);
hash.update(&.{0});
hash.update(sc.server_register_server_reference);
hash.update(&.{0});
hash.update(sc.server_runtime_import);
hash.update(&.{0});
} else {
bun.writeAnyToHasher(&hash, false);
}
if (dev.framework.react_fast_refresh) |rfr| {
bun.writeAnyToHasher(&hash, true);
hash.update(rfr.import_source);
} else {
bun.writeAnyToHasher(&hash, false);
}
for (dev.framework.built_in_modules.keys(), dev.framework.built_in_modules.values()) |k, v| {
hash.update(k);
hash.update(&.{0});
bun.writeAnyToHasher(&hash, std.meta.activeTag(v));
hash.update(switch (v) {
inline else => |data| data,
});
hash.update(&.{0});
}
hash.update(&.{0});
break :hash_key std.fmt.bytesToHex(std.mem.asBytes(&hash.final()), .lower);
};
// Add react fast refresh if needed. This is the first file on the client side,
// as it will be referred to by index.
if (dev.framework.react_fast_refresh) |rfr| {
assert(try dev.client_graph.insertStale(rfr.import_source, false) == IncrementalGraph(.client).react_refresh_index);
}
if (!dev.frontend_only) {
dev.initServerRuntime();
}
// Initialize FrameworkRouter
dev.router = router: {
var types = try std.ArrayListUnmanaged(FrameworkRouter.Type).initCapacity(allocator, options.framework.file_system_router_types.len);
errdefer types.deinit(allocator);
for (options.framework.file_system_router_types, 0..) |fsr, i| {
const buf = bun.PathBufferPool.get();
defer bun.PathBufferPool.put(buf);
const joined_root = bun.path.joinAbsStringBuf(dev.root, buf, &.{fsr.root}, .auto);
const entry = dev.server_transpiler.resolver.readDirInfoIgnoreError(joined_root) orelse
continue;
const server_file = try dev.server_graph.insertStaleExtra(fsr.entry_server, false, true);
try types.append(allocator, .{
.abs_root = bun.strings.withoutTrailingSlash(entry.abs_path),
.prefix = fsr.prefix,
.ignore_underscores = fsr.ignore_underscores,
.ignore_dirs = fsr.ignore_dirs,
.extensions = fsr.extensions,
.style = fsr.style,
.allow_layouts = fsr.allow_layouts,
.server_file = toOpaqueFileId(.server, server_file),
.client_file = if (fsr.entry_client) |client|
toOpaqueFileId(.client, try dev.client_graph.insertStale(client, false)).toOptional()
else
.none,
.server_file_string = .empty,
});
try dev.route_lookup.put(allocator, server_file, .{
.route_index = FrameworkRouter.Route.Index.init(@intCast(i)),
.should_recurse_when_visiting = true,
});
}
break :router try FrameworkRouter.initEmpty(dev.root, types.items, allocator);
};
// TODO: move scanning to be one tick after server startup. this way the
// line saying the server is ready shows quicker, and route errors show up
// after that line.
try dev.scanInitialRoutes();
if (bun.FeatureFlags.bake_debugging_features and dev.has_pre_crash_handler)
try bun.crash_handler.appendPreCrashHandler(DevServer, dev, dumpStateDueToCrash);
return dev;
}
pub fn deinit(dev: *DevServer) void {
dev_server_deinit_count_for_testing +|= 1;
const allocator = dev.allocator;
const discard = voidFieldTypeDiscardHelper;
_ = VoidFieldTypes(DevServer){
.root = {},
.allocator = {},
.allocation_scope = {}, // deinit at end
.configuration_hash_key = {},
.plugin_state = {},
.generation = {},
.bundles_since_last_error = {},
.emit_visualizer_events = {},
.deferred_request_pool = {},
.frontend_only = {},
.vm = {},
.server = {},
.server_transpiler = {},
.client_transpiler = {},
.ssr_transpiler = {},
.framework = {},
.bundler_options = {},
.assume_perfect_incremental_bundling = {},
.relative_path_buf = {},
.relative_path_buf_lock = {},
.graph_safety_lock = dev.graph_safety_lock.lock(),
.bun_watcher = dev.bun_watcher.deinit(true),
.dump_dir = if (bun.FeatureFlags.bake_debugging_features) if (dev.dump_dir) |*dir| dir.close(),
.log = dev.log.deinit(),
.server_fetch_function_callback = dev.server_fetch_function_callback.deinit(),
.server_register_update_callback = dev.server_register_update_callback.deinit(),
.has_pre_crash_handler = if (dev.has_pre_crash_handler)
bun.crash_handler.removePreCrashHandler(dev),
.router = {
dev.router.deinit(allocator);
},
.route_bundles = {
for (dev.route_bundles.items) |*rb| {
rb.deinit(allocator);
}
dev.route_bundles.deinit(allocator);
},
.server_graph = dev.server_graph.deinit(allocator),
.client_graph = dev.client_graph.deinit(allocator),
.assets = dev.assets.deinit(allocator),
.incremental_result = discard(VoidFieldTypes(IncrementalResult){
.had_adjusted_edges = {},
.client_components_added = dev.incremental_result.client_components_added.deinit(allocator),
.framework_routes_affected = dev.incremental_result.framework_routes_affected.deinit(allocator),
.client_components_removed = dev.incremental_result.client_components_removed.deinit(allocator),
.failures_removed = dev.incremental_result.failures_removed.deinit(allocator),
.client_components_affected = dev.incremental_result.client_components_affected.deinit(allocator),
.failures_added = dev.incremental_result.failures_added.deinit(allocator),
.html_routes_soft_affected = dev.incremental_result.html_routes_soft_affected.deinit(allocator),
.html_routes_hard_affected = dev.incremental_result.html_routes_hard_affected.deinit(allocator),
}),
.has_tailwind_plugin_hack = if (dev.has_tailwind_plugin_hack) |*hack| {
hack.deinit(allocator);
},
.directory_watchers = {
// dev.directory_watchers.dependencies
for (dev.directory_watchers.watches.keys()) |dir_name| {
allocator.free(dir_name);
}
for (dev.directory_watchers.dependencies.items) |watcher| {
allocator.free(watcher.specifier);
}
dev.directory_watchers.watches.deinit(allocator);
dev.directory_watchers.dependencies.deinit(allocator);
dev.directory_watchers.dependencies_free_list.deinit(allocator);
},
.html_router = dev.html_router.map.deinit(dev.allocator),
.bundling_failures = {
for (dev.bundling_failures.keys()) |failure| {
failure.deinit(dev);
}
dev.bundling_failures.deinit(allocator);
},
.current_bundle = {
if (dev.current_bundle) |_| {
bun.debugAssert(false); // impossible to de-initialize this state correctly.
}
},
.next_bundle = {
var r = dev.next_bundle.requests.first;
while (r) |request| {
defer dev.deferred_request_pool.put(request);
// TODO: deinitializing in this state is almost certainly an assertion failure.
// This code is shipped in release because it is only reachable by experimenntal server components.
bun.debugAssert(request.data.handler != .server_handler);
request.data.deinit();
r = request.next;
}
dev.next_bundle.route_queue.deinit(allocator);
},
.route_lookup = dev.route_lookup.deinit(allocator),
.source_maps = {
for (dev.source_maps.entries.values()) |value| {
allocator.free(value.sourceContents());
allocator.free(value.file_paths);
value.response.deref();
}
dev.source_maps.entries.deinit(allocator);
},
.active_websocket_connections = {
var it = dev.active_websocket_connections.keyIterator();
while (it.next()) |item| {
const s: *HmrSocket = item.*;
if (s.underlying) |websocket|
websocket.close();
}
dev.active_websocket_connections.deinit(allocator);
},
.watcher_atomics = for (&dev.watcher_atomics.events) |*event| {
event.dirs.deinit(dev.allocator);
event.files.deinit(dev.allocator);
event.extra_files.deinit(dev.allocator);
},
.testing_batch_events = switch (dev.testing_batch_events) {
.disabled => {},
.enabled => |*batch| {
batch.entry_points.deinit(allocator);
},
.enable_after_bundle => {},
},
};
dev.allocation_scope.deinit();
bun.destroy(dev);
}
/// Returns an estimation for how many bytes DevServer is explicitly aware of.
/// If this number stays constant but RSS grows, then there is a memory leak. If
/// this number grows out of control, then incremental garbage collection is not
/// good enough.
///
/// Memory measurements are important as DevServer has a long lifetime, but
/// unlike the HTTP server, it controls a lot of objects that are frequently
/// being added, removed, and changed (as the developer edits source files). It
/// is exponentially easy to mess up memory management.
pub fn memoryCost(dev: *DevServer) usize {
var cost: usize = @sizeOf(DevServer);
const discard = voidFieldTypeDiscardHelper;
// See https://github.com/ziglang/zig/issues/21879
_ = VoidFieldTypes(DevServer){
// does not contain pointers
.allocator = {},
.configuration_hash_key = {},
.graph_safety_lock = {},
.bun_watcher = {},
.watcher_atomics = {},
.plugin_state = {},
.generation = {},
.bundles_since_last_error = {},
.emit_visualizer_events = {},
.dump_dir = {},
.has_pre_crash_handler = {},
.frontend_only = {},
.server_fetch_function_callback = {},
.server_register_update_callback = {},
.deferred_request_pool = {},
.assume_perfect_incremental_bundling = {},
.relative_path_buf = {},
.relative_path_buf_lock = {},
// pointers that are not considered a part of DevServer
.vm = {},
.server = {},
.server_transpiler = {},
.client_transpiler = {},
.ssr_transpiler = {},
.log = {},
.framework = {},
.bundler_options = {},
.allocation_scope = {},
// to be counted.
.root = {
cost += dev.root.len;
},
.router = {
cost += dev.router.memoryCost();
},
.route_bundles = for (dev.route_bundles.items) |*bundle| {
cost += bundle.memoryCost();
},
.server_graph = {
cost += dev.server_graph.memoryCost();
},
.client_graph = {
cost += dev.client_graph.memoryCost();
},
.assets = {
cost += dev.assets.memoryCost();
},
.active_websocket_connections = {
cost += dev.active_websocket_connections.capacity() * @sizeOf(*HmrSocket);
},
.source_maps = {
cost += memoryCostArrayHashMap(dev.source_maps.entries);
for (dev.source_maps.entries.values()) |entry| {
cost += entry.response.memoryCost();
cost += memoryCostSlice(entry.sourceContents());
cost += memoryCostSlice(entry.file_paths); // do not re-count contents
}
},
.incremental_result = discard(VoidFieldTypes(IncrementalResult){
.had_adjusted_edges = {},
.client_components_added = {
cost += memoryCostArrayList(dev.incremental_result.client_components_added);
},
.framework_routes_affected = {
cost += memoryCostArrayList(dev.incremental_result.framework_routes_affected);
},
.client_components_removed = {
cost += memoryCostArrayList(dev.incremental_result.client_components_removed);
},
.failures_removed = {
cost += memoryCostArrayList(dev.incremental_result.failures_removed);
},
.client_components_affected = {
cost += memoryCostArrayList(dev.incremental_result.client_components_affected);
},
.failures_added = {
cost += memoryCostArrayList(dev.incremental_result.failures_added);
},
.html_routes_soft_affected = {
cost += memoryCostArrayList(dev.incremental_result.html_routes_soft_affected);
},
.html_routes_hard_affected = {
cost += memoryCostArrayList(dev.incremental_result.html_routes_hard_affected);
},
}),
.has_tailwind_plugin_hack = if (dev.has_tailwind_plugin_hack) |hack| {
cost += memoryCostArrayHashMap(hack);
},
.directory_watchers = {
cost += memoryCostArrayList(dev.directory_watchers.dependencies);
cost += memoryCostArrayList(dev.directory_watchers.dependencies_free_list);
cost += memoryCostArrayHashMap(dev.directory_watchers.watches);
for (dev.directory_watchers.dependencies.items) |dep| {
cost += dep.specifier.len;
}
for (dev.directory_watchers.watches.keys()) |dir_name| {
cost += dir_name.len;
}
},
.html_router = {
// std does not provide a way to measure exact allocation size of HashMapUnmanaged
cost += dev.html_router.map.capacity() * (@sizeOf(*HTMLBundle.HTMLBundleRoute) + @sizeOf([]const u8));
// DevServer does not count the referenced HTMLBundle.HTMLBundleRoutes
},
.bundling_failures = {
cost += memoryCostSlice(dev.bundling_failures.keys());
for (dev.bundling_failures.keys()) |failure| {
cost += failure.data.len;
}
},
// All entries are owned by the bundler arena, not DevServer, except for `requests`
.current_bundle = if (dev.current_bundle) |bundle| {
var r = bundle.requests.first;
while (r) |request| : (r = request.next) {
cost += @sizeOf(DeferredRequest.Node);
}
},
.next_bundle = {
var r = dev.next_bundle.requests.first;
while (r) |request| : (r = request.next) {
cost += @sizeOf(DeferredRequest.Node);
}
cost += memoryCostArrayHashMap(dev.next_bundle.route_queue);
},
.route_lookup = {
cost += memoryCostArrayHashMap(dev.route_lookup);
},
.testing_batch_events = switch (dev.testing_batch_events) {
.disabled => {},
.enabled => |batch| {
cost += memoryCostArrayHashMap(batch.entry_points.set);
},
.enable_after_bundle => {},
},
};
return cost;
}
fn memoryCostArrayList(slice: anytype) usize {
return slice.capacity * @sizeOf(@typeInfo(@TypeOf(slice.items)).pointer.child);
}
fn memoryCostSlice(slice: anytype) usize {
return slice.len * @sizeOf(@typeInfo(@TypeOf(slice)).pointer.child);
}
fn memoryCostArrayHashMap(map: anytype) usize {
return @TypeOf(map.entries).capacityInBytes(map.entries.capacity);
}
fn initServerRuntime(dev: *DevServer) void {
const runtime = bun.String.static(bun.bake.getHmrRuntime(.server).code);
const interface = c.BakeLoadInitialServerCode(
@ptrCast(dev.vm.global),
runtime,
if (dev.framework.server_components) |sc| sc.separate_ssr_graph else false,
) catch |err| {
dev.vm.printErrorLikeObjectToConsole(dev.vm.global.takeException(err));
@panic("Server runtime failed to start. The above error is always a bug in Bun");
};
if (!interface.isObject()) @panic("Internal assertion failure: expected interface from HMR runtime to be an object");
const fetch_function = interface.get(dev.vm.global, "handleRequest") catch null orelse
@panic("Internal assertion failure: expected interface from HMR runtime to contain handleRequest");
bun.assert(fetch_function.isCallable());
dev.server_fetch_function_callback = JSC.Strong.create(fetch_function, dev.vm.global);
const register_update = interface.get(dev.vm.global, "registerUpdate") catch null orelse
@panic("Internal assertion failure: expected interface from HMR runtime to contain registerUpdate");
dev.server_register_update_callback = JSC.Strong.create(register_update, dev.vm.global);
fetch_function.ensureStillAlive();
register_update.ensureStillAlive();
}
/// Deferred one tick so that the server can be up faster
fn scanInitialRoutes(dev: *DevServer) !void {
try dev.router.scanAll(
dev.allocator,
&dev.server_transpiler.resolver,
FrameworkRouter.InsertionContext.wrap(DevServer, dev),
);
try dev.server_graph.ensureStaleBitCapacity(true);
try dev.client_graph.ensureStaleBitCapacity(true);
}
/// Returns true if a catch-all handler was attached.
pub fn setRoutes(dev: *DevServer, server: anytype) !bool {
// TODO: all paths here must be prefixed with publicPath if set.
dev.server = bun.JSC.API.AnyServer.from(server);
const app = server.app.?;
const is_ssl = @typeInfo(@TypeOf(app)).pointer.child.is_ssl;
app.get(client_prefix ++ "/:route", *DevServer, dev, wrapGenericRequestHandler(onJsRequest, is_ssl));
app.get(asset_prefix ++ "/:asset", *DevServer, dev, wrapGenericRequestHandler(onAssetRequest, is_ssl));
app.get(internal_prefix ++ "/src/*", *DevServer, dev, wrapGenericRequestHandler(onSrcRequest, is_ssl));
app.post(internal_prefix ++ "/report_error", *DevServer, dev, wrapGenericRequestHandler(ErrorReportRequest.run, is_ssl));
app.any(internal_prefix, *DevServer, dev, wrapGenericRequestHandler(onNotFound, is_ssl));
app.ws(
internal_prefix ++ "/hmr",
dev,
0,
uws.WebSocketBehavior.Wrap(DevServer, HmrSocket, is_ssl).apply(.{}),
);
if (bun.FeatureFlags.bake_debugging_features) {
app.get(
internal_prefix ++ "/incremental_visualizer",
*DevServer,
dev,
wrapGenericRequestHandler(onIncrementalVisualizer, is_ssl),
);
app.get(
internal_prefix ++ "/iv",
*DevServer,