-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgea_node.cpp
More file actions
3428 lines (3108 loc) · 128 KB
/
Copy pathgea_node.cpp
File metadata and controls
3428 lines (3108 loc) · 128 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
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
// SPDX-License-Identifier: Apache-2.0
// node-compat native runtime.
//
// Emitted as its own generated C++ source by the node-compat geatsc plugin.
// This is the thin native layer the geatsc-compiled Node builtins
// (runtime/node/*.ts) sit on: a small reactor event loop and TCP/HTTP over
// sockets, written as proper namespaced OOP C++ (RAII, a polymorphic watcher
// interface — not C soup).
//
// Compiled under -std=gnu++20 -fno-exceptions -fno-rtti -Os.
#ifndef GEA_NODE_RUNTIME_INCLUDED
#define GEA_NODE_RUNTIME_INCLUDED
// The native carriers and byte adapters arrive from `gea_node.hpp`.
#include <algorithm>
#include <atomic>
#include <charconv>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <vector>
#include <arpa/inet.h>
#include <dlfcn.h>
#include <errno.h>
#include <execinfo.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <spawn.h>
#include <climits>
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
extern char **environ;
#include <unistd.h>
#ifdef __linux__
#include <sys/epoll.h>
#include <sys/random.h>
#endif
// ---------------------------------------------------------------------------
// The microtask queue.
//
// The loop below drains microtasks at six points, and the request path enqueues
// them. The compiler's runtime owns no queue of its own -- deliberately, a
// microtask queue being a host's concern rather than the language's -- so the
// queue is defined here, beside the loop that drains it, and
// `plugin/index.mjs` points the compiled program's `queueMicrotask` at the same
// symbol.
//
// It is reached through ONE spelling; a call site that named a queue directly
// would be a second authority on which one this reactor uses.
// ---------------------------------------------------------------------------
namespace gea::node {
inline std::deque<std::function<void()>> µtasks() {
static std::deque<std::function<void()>> queue;
return queue;
}
inline void queue_microtask(std::function<void()> callback) { microtasks().push_back(std::move(callback)); }
inline void drain_microtasks() {
// Popped before it runs: a microtask that enqueues another must not see its
// own entry still in the queue, and the drain has to reach the new one.
while (!microtasks().empty()) {
// Node's next-tick queue outranks both Promise reactions and host
// `queueMicrotask` callbacks. A callback may enqueue more ticks, so the
// priority boundary is every individual microtask, not just the start of
// one reactor turn.
drain_next_ticks();
std::function<void()> task = std::move(microtasks().front());
microtasks().pop_front();
task();
}
drain_next_ticks();
}
inline std::deque<std::function<void()>> &next_ticks() {
static std::deque<std::function<void()>> queue;
return queue;
}
inline void queue_next_tick(std::function<void()> callback) { next_ticks().push_back(std::move(callback)); }
inline void drain_next_ticks() {
while (!next_ticks().empty()) {
std::function<void()> task = std::move(next_ticks().front());
next_ticks().pop_front();
task();
}
}
} // namespace gea::node
namespace gea::node {
namespace {
[[noreturn]] inline void mongodb_exchange_fail(const char *operation) {
std::fprintf(stderr, "gea: MongoDB wire %s failed: %s\n", operation, std::strerror(errno));
std::abort();
}
inline int mongodb_connect_socket(const std::string &host, unsigned int port) {
const std::string service = std::to_string(port);
addrinfo query{};
query.ai_family = AF_UNSPEC;
query.ai_socktype = SOCK_STREAM;
addrinfo *resolved = nullptr;
if (::getaddrinfo(host.c_str(), service.c_str(), &query, &resolved) != 0) mongodb_exchange_fail("resolve");
int fd = -1;
for (addrinfo *candidate = resolved; candidate != nullptr; candidate = candidate->ai_next) {
fd = ::socket(candidate->ai_family, candidate->ai_socktype, candidate->ai_protocol);
if (fd < 0) continue;
int enabled = 1;
::setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &enabled, sizeof(enabled));
::setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &enabled, sizeof(enabled));
if (::connect(fd, candidate->ai_addr, candidate->ai_addrlen) == 0) break;
::close(fd);
fd = -1;
}
::freeaddrinfo(resolved);
if (fd < 0) mongodb_exchange_fail("connect");
return fd;
}
class MongoConnectionPool {
public:
MongoConnectionPool(std::string host, unsigned int port, std::size_t max_size)
: host_(std::move(host)), port_(port), max_size_(max_size) {
idle_.push_back(mongodb_connect_socket(host_, port_));
}
~MongoConnectionPool() {
for (const int fd : idle_) ::close(fd);
}
int lease() {
if (!idle_.empty()) {
const int fd = idle_.back();
idle_.pop_back();
++leased_;
return fd;
}
if (leased_ >= max_size_) {
errno = EBUSY;
mongodb_exchange_fail("pool lease");
}
++leased_;
return mongodb_connect_socket(host_, port_);
}
void release(int fd) {
if (leased_ == 0) {
errno = EINVAL;
mongodb_exchange_fail("pool release");
}
--leased_;
idle_.push_back(fd);
}
private:
std::string host_;
unsigned int port_;
std::size_t max_size_;
std::size_t leased_ = 0;
std::vector<int> idle_;
};
inline std::unordered_map<std::uint64_t, std::unique_ptr<MongoConnectionPool>> &mongodb_pools() {
static std::unordered_map<std::uint64_t, std::unique_ptr<MongoConnectionPool>> pools;
return pools;
}
inline std::uint64_t &mongodb_next_pool_id() {
static std::uint64_t id = 1;
return id;
}
inline MongoConnectionPool &mongodb_pool_for(double pool_id) {
const auto found = mongodb_pools().find(static_cast<std::uint64_t>(pool_id));
if (found == mongodb_pools().end()) {
errno = EINVAL;
mongodb_exchange_fail("pool lookup");
}
return *found->second;
}
inline void mongodb_send_all(int fd, const std::uint8_t *bytes, std::size_t length) {
std::size_t sent = 0;
while (sent < length) {
#ifdef MSG_NOSIGNAL
const ssize_t count = ::send(fd, bytes + sent, length - sent, MSG_NOSIGNAL);
#else
const ssize_t count = ::send(fd, bytes + sent, length - sent, 0);
#endif
if (count < 0 && errno == EINTR) continue;
if (count <= 0) mongodb_exchange_fail("write");
sent += static_cast<std::size_t>(count);
}
}
inline void mongodb_read_all(int fd, std::uint8_t *bytes, std::size_t length) {
std::size_t received = 0;
while (received < length) {
const ssize_t count = ::recv(fd, bytes + received, length - received, 0);
if (count < 0 && errno == EINTR) continue;
if (count <= 0) mongodb_exchange_fail("read");
received += static_cast<std::size_t>(count);
}
}
} // namespace
inline double mongodb_pool_open(std::string host, double port, double max_size) {
const std::uint64_t id = mongodb_next_pool_id()++;
const std::size_t bounded_size =
std::max<std::size_t>(1, std::min<std::size_t>(64, static_cast<std::size_t>(max_size)));
mongodb_pools().emplace(
id, std::make_unique<MongoConnectionPool>(std::move(host), static_cast<unsigned int>(port), bounded_size));
return static_cast<double>(id);
}
inline std::vector<std::uint8_t> mongodb_pool_exchange(double pool_id, const gea::TypedArray<std::uint8_t> &request) {
MongoConnectionPool &pool = mongodb_pool_for(pool_id);
const int fd = pool.lease();
mongodb_send_all(fd, request.data(), request.size());
std::uint8_t header[4]{};
mongodb_read_all(fd, header, sizeof(header));
const std::uint32_t length = static_cast<std::uint32_t>(header[0]) |
(static_cast<std::uint32_t>(header[1]) << 8) |
(static_cast<std::uint32_t>(header[2]) << 16) |
(static_cast<std::uint32_t>(header[3]) << 24);
if (length < 21 || length > 64u * 1024u * 1024u) {
std::fprintf(stderr, "gea: MongoDB returned invalid wire message length %u\n", length);
std::abort();
}
std::vector<std::uint8_t> response(length);
std::copy(std::begin(header), std::end(header), response.begin());
mongodb_read_all(fd, response.data() + sizeof(header), response.size() - sizeof(header));
pool.release(fd);
return response;
}
inline void mongodb_pool_close(double pool_id) {
mongodb_pools().erase(static_cast<std::uint64_t>(pool_id));
}
} // namespace gea::node
// ---------------------------------------------------------------------------
// Reactor-integrated timers. setTimeout/setInterval in compiled TS lower to
// the __gea_node_set_timeout/... intrinsics (plugin-mapped), which register
// here; the EventLoop polls with nextDelayMs() and fires due timers each pass.
// ---------------------------------------------------------------------------
namespace gea::node::timers {
struct Timer {
double id;
double dueMs;
double intervalMs;
bool repeats;
bool referenced;
std::function<void()> callback;
};
inline std::vector<Timer> ®istry() {
static std::vector<Timer> timers;
return timers;
}
inline double nowMs() {
using namespace std::chrono;
return duration_cast<duration<double, std::milli>>(steady_clock::now().time_since_epoch()).count();
}
inline double nextTimerId() {
static double id = 0;
return ++id;
}
inline bool hasPending() { return !registry().empty(); }
inline bool hasReferenced() {
for (const Timer &timer : registry())
if (timer.referenced) return true;
return false;
}
// Poll timeout in ms until the earliest timer is due (0 if already due,
// capped so a far-future timer cannot starve the loop of periodic passes).
inline int nextDelayMs() {
const auto &timers = registry();
if (timers.empty()) return -1;
double earliest = timers[0].dueMs;
for (const Timer &timer : timers) earliest = std::min(earliest, timer.dueMs);
const double delay = earliest - nowMs();
if (delay <= 0) return 0;
if (delay > 60000) return 60000;
return static_cast<int>(delay) + 1;
}
inline double add(std::function<void()> callback, double delayMs, bool repeats) {
const double id = nextTimerId();
if (delayMs < 0) delayMs = 0;
registry().push_back(Timer{id, nowMs() + delayMs, delayMs, repeats, true, std::move(callback)});
return id;
}
inline void remove(double id) {
auto &timers = registry();
timers.erase(std::remove_if(timers.begin(), timers.end(), [&](const Timer &timer) { return timer.id == id; }),
timers.end());
}
inline void unref(double id) {
for (Timer &timer : registry()) {
if (timer.id == id) {
timer.referenced = false;
return;
}
}
}
inline void fireDue() {
const double now = nowMs();
// Collect due timers first: callbacks may add/clear timers while running.
std::vector<Timer> due;
auto &timers = registry();
for (std::size_t i = 0; i < timers.size();) {
if (timers[i].dueMs <= now) {
due.push_back(timers[i]);
if (timers[i].repeats) {
timers[i].dueMs = now + std::max(timers[i].intervalMs, 1.0);
++i;
} else {
timers.erase(timers.begin() + static_cast<std::ptrdiff_t>(i));
}
} else {
++i;
}
}
std::sort(due.begin(), due.end(), [](const Timer &a, const Timer &b) {
return a.dueMs != b.dueMs ? a.dueMs < b.dueMs : a.id < b.id;
});
for (Timer &timer : due) {
if (timer.callback) timer.callback();
}
}
} // namespace gea::node::timers
// ---------------------------------------------------------------------------
// Size-class free-list allocator (global operator new/delete override).
//
// A server's steady-state request path allocates the same handful of block
// sizes over and over (req/res control blocks, header vectors, body/response
// strings, map entries). Routing those through the system malloc dominated
// the non-syscall profile (~650 leaf samples of malloc/free vs ~4200 syscall).
// Recycling freed blocks per size class turns each of those into a pointer
// pop/push.
//
// Safety model: pooled blocks are carved from 1 MB-aligned arena chunks whose
// bases are registered in a global table. `release` masks the pointer to its
// chunk base and looks it up — a hit recycles onto the size-class free list, a
// miss means the block came from some other allocator (malloc passthrough for
// large sizes, or a system `operator new` in a library path that did not
// resolve to this override) and is handed to `free`, which is correct for the
// malloc-backed default `operator new` on both macOS and Linux. This makes
// cross-pairing (their new → our delete) safe by construction. The reverse
// direction (our new → their delete) is prevented by exporting the override
// with default visibility so every image in the process resolves to it.
//
// Free lists are thread_local: the node runtime is a single-threaded reactor,
// and any stray secondary thread gets its own lists (a cross-thread free just
// migrates the block). The chunk table is global and append-only (chunks are
// never returned to the OS), with atomic entries so any thread can look up
// membership. Set GEA_NO_POOL_ALLOC=1 to route every allocation to malloc.
// ---------------------------------------------------------------------------
namespace gea::node::alloc {
inline constexpr std::size_t kGranule = 16; // size-class step
inline constexpr std::size_t kMaxPooled = 4096; // larger blocks pass through
inline constexpr std::size_t kClassCount = kMaxPooled / kGranule;
inline constexpr std::size_t kChunkSize = std::size_t(1) << 20; // 1 MB, alignment == size
inline constexpr std::size_t kChunkTableSize = 8192; // power of two; 8 GB of chunks
inline constexpr std::size_t kMaxProbe = 64;
// Each entry packs (chunkBase >> 20) << 12 | sizeClass. 0 = empty. Entries are
// written once and never removed, so a relaxed-read hit is always valid.
inline std::atomic<std::uint64_t> g_chunk_table[kChunkTableSize];
// POD, zero-initialized — safe to touch during static initialization.
inline thread_local void *g_free[kClassCount];
inline thread_local char *g_bump[kClassCount];
inline thread_local char *g_bump_end[kClassCount];
/**
* Per-size-class allocation census, printed at exit under `GEA_ALLOC_CENSUS=1`.
*
* The pool makes each allocation cheap -- a free-list pop is two loads and a
* store -- so when `allocate` shows up in a profile it is saying the request
* path allocates OFTEN, not slowly. A profile cannot say how many times or in
* what sizes, and that is exactly what decides whether the answer is a faster
* allocator or fewer objects. Counting is off unless asked for, and the
* counters are thread-local, so the measured path pays one predictable branch.
*/
inline void installAllocCensusExit();
inline int allocCensusLevel() {
static const int level = [] {
const char *value = std::getenv("GEA_ALLOC_CENSUS");
const int n = value == nullptr ? 0 : value[0] - '0';
if (n >= 1) installAllocCensusExit();
return n >= 1 && n <= 2 ? n : 0;
}();
return level;
}
inline bool allocCensusEnabled() { return allocCensusLevel() >= 1; }
/**
* Caller census (`GEA_ALLOC_CENSUS=2`): which call sites allocate, not just
* how big. A size histogram says "18 blocks of <=32B per request" without
* saying whether that is one std::string per header or eighteen short-lived
* runtime objects, and those two findings point at opposite fixes. Frames are
* captured with backtrace() and bucketed by the whole 4-frame prefix, so two
* paths reaching the same leaf stay distinguishable. Reported as
* binary-relative offsets, which addr2line resolves against the executable.
*/
inline constexpr std::size_t kCallerFrames = 4;
inline constexpr std::size_t kCallerSlots = 4096;
struct CallerSite {
void *frames[kCallerFrames];
std::uint64_t count;
};
inline thread_local CallerSite g_callers[kCallerSlots];
inline thread_local std::uint64_t g_callers_lost;
inline void recordCallerSite() {
void *raw[kCallerFrames + 3];
const int depth = ::backtrace(raw, static_cast<int>(kCallerFrames + 3));
// Frame 0 is backtrace itself; 1 is allocate (or the operator new it was
// inlined into). Start at 2 so the first recorded frame is request-path code.
const int first = depth > 2 ? 2 : depth;
std::uint64_t hash = 1469598103934665603ull;
void *frames[kCallerFrames] = {};
for (std::size_t i = 0; i < kCallerFrames; ++i) {
const int index = first + static_cast<int>(i);
frames[i] = index < depth ? raw[index] : nullptr;
hash = (hash ^ reinterpret_cast<std::uintptr_t>(frames[i])) * 1099511628211ull;
}
std::size_t slot = static_cast<std::size_t>(hash) & (kCallerSlots - 1);
for (std::size_t probe = 0; probe < 64; ++probe) {
CallerSite &site = g_callers[slot];
if (site.count == 0) {
for (std::size_t i = 0; i < kCallerFrames; ++i) site.frames[i] = frames[i];
site.count = 1;
return;
}
bool same = true;
for (std::size_t i = 0; i < kCallerFrames; ++i)
if (site.frames[i] != frames[i]) { same = false; break; }
if (same) { ++site.count; return; }
slot = (slot + 1) & (kCallerSlots - 1);
}
++g_callers_lost;
}
inline void reportCallerCensus() {
if (allocCensusLevel() < 2) return;
Dl_info info;
std::uintptr_t base = 0;
if (::dladdr(reinterpret_cast<void *>(&reportCallerCensus), &info) && info.dli_fbase)
base = reinterpret_cast<std::uintptr_t>(info.dli_fbase);
std::vector<const CallerSite *> sites;
for (std::size_t i = 0; i < kCallerSlots; ++i)
if (g_callers[i].count != 0) sites.push_back(&g_callers[i]);
std::sort(sites.begin(), sites.end(),
[](const CallerSite *a, const CallerSite *b) { return a->count > b->count; });
std::fprintf(stderr, "gea-alloc-callers: sites=%zu lost=%llu base=0x%llx\n", sites.size(),
static_cast<unsigned long long>(g_callers_lost),
static_cast<unsigned long long>(base));
const std::size_t shown = sites.size() < 30 ? sites.size() : 30;
for (std::size_t i = 0; i < shown; ++i) {
std::fprintf(stderr, " %8llu", static_cast<unsigned long long>(sites[i]->count));
for (std::size_t f = 0; f < kCallerFrames; ++f) {
if (sites[i]->frames[f] == nullptr) break;
std::fprintf(stderr, " %llx",
static_cast<unsigned long long>(
reinterpret_cast<std::uintptr_t>(sites[i]->frames[f]) - base));
}
std::fputc('\n', stderr);
}
}
inline thread_local std::uint64_t g_census[kClassCount + 1];
inline thread_local std::uint64_t g_census_large;
inline void reportAllocCensus();
/**
* Make the census survive how a server actually stops.
*
* A benchmark harness ends the server with SIGTERM, whose default action
* terminates the process without running `atexit`, so a report registered
* there alone would never print. Installed only when the census is enabled,
* so the ordinary signal behaviour is untouched.
*/
inline void installAllocCensusExit() {
::atexit(reportAllocCensus);
struct Handler {
static void onSignal(int) { std::exit(0); }
};
::signal(SIGTERM, &Handler::onSignal);
::signal(SIGINT, &Handler::onSignal);
}
inline void reportAllocCensus() {
if (!allocCensusEnabled()) return;
std::uint64_t total = 0;
for (std::size_t klass = 1; klass <= kClassCount; ++klass) total += g_census[klass];
total += g_census_large;
std::fprintf(stderr, "gea-alloc-census: total=%llu\n", static_cast<unsigned long long>(total));
for (std::size_t klass = 1; klass <= kClassCount; ++klass) {
if (g_census[klass] == 0) continue;
std::fprintf(stderr, " <=%zuB %llu\n", klass * kGranule,
static_cast<unsigned long long>(g_census[klass]));
}
if (g_census_large != 0)
std::fprintf(stderr, " large %llu\n", static_cast<unsigned long long>(g_census_large));
reportCallerCensus();
}
inline bool poolDisabled() {
#ifdef __APPLE__
// Apple's prebuilt libc++.dylib has INTERNALIZED free() calls (e.g. inside
// the out-of-line std::string::__grow_by_and_replace): a buffer allocated by
// this pool via an inlined operator new gets freed by the dylib's raw free()
// — "pointer being freed was not allocated", SIGABRT. No operator override
// can intercept those, so pooling is unsafe on macOS (a malloc-zone
// replacement would be the correct mechanism there). Linux interposition via
// the executable's exported operators is fully consistent — pool stays on.
static const bool disabled = [] {
const char *p = std::getenv("GEA_POOL_ALLOC"); // opt-in for experiments only
return !(p && *p == '1');
}();
return disabled;
#else
static const bool disabled = [] {
const char *p = std::getenv("GEA_NO_POOL_ALLOC");
return p && *p == '1';
}();
return disabled;
#endif
}
inline std::size_t chunkSlot(std::uintptr_t base) {
return (static_cast<std::size_t>(base >> 20) * 0x9E3779B97F4A7C15ull) & (kChunkTableSize - 1);
}
inline bool registerChunk(std::uintptr_t base, std::size_t klass) {
const std::uint64_t entry = (static_cast<std::uint64_t>(base >> 20) << 12) | klass;
std::size_t slot = chunkSlot(base);
for (std::size_t probe = 0; probe < kMaxProbe; ++probe) {
std::uint64_t expected = 0;
if (g_chunk_table[slot].compare_exchange_strong(expected, entry, std::memory_order_release, std::memory_order_relaxed))
return true;
slot = (slot + 1) & (kChunkTableSize - 1);
}
return false; // table saturated — caller falls back to malloc
}
inline std::size_t lookupChunkClass(std::uintptr_t base) {
const std::uint64_t key = static_cast<std::uint64_t>(base >> 20) << 12;
std::size_t slot = chunkSlot(base);
for (std::size_t probe = 0; probe < kMaxProbe; ++probe) {
const std::uint64_t entry = g_chunk_table[slot].load(std::memory_order_acquire);
if (entry == 0) return 0;
if ((entry & ~0xFFFull) == key) return static_cast<std::size_t>(entry & 0xFFF);
slot = (slot + 1) & (kChunkTableSize - 1);
}
return 0;
}
// Free-list links are stored in the first bytes of recycled blocks — memory
// that previously held arbitrary object types. Read/write them with memcpy
// (the blessed type-punning form): a raw `*(void **)block` violates strict
// aliasing, and clang at -O2 reorders those accesses against the surrounding
// object stores (observed as a SIGABRT on the first request).
inline void *loadFreeLink(const void *block) noexcept {
void *next;
std::memcpy(&next, block, sizeof next);
return next;
}
inline void storeFreeLink(void *block, void *next) noexcept { std::memcpy(block, &next, sizeof next); }
inline void *allocate(std::size_t size) noexcept {
const std::size_t klass = (size + kGranule - 1) / kGranule; // 1-based class index
if (allocCensusEnabled()) {
if (klass >= 1 && klass <= kClassCount) ++g_census[klass];
else ++g_census_large;
if (allocCensusLevel() >= 2) recordCallerSite();
}
if (klass >= 1 && klass <= kClassCount && !poolDisabled()) {
void *&head = g_free[klass - 1];
if (head) {
void *block = head;
head = loadFreeLink(block);
return block;
}
const std::size_t bytes = klass * kGranule;
char *&bump = g_bump[klass - 1];
char *&end = g_bump_end[klass - 1];
if (bump == nullptr || static_cast<std::size_t>(end - bump) < bytes) {
void *chunk = nullptr;
if (posix_memalign(&chunk, kChunkSize, kChunkSize) == 0 && chunk) {
if (registerChunk(reinterpret_cast<std::uintptr_t>(chunk), klass)) {
bump = static_cast<char *>(chunk);
end = bump + kChunkSize;
} else {
std::free(chunk); // table saturated — stop pooling this class
}
}
}
if (bump != nullptr && static_cast<std::size_t>(end - bump) >= bytes) {
void *block = bump;
bump += bytes;
return block;
}
}
void *block = std::malloc(size ? size : 1);
if (!block) std::abort();
return block;
}
// The steady-state request path frees from the same couple of hot chunks, so a
// one-entry cache in front of the table probe catches almost every release.
inline thread_local std::uintptr_t g_last_chunk_base;
inline thread_local std::size_t g_last_chunk_class;
inline void release(void *ptr) noexcept {
if (!ptr) return;
const std::uintptr_t base = reinterpret_cast<std::uintptr_t>(ptr) & ~(kChunkSize - 1);
std::size_t klass;
if (base == g_last_chunk_base && g_last_chunk_class != 0) {
klass = g_last_chunk_class;
} else {
klass = lookupChunkClass(base);
if (klass != 0) {
g_last_chunk_base = base;
g_last_chunk_class = klass;
}
}
if (klass != 0) {
void *&head = g_free[klass - 1];
storeFreeLink(ptr, head);
head = ptr;
return;
}
std::free(ptr);
}
} // namespace gea::node::alloc
#define GEA_ALLOC_EXPORT __attribute__((visibility("default")))
#ifdef GEA_NODE_IMPLEMENTATION
GEA_ALLOC_EXPORT void *operator new(std::size_t size) { return gea::node::alloc::allocate(size); }
GEA_ALLOC_EXPORT void *operator new(std::size_t size, const std::nothrow_t &) noexcept { return gea::node::alloc::allocate(size); }
GEA_ALLOC_EXPORT void *operator new[](std::size_t size) { return gea::node::alloc::allocate(size); }
GEA_ALLOC_EXPORT void *operator new[](std::size_t size, const std::nothrow_t &) noexcept { return gea::node::alloc::allocate(size); }
GEA_ALLOC_EXPORT void operator delete(void *ptr) noexcept { gea::node::alloc::release(ptr); }
GEA_ALLOC_EXPORT void operator delete(void *ptr, std::size_t) noexcept { gea::node::alloc::release(ptr); }
GEA_ALLOC_EXPORT void operator delete(void *ptr, const std::nothrow_t &) noexcept { gea::node::alloc::release(ptr); }
GEA_ALLOC_EXPORT void operator delete[](void *ptr) noexcept { gea::node::alloc::release(ptr); }
GEA_ALLOC_EXPORT void operator delete[](void *ptr, std::size_t) noexcept { gea::node::alloc::release(ptr); }
GEA_ALLOC_EXPORT void operator delete[](void *ptr, const std::nothrow_t &) noexcept { gea::node::alloc::release(ptr); }
#endif
namespace gea::node {
// ---------------------------------------------------------------------------
// A file descriptor the event loop watches. Concrete watchers (listener,
// connection) implement the readiness callback.
// ---------------------------------------------------------------------------
class IoWatcher {
public:
virtual ~IoWatcher() = default;
virtual int fd() const noexcept = 0;
virtual short interestedEvents() const noexcept = 0; // POLLIN | POLLOUT
virtual void onReady(short revents) = 0;
virtual bool isReferenced() const noexcept { return true; }
};
// ---------------------------------------------------------------------------
// A minimal single-threaded poll() reactor. Borrowed watchers outlive the loop
// (e.g. a listener owned by its server); adopted watchers are owned by the loop
// (e.g. accepted connections) and destroyed when closed.
// ---------------------------------------------------------------------------
class EventLoop {
public:
#ifdef __linux__
EventLoop() : epollFd_(::epoll_create1(EPOLL_CLOEXEC)) {}
~EventLoop() {
if (epollFd_ >= 0) ::close(epollFd_);
}
#endif
void addBorrowed(IoWatcher *watcher) {
borrowed_.push_back(watcher);
watcherAdded(watcher);
}
void adopt(std::unique_ptr<IoWatcher> watcher) {
watcherAdded(watcher.get());
owned_.push_back(std::move(watcher));
}
// Defer removal until the current dispatch pass completes, so a watcher can
// close itself from inside its own onReady().
void close(IoWatcher *watcher) {
if (std::find(closing_.begin(), closing_.end(), watcher) != closing_.end()) return;
closing_.push_back(watcher);
#ifdef __linux__
// Stop readiness delivery immediately but retain the C++ object until no
// outer or nested dispatch snapshot can still contain its pointer.
if (epollFd_ >= 0) {
::epoll_ctl(epollFd_, EPOLL_CTL_DEL, watcher->fd(), nullptr);
epollInterest_.erase(watcher);
}
#endif
}
void run() {
#ifdef __linux__
if (epollFd_ >= 0) {
(void)runEpoll(nullptr);
return;
}
#endif
(void)runPoll(nullptr);
}
// Drive the same reactor used by the normal Node run loop until an awaited
// host operation settles. This deliberately does not wait for the reactor to
// become empty: a connected client socket remains watched for future reads,
// so "run everything" would never return from an individual operation.
//
// Returns false only when no referenced timer or live watcher can make
// progress (or the platform wait fails) while the predicate is still false.
bool runUntil(const std::function<bool()> &done) {
if (!done || done()) return true;
#ifdef __linux__
if (epollFd_ >= 0) return runEpoll(&done);
#endif
return runPoll(&done);
}
private:
using StopPredicate = const std::function<bool()> *;
static bool stopRequested(StopPredicate done) {
return done != nullptr && static_cast<bool>(*done) && (*done)();
}
// An await may pump the reactor from inside an existing watcher callback
// (for example, outbound I/O issued by an HTTP handler). Watchers closed
// by that nested pass must remain alive until the outer callback and its
// ready-watcher snapshot have both finished. The closing_ membership check
// prevents any such watcher from being dispatched again in the meantime.
void dispatchWatcher(IoWatcher *watcher, short revents) {
++dispatchDepth_;
watcher->onReady(revents);
--dispatchDepth_;
}
void purgeClosedIfSafe() {
if (dispatchDepth_ == 0) purgeClosed();
}
// poll() backend — the portable fallback (macOS, or epoll_create failure).
bool runPoll(StopPredicate done) {
std::vector<pollfd> pfds;
std::vector<IoWatcher *> polledWatchers;
std::vector<std::pair<IoWatcher *, short>> ready;
for (;;) {
gea::node::drain_microtasks();
if (stopRequested(done)) {
purgeClosedIfSafe();
return true;
}
pfds.clear();
polledWatchers.clear();
bool haveReferencedWatcher = false;
forEachWatcher([&](IoWatcher *w) {
if (isClosing(w)) return;
pfds.push_back(pollfd{w->fd(), w->interestedEvents(), 0});
polledWatchers.push_back(w);
if (w->isReferenced()) haveReferencedWatcher = true;
});
const bool timersPending = gea::node::timers::hasPending();
if ((pfds.empty() || (done == nullptr && !haveReferencedWatcher)) &&
!gea::node::timers::hasReferenced()) {
purgeClosedIfSafe();
return stopRequested(done); // only unref work remains
}
const int timeout = timersPending ? gea::node::timers::nextDelayMs() : -1;
const int events = ::poll(pfds.data(), static_cast<nfds_t>(pfds.size()), timeout);
if (events < 0) {
if (errno == EINTR) continue;
purgeClosedIfSafe();
return stopRequested(done);
}
// Keep the watcher set alive for the whole post-poll pass. Timer and
// microtask callbacks may themselves await host work and recursively
// pump this loop; any watcher they close must remain valid until the
// pollfd snapshot below is no longer in use.
++dispatchDepth_;
gea::node::timers::fireDue();
gea::node::drain_microtasks();
if (stopRequested(done)) {
--dispatchDepth_;
purgeClosedIfSafe();
return true;
}
// Snapshot ready watchers before dispatching (a handler may add/close).
ready.clear();
for (std::size_t i = 0; i < pfds.size(); ++i) {
IoWatcher *watcher = polledWatchers[i];
if (!isClosing(watcher) && pfds[i].revents != 0) ready.emplace_back(watcher, pfds[i].revents);
}
for (const auto &[watcher, revents] : ready) {
if (isClosing(watcher)) continue;
if (revents != 0) dispatchWatcher(watcher, revents);
if (stopRequested(done)) break;
}
// Handler promises progress here: continuations queued during dispatch
// (async handlers, body-delivery microtasks) run before the next poll.
gea::node::drain_microtasks();
const bool stopped = stopRequested(done);
--dispatchDepth_;
purgeClosedIfSafe();
if (stopped) return true;
}
}
#ifdef __linux__
// epoll backend: the kernel wait is O(ready) instead of poll()'s O(watchers)
// array copy + scan per wakeup. Watchers register on add; interest changes
// (POLLOUT wanted only while a response is buffered) are synced with
// EPOLL_CTL_MOD each pass — a cheap userland compare, a syscall only when
// the interest actually changed.
bool runEpoll(StopPredicate done) {
epoll_event events[128];
for (;;) {
gea::node::drain_microtasks();
if (stopRequested(done)) {
purgeClosedIfSafe();
return true;
}
bool haveWatchers = false;
bool haveReferencedWatcher = false;
forEachWatcher([&](IoWatcher *w) {
if (isClosing(w)) return;
haveWatchers = true;
if (w->isReferenced()) haveReferencedWatcher = true;
const short want = w->interestedEvents();
auto found = epollInterest_.find(w);
if (found != epollInterest_.end() && found->second != want) {
epoll_event ev{};
ev.events = static_cast<uint32_t>(want);
ev.data.ptr = w;
::epoll_ctl(epollFd_, EPOLL_CTL_MOD, w->fd(), &ev);
found->second = want;
}
});
const bool timersPending = gea::node::timers::hasPending();
if ((!haveWatchers || (done == nullptr && !haveReferencedWatcher)) &&
!gea::node::timers::hasReferenced()) {
purgeClosedIfSafe();
return stopRequested(done);
}
const int timeout = timersPending ? gea::node::timers::nextDelayMs() : -1;
const int count = ::epoll_wait(epollFd_, events, 128, timeout);
if (count < 0) {
if (errno == EINTR) continue;
purgeClosedIfSafe();
return stopRequested(done);
}
// epoll stores raw watcher pointers in its event snapshot. Preserve
// those objects across timer/microtask callbacks and nested pumps until
// this entire batch has been consumed.
++dispatchDepth_;
gea::node::timers::fireDue();
gea::node::drain_microtasks();
if (stopRequested(done)) {
--dispatchDepth_;
purgeClosedIfSafe();
return true;
}
for (int i = 0; i < count; ++i) {
auto *watcher = static_cast<IoWatcher *>(events[i].data.ptr);
if (isClosing(watcher)) continue;
// Linux defines the EPOLL* event bits to coincide with the POLL* bits.
dispatchWatcher(
watcher,
static_cast<short>(events[i].events & (POLLIN | POLLOUT | POLLERR | POLLHUP | POLLNVAL)));
if (stopRequested(done)) break;
}
gea::node::drain_microtasks();
const bool stopped = stopRequested(done);
--dispatchDepth_;
purgeClosedIfSafe();
if (stopped) return true;
}
}
#endif
void watcherAdded(IoWatcher *watcher) {
#ifdef __linux__
if (epollFd_ >= 0) {
const short want = watcher->interestedEvents();
epoll_event ev{};
ev.events = static_cast<uint32_t>(want);
ev.data.ptr = watcher;
::epoll_ctl(epollFd_, EPOLL_CTL_ADD, watcher->fd(), &ev);
epollInterest_[watcher] = want;
}
#else
(void)watcher;
#endif
}
public:
private:
template <typename Fn>
void forEachWatcher(Fn &&fn) {
for (IoWatcher *w : borrowed_) fn(w);
for (const std::unique_ptr<IoWatcher> &w : owned_) fn(w.get());
}
bool isClosing(IoWatcher *watcher) const {
return std::find(closing_.begin(), closing_.end(), watcher) != closing_.end();
}
void purgeClosed() {
for (IoWatcher *watcher : closing_) {
borrowed_.erase(std::remove(borrowed_.begin(), borrowed_.end(), watcher), borrowed_.end());
owned_.erase(std::remove_if(owned_.begin(), owned_.end(),
[&](const std::unique_ptr<IoWatcher> &owned) { return owned.get() == watcher; }),
owned_.end());
}
closing_.clear();
}
std::vector<IoWatcher *> borrowed_;
std::vector<std::unique_ptr<IoWatcher>> owned_;
std::vector<IoWatcher *> closing_;
std::size_t dispatchDepth_ = 0;
#ifdef __linux__
int epollFd_ = -1;
std::unordered_map<IoWatcher *, short> epollInterest_;
#endif
};
// Every Node client and HTTP server in a process shares one reactor. This is
// essential for lazy clients created inside an HTTP handler: the server's run
// loop must also drive the newly-created outbound socket.
inline EventLoop &clientEventLoop() {
static EventLoop loop;
return loop;
}
// ---------------------------------------------------------------------------
// A non-blocking TCP socket wrapper (RAII: closes its fd on destruction).
// ---------------------------------------------------------------------------
class Socket {
public: