Fix the sanitizer lanes on the 0.5.0 release commit (#4790)

* Fix the sanitizer lanes on the 0.5.0 release commit

* Materialize @types/node's entry declaration before a tsc-ts build

* Accept the Node types materializer before tsc-ts in the TypeScript 7 build check

* Skip ICU-only corpus programs on packs without Intl

* Honor a reason after a corpus program's darwin skip marker

* Give the loopback WebSocket corpus programs room on slow hosts

* Let reuseAddr share a datagram port on the BSDs

* Keep the unread-response probes inside the macOS port range

* Make the loopback load-race corpus programs deterministic

* Copy pnpm's store files on Windows before the compiler build

* Run the island exit cleanups after Node's shutdown work

* Run the island-origin self-hosting test in its own sanitized job

* Add HTTP/2 abrupt peer FIN without GOAWAY corpus test

* Refresh HTTP/2 idle timeouts on writes and keep an upgraded WebSocket alive
This commit is contained in:
Chris Tate
2026-12-03 04:51:10 -06:00
committed by GitHub
parent 4119844d1e
commit 1be922ae8e
54 changed files with 1320 additions and 372 deletions
+24 -14
View File
@@ -1046,18 +1046,21 @@ jobs:
with:
name: failure-report-three-san
# The sanitized self-hosting native-frontend builds alone. Each of these
# three files compiles the whole frontend under ASan in beforeAll: the
# compile in Node holds 6.5 to 7.4 GB while clang builds the executable,
# one clang per core at a time, the largest of them 5.1 GB. Beside a
# shard's corpus workers the kernel killed it intermittently at 670-740 s
# (SIGKILL, empty stderr, every test skipped), so: one file per job, one
# worker, no corpus. On the runner's four cores the build alone has since
# outgrown its 16 GB (the kernel kills the compile at 560 s; a hosted runner
# goes down itself first, and the step ends cancelled about ten minutes in,
# with no test output), so the step runs on two cores: two clangs at a
# time, 14.5 GB at the peak. The plain suite and the macOS shards keep these
# files in the shard side queue (scripts/ci-test-plan.mjs).
# The sanitized self-hosting builds alone. These files compile the whole
# frontend under ASan: the compile in Node holds 6.5 to 7.4 GB while clang
# builds the executable, one clang per core at a time, the largest of them
# 5.1 GB. Beside a shard's corpus workers the kernel killed them
# intermittently at 670-740 s (SIGKILL, empty stderr, every test skipped),
# so: one file per job, one worker, no corpus.
# self-hosting-island-origin.test.ts compiles the same frontend in its own
# child process and was killed the same way after 21 minutes beside a
# shard's corpus workers. On the runner's four cores the build alone has
# since outgrown its 16 GB (the kernel kills the compile at 560 s; a hosted
# runner goes down itself first, and the step ends cancelled about ten
# minutes in, with no test output), so the step runs on two cores: two
# clangs at a time, 14.5 GB at the peak. The plain suite and the macOS
# shards keep these files in the shard side queue
# (scripts/ci-test-plan.mjs).
native_frontend_san:
needs: [validation_scope, lanes, native_linux]
if: ${{ needs.validation_scope.outputs.full == 'true' && needs.lanes.outputs.linux == 'true' && needs.lanes.outputs.queue != 'true' }}
@@ -1074,6 +1077,8 @@ jobs:
file: tests/harness/self-hosting-native-frontend-checks.test.ts
- suite: frontend
file: tests/harness/self-hosting-native-frontend.test.ts
- suite: island-origin
file: tests/harness/self-hosting-island-origin.test.ts
env:
SCRIPTC_SAN: "1"
SCRIPTC_TEST_WORKERS: "1"
@@ -1437,7 +1442,7 @@ jobs:
if: ${{ needs.validation_scope.outputs.full == 'true' && needs.lanes.outputs.linux == 'true' && needs.lanes.outputs.queue != 'true' }}
name: test (TypeScript 7 parity)
runs-on: ubuntu-24.04
timeout-minutes: 10
timeout-minutes: 20
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
@@ -2016,7 +2021,12 @@ jobs:
Move-Item "$expanded\clang+llvm-22.1.8-x86_64-pc-windows-msvc" $llvm
echo "LLVM_DIR=$llvm\lib\cmake\llvm" >> $env:GITHUB_ENV
echo "$llvm\bin" >> $env:GITHUB_PATH
- run: pnpm install --frozen-lockfile
# A Windows runner can report a package file's real path inside pnpm's
# store, where the package's sibling files are absent; tsc-ts resolves
# files through their real path, so the compiler build then fails to
# resolve the packages it imports. Copying the store's files into
# node_modules keeps every real path inside the checkout.
- run: pnpm install --frozen-lockfile --package-import-method=copy
# Zig builds the helper package's comptime evaluator and the runtime pack.
- uses: ./.github/actions/zig
- name: Build Windows helper
+7 -1
View File
@@ -308,7 +308,13 @@ jobs:
if: endsWith(matrix.cli_target, '-musl')
run: |
printf 'supportedArchitectures:\n libc: [current, musl]\n' >> pnpm-workspace.yaml
- run: pnpm install --frozen-lockfile
# tsc-ts resolves each file it loads through its real path. A Windows
# runner can report a package file's real path inside pnpm's store (the
# failing build loaded files from .pnpm-store/v11/files), where the
# package's sibling files are absent, and the compiler build then cannot
# resolve the packages it imports. Copying the store's files into
# node_modules keeps every real path inside the checkout.
- run: pnpm install --frozen-lockfile ${{ matrix.platform == 'windows-x64' && '--package-import-method=copy' || '' }}
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: packs-${{ matrix.platform }}
+1 -1
View File
@@ -21,7 +21,7 @@
"node": ">=24"
},
"scripts": {
"build": "node node_modules/tsc-ts/bin/tsc-ts.js -p tsconfig.json",
"build": "node ../../scripts/materialize-node-types.mjs && node node_modules/tsc-ts/bin/tsc-ts.js -p tsconfig.json",
"prepack": "node scripts/prepare-native.mjs",
"postinstall": "node scripts/install-native.mjs"
},
+1 -1
View File
@@ -36,7 +36,7 @@
"access": "public"
},
"scripts": {
"build": "node node_modules/tsc-ts/bin/tsc-ts.js -p tsconfig.json"
"build": "node ../../scripts/materialize-node-types.mjs && node node_modules/tsc-ts/bin/tsc-ts.js -p tsconfig.json"
},
"dependencies": {
"@scriptc/runtime": "workspace:*",
@@ -981,15 +981,22 @@ export function emitModuleParts(emitter: LlEmitter): TextPart[] {
emitter.declare(`declare void @scr_tls_ca_install()`);
}
// Inline exit listeners run when something they must beat exists:
// the refcounted-global releases, or the retained-FFI atexit ledger
// the refcounted-global releases, the retained-FFI atexit ledger
// sweep (a listener may legitimately release or pump a registration,
// and only the inline call orders ahead of every atexit handler —
// the runtime ABI’s runExitListeners stance). Plain event programs
// with neither keep the atexit path, so their listener timing is
// unchanged.
// the runtime ABI’s runExitListeners stance), or fs.Utf8Stream, whose
// unit registers its listener-edge teardown when the first stream is
// created — later than scr_events_install, so that atexit runs before
// the exit listeners and takes the listeners a synchronous write from
// one of them still needs. Plain event programs with none keep the
// atexit path, so their listener timing is unchanged.
const hasRefGlobals = globals.some((g) => isRefCounted(g.type)) || fnValueProps.length > 0;
const inlineExitListeners =
usesEvents && (emitter.mod.workers || hasRefGlobals || emitter.ffiHasRetainedCallback);
usesEvents &&
(emitter.mod.workers ||
hasRefGlobals ||
emitter.ffiHasRetainedCallback ||
runtimeFeatures.fsUtf8Stream);
emitter.declare(`declare i32 @scr_exit_code_hint_get()`);
if (inlineExitListeners) {
emitter.declare(`declare void @scr_run_exit_listeners(double)`);
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/http2-outbound-write-timeout.ts"
],
"diags": []
}
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/http2-peer-fin-without-goaway.ts"
],
"diags": []
}
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/node-island-lazy-class-exit/main.ts"
],
"diags": []
}
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/corpus/websocket-uncaptured-delayed-frame.ts"
],
"diags": []
}
+9
View File
@@ -718,7 +718,16 @@ static void scr_dgram_ensure_fd(ScrDgramSocket *s) {
scr_dgram_nonblock(fd);
if (s->reuse_addr) {
int one = 1;
/* libuv's uv__sock_reuseaddr: on the BSDs (macOS included) SO_REUSEPORT
* implies SO_REUSEADDR and is what lets a second datagram socket share
* the port; on Linux and the platforms whose SO_REUSEPORT load-balances,
* SO_REUSEADDR is the Node answer. */
#if defined(SO_REUSEPORT) && !defined(__linux__) && !defined(__GNU__) && \
!defined(__illumos__) && !defined(__DragonFly__) && !defined(_AIX73)
setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (const void *)&one, sizeof one);
#else
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&one, sizeof one);
#endif
}
#ifdef SO_REUSEPORT
if (s->reuse_port) {
+7 -4
View File
@@ -1122,12 +1122,15 @@ static void scr_ee_dyn_fire(ScrClosure *self, ScrDyn *arg /*moves*/) {
scr_dyn_release(fn);
}
static void scr_ee_dyn_error_fire(ScrClosure *self, ScrError *err) {
scr_ee_dyn_fire(self, scr_dyn_from_error(err));
/* The fixed-arity shims call a stored listener through its own function
* type (void (*)(ScrClosure *, void *)), so these adapters take the one
* argument as a void pointer and recover its type here. */
static void scr_ee_dyn_error_fire(ScrClosure *self, void *arg) {
scr_ee_dyn_fire(self, scr_dyn_from_error((ScrError *)arg));
}
static void scr_ee_dyn_name_fire(ScrClosure *self, ScrStr *name) {
scr_ee_dyn_fire(self, scr_dyn_new_str(name));
static void scr_ee_dyn_name_fire(ScrClosure *self, void *arg) {
scr_ee_dyn_fire(self, scr_dyn_new_str((ScrStr *)arg));
}
static ScrClosure *scr_ee_dyn_adapter(const ScrDyn *cb, void *fire) {
+64 -1
View File
@@ -111,6 +111,7 @@ typedef struct ScrUtf8Stream {
size_t release_units; /* the accounting units that flush carried */
ScrU8FlushCb *flush_cbs;
ScrU8Listener *listeners;
struct ScrUtf8Stream *next_live; /* the exit hook's live-stream list */
} ScrUtf8Stream;
static void scr_u8_oom(void) { scr_trap("scriptc: out of memory\n"); }
@@ -124,6 +125,61 @@ static void scr_u8_listener_drop(ScrU8Listener *l) {
}
}
static ScrUtf8Stream *scr_u8_retain(ScrUtf8Stream *s);
static void scr_u8_release(ScrUtf8Stream *s);
/* ── live-stream teardown at exit ─────────────────────────────────────
* A listener often closes over the stream itself (stream -> listener
* closure -> checked-dynamic handle -> stream). The cycle collector does
* not follow a handle into its native object, so a stream that never
* reaches its close completion (an open failure the program leaves
* unhandled, a destroy queued as the process ends) would keep its
* listeners — and through them itself — alive to the exit audit. Node
* relies on its GC here. Breaking the listener edges at exit is
* observationally free: no JavaScript runs after the exit hooks. */
static SCR_TL ScrUtf8Stream *scr_u8_live_head = NULL;
static SCR_TL bool scr_u8_live_cleanup = false;
static void scr_u8_live_shutdown(void) {
/* A listener's release can drop another live stream's last reference (one
* stream's listener closing over another), so every entry is held for the
* whole walk. */
for (ScrUtf8Stream *s = scr_u8_live_head; s != NULL; s = s->next_live)
scr_u8_retain(s);
ScrUtf8Stream *s = scr_u8_live_head;
while (s != NULL) {
ScrUtf8Stream *next = s->next_live;
scr_u8_listener_drop(s->listeners);
s->listeners = NULL;
while (s->flush_cbs != NULL) {
ScrU8FlushCb *cb = s->flush_cbs;
s->flush_cbs = cb->next;
scr_dyn_release(cb->cb);
free(cb);
}
scr_dyn_release(s->open_error);
s->open_error = NULL;
scr_u8_release(s);
s = next;
}
}
static void scr_u8_live_add(ScrUtf8Stream *s) {
if (!scr_u8_live_cleanup) {
scr_atexit(scr_u8_live_shutdown);
scr_u8_live_cleanup = true;
}
s->next_live = scr_u8_live_head;
scr_u8_live_head = s;
}
static void scr_u8_live_remove(ScrUtf8Stream *s) {
ScrUtf8Stream **link = &scr_u8_live_head;
while (*link != NULL && *link != s) link = &(*link)->next_live;
if (*link == s) *link = s->next_live;
s->next_live = NULL;
}
static ScrUtf8Stream *scr_u8_retain(ScrUtf8Stream *s) {
if (s->rc != SIZE_MAX) s->rc++;
return s;
@@ -151,6 +207,7 @@ static void scr_u8_release(ScrUtf8Stream *s) {
s->flush_cbs = next;
}
free(s->buf);
scr_u8_live_remove(s);
free(s);
}
@@ -302,7 +359,12 @@ static void scr_u8_tick(ScrUtf8Stream *s, int event) {
* attached. An 'error' nobody listens for then throws, as Node's EventEmitter
* does. */
static ScrDyn *scr_u8_defer_open_error(ScrUtf8Stream *s) {
s->open_error = scr_caught_to_dyn(scr_exc_take());
/* scr_caught_to_dyn borrows the caught value: the pending exception's
* wrapper has to go, or every failed open leaks its error (the caught
* record plus the strings it holds). */
ScrCaught *caught = scr_exc_take();
s->open_error = scr_caught_to_dyn(caught);
scr_caught_release(caught);
s->fd = -1;
ScrDyn *box = scr_dyn_new_handle(s, SCR_DYNH_UTF8_STREAM);
scr_u8_defer(s, scr_u8_step_open_error);
@@ -970,6 +1032,7 @@ ScrDyn *scr_fs_utf8_stream_new(ScrDyn *options) {
ScrUtf8Stream *s = calloc(1, sizeof *s);
if (s == NULL) scr_u8_oom();
s->rc = 1;
scr_u8_live_add(s);
s->fd = -1;
s->retired_fd = -1;
s->worker_fd = -1;
+47 -32
View File
@@ -7980,41 +7980,56 @@ static void scr_http_client_settle(struct ScrHttpClientReq *c) {
* their callbacks now with ERR_STREAM_DESTROYED, after 'close' (Node's
* afterWrite on a destroyed stream). Callbacks still waiting in the
* message's own buffer are dropped silently, as Node drops a write that
* never left the message. */
* never left the message.
*
* A response that completed while its request's bytes were still in a
* live socket is not a destroyed stream: Node's afterWrite completes those
* write callbacks without an error once the socket drains them (the socket
* may be pooled and keep sending them to the server that still reads). */
const bool write_drains =
c->response_done && !c->had_error && !c->aborted && c->sock != NULL &&
!scr_net_sock_destroyed(c->sock);
if ((c->socket_emitted && scr_net_ls_has_live(&c->wcb_ls)) ||
scr_net_ls_has_live(&c->destroy_cb_ls)) {
static const char destroyed_text[] = "Cannot call write after a stream was destroyed";
ScrStr *text = scr_str_new(destroyed_text, sizeof destroyed_text - 1);
ScrError *err = scr_error_new(SCR_ERR_ERROR, text);
scr_error_set_code(err, "ERR_STREAM_DESTROYED");
ScrError *saved = scr_event_error_payload;
scr_event_error_payload = err;
ScrNetLs due = c->wcb_ls;
ScrNetLs posted = c->destroy_cb_ls;
c->wcb_ls = (ScrNetLs){0};
c->destroy_cb_ls = (ScrNetLs){0};
ScrNetL *snap;
size_t due_n = scr_net_ls_snapshot(&due, &snap);
scr_dyn_this_push(c, SCR_DYNH_HTTP_CLIENT);
for (size_t i = 0; i < due_n; i++) {
if (!scr_exc_pending()) scr_dyn_listener_fire_err(snap[i].cb, text);
scr_closure_release(snap[i].cb);
if (write_drains && !scr_net_ls_has_live(&c->destroy_cb_ls)) {
ScrNetLs due = c->wcb_ls;
c->wcb_ls = (ScrNetLs){0};
scr_net_fire0_this(&due, c, SCR_DYNH_HTTP_CLIENT);
scr_net_ls_drop(&due);
} else {
static const char destroyed_text[] = "Cannot call write after a stream was destroyed";
ScrStr *text = scr_str_new(destroyed_text, sizeof destroyed_text - 1);
ScrError *err = scr_error_new(SCR_ERR_ERROR, text);
scr_error_set_code(err, "ERR_STREAM_DESTROYED");
ScrError *saved = scr_event_error_payload;
scr_event_error_payload = err;
ScrNetLs due = c->wcb_ls;
ScrNetLs posted = c->destroy_cb_ls;
c->wcb_ls = (ScrNetLs){0};
c->destroy_cb_ls = (ScrNetLs){0};
ScrNetL *snap;
size_t due_n = scr_net_ls_snapshot(&due, &snap);
scr_dyn_this_push(c, SCR_DYNH_HTTP_CLIENT);
for (size_t i = 0; i < due_n; i++) {
if (!scr_exc_pending()) scr_dyn_listener_fire_err(snap[i].cb, text);
scr_closure_release(snap[i].cb);
}
scr_dyn_this_pop();
free(snap);
free(due.ls);
scr_dyn_this_push(c, SCR_DYNH_HTTP_CLIENT);
size_t post_n = scr_net_ls_snapshot(&posted, &snap);
for (size_t i = 0; i < post_n; i++) {
if (!scr_exc_pending()) scr_dyn_listener_fire_err(snap[i].cb, text);
scr_closure_release(snap[i].cb);
}
scr_dyn_this_pop();
free(snap);
free(posted.ls);
scr_event_error_payload = saved;
scr_error_release(err);
scr_str_release(text);
}
scr_dyn_this_pop();
free(snap);
free(due.ls);
scr_dyn_this_push(c, SCR_DYNH_HTTP_CLIENT);
size_t post_n = scr_net_ls_snapshot(&posted, &snap);
for (size_t i = 0; i < post_n; i++) {
if (!scr_exc_pending()) scr_dyn_listener_fire_err(snap[i].cb, text);
scr_closure_release(snap[i].cb);
}
scr_dyn_this_pop();
free(snap);
free(posted.ls);
scr_event_error_payload = saved;
scr_error_release(err);
scr_str_release(text);
}
scr_net_ls_drop(&c->wcb_ls);
scr_net_ls_drop(&c->wcb_pre_ls);
+301 -19
View File
@@ -864,6 +864,9 @@ struct ScrH2Session {
bool preface_done; /* server: magic received; client: always true */
bool goaway_sent, goaway_recv;
bool goaway_final_sent; /* the graceful close's second GOAWAY went out */
/* server.close() closed this session: its 'close' is deferred one turn so
* the server's own 'close' callback runs first, as Node orders them. */
bool srv_closing, srv_close_deferred;
/* Node's maxSessionMemory (MB, 10 by default): what the streams this
* session carries hold, refused once the limit is passed. */
size_t mem_used;
@@ -878,6 +881,14 @@ struct ScrH2Session {
* whether the server-level timeout forwards to its listeners is fixed for
* this session, whatever server.timeout becomes later. */
bool srv_timeout_forward; /* +1; NULL on client sessions */
/* Darwin: the session socket's setTimeout and the server idle timeout run
* on the runtime's timer loop; the kqueue idle timer does not wake the
* loop on this platform. */
double srv_timeout_handle;
double srv_timeout_ms;
double sock_timeout_handle;
double sock_timeout_ms;
double destroy_timer_handle;
/* frame reassembly */
char *rbuf;
size_t rlen, rcap;
@@ -1027,6 +1038,7 @@ static void scr_h2_srv_close_sessions(void *ctx) {
if (!snap) scr_h2_oom();
for (size_t i = 0; i < n; i++) snap[i] = scr_http2_session_retain(srv->sessions[i]);
for (size_t i = 0; i < n; i++) {
snap[i]->srv_closing = true;
scr_http2_session_close(snap[i], NULL);
scr_http2_session_release(snap[i]);
}
@@ -1096,6 +1108,18 @@ static void scr_h2_session_drop_lists(ScrH2Session *s) {
}
static void scr_h2_session_free(ScrH2Session *s) {
if (s->srv_timeout_handle > 0) {
scr_clear_interval(s->srv_timeout_handle);
s->srv_timeout_handle = 0;
}
if (s->sock_timeout_handle > 0) {
scr_clear_interval(s->sock_timeout_handle);
s->sock_timeout_handle = 0;
}
if (s->destroy_timer_handle > 0) {
scr_clear_interval(s->destroy_timer_handle);
s->destroy_timer_handle = 0;
}
scr_h2_session_drop_lists(s);
for (size_t i = 0; i < s->nstreams; i++) scr_http2_stream_release(s->streams[i]);
free(s->streams);
@@ -1123,6 +1147,7 @@ static void scr_h2_session_free(ScrH2Session *s) {
enum {
SCR_H2_EMIT_STREAM_CLOSE, /* the compat pair's close, then the stream's */
SCR_H2_EMIT_STREAM_CLOSED, /* 'error' (nonzero code) then 'close' */
SCR_H2_EMIT_STREAM_RST, /* deferred RST_STREAM (superseded by session GOAWAY) */
SCR_H2_EMIT_SESSION_CLOSE, /* session 'close' */
SCR_H2_EMIT_SESSION_CONNECT, /* client 'connect' */
SCR_H2_EMIT_SESSION_PINGS, /* cancelled ping() callbacks */
@@ -1151,6 +1176,7 @@ static void scr_h2_emit_release(ScrH2Emit *e) {
scr_http2_stream_release((ScrH2Stream *)e->h);
break;
case SCR_H2_EMIT_STREAM_CLOSED:
case SCR_H2_EMIT_STREAM_RST:
case SCR_H2_EMIT_STREAM_DRAIN:
case SCR_H2_EMIT_STREAM_WANT_TRAILERS:
case SCR_H2_EMIT_STREAM_READY:
@@ -1192,6 +1218,8 @@ static bool scr_h2_sock_alive(ScrH2Session *s) {
return s->sock != NULL && !scr_net_sock_destroyed(s->sock);
}
static void scr_h2_session_touch_timeout(ScrH2Session *s);
static void scr_h2_send_frame(ScrH2Session *s, uint8_t type, uint8_t flags,
int32_t stream_id, const void *payload, size_t n) {
if (!scr_h2_sock_alive(s)) return;
@@ -1207,6 +1235,7 @@ static void scr_h2_send_frame(ScrH2Session *s, uint8_t type, uint8_t flags,
head[8] = (uint8_t)stream_id;
scr_net_sock_write_native(s->sock, (const char *)head, 9);
if (n > 0) scr_net_sock_write_native(s->sock, payload, n);
scr_h2_session_touch_timeout(s);
}
/* Record a SETTINGS frame about to go out; `after` is the local record its
@@ -1894,9 +1923,27 @@ static ScrDyn *scr_h2_iter_next(ScrClosure *clo, ScrDyn *const *args, size_t arg
return out;
}
/* return(): the loop left early. Node's destroyOnReturn destroys the
* stream, and its destroyAbort sends RST_STREAM(CANCEL, 8) — the code the
* peer sees and the close reports. */
/* return(): the loop left early. Node's destroyOnReturn destroys the stream
* with NGHTTP2_CANCEL (8) and queues RST_STREAM(8) in nghttp2's outbound queue;
* if the stream's 'close' listener destroys the session before that flush,
* nghttp2 drops the queued RST_STREAM in favor of the session's GOAWAY
* (NGHTTP2_ERR_SESSION_CLOSING). */
static void scr_h2_stream_begin_close(ScrH2Stream *st);
static void scr_h2_stream_close_deferred_rst(ScrH2Stream *st, uint32_t code) {
if (st->destroyed || st->close_queued || st->close_emitted) return;
st->api_destroyed = true;
st->rst_code = code;
bool send_rst = st->state != SCR_H2_S_CLOSED && scr_h2_sock_alive(st->sess);
st->rst_sent = true;
st->destroyed = true;
scr_h2_stream_begin_close(st);
scr_h2_stream_settle(st);
if (send_rst) {
scr_h2_emit_push(SCR_H2_EMIT_STREAM_RST, scr_http2_stream_retain(st));
}
}
static ScrDyn *scr_h2_iter_return(ScrClosure *clo, ScrDyn *const *args, size_t argc) {
(void)args;
(void)argc;
@@ -1912,8 +1959,7 @@ static ScrDyn *scr_h2_iter_return(ScrClosure *clo, ScrDyn *const *args, size_t a
if (it->error == NULL) it->error = scr_error_retain(abort);
scr_error_release(abort);
if (!st->destroyed && !st->close_queued && !st->close_emitted) {
st->api_destroyed = true;
scr_http2_stream_close(st, 8.0 /* NGHTTP2_CANCEL */, NULL);
scr_h2_stream_close_deferred_rst(st, 8 /* NGHTTP2_CANCEL */);
}
scr_h2_iter_obj_release_v(obj);
ScrPromise *p = scr_promise_new();
@@ -2088,6 +2134,19 @@ static void scr_h2_file_schedule_retry(ScrH2Stream *st) {
}
}
/* Re-queue a server-close-induced session 'close' after the turn in which
* the server's own close callback runs. */
static void scr_h2_session_queue_close(ScrH2Session *s);
static void scr_h2_session_close_tick(ScrClosure *cb) {
ScrH2Session *s = (ScrH2Session *)scr_box_get_ref(cb->caps[0]); /* +1 */
if (s != NULL && !s->close_emitted) {
s->close_queued = false;
scr_h2_session_queue_close(s);
}
scr_http2_session_release(s);
}
static bool scr_h2_proto_pending(void) { return scr_h2_emits_head < scr_h2_emits_len; }
static void scr_h2_proto_sweep(void) {
@@ -2095,6 +2154,7 @@ static void scr_h2_proto_sweep(void) {
ScrH2Emit e = scr_h2_emits[scr_h2_emits_head++];
ScrAlsCtx *prev = scr_als_dispatch_enter(
e.kind == SCR_H2_EMIT_STREAM_CLOSE || e.kind == SCR_H2_EMIT_STREAM_CLOSED ||
e.kind == SCR_H2_EMIT_STREAM_RST ||
e.kind == SCR_H2_EMIT_STREAM_DRAIN ||
e.kind == SCR_H2_EMIT_STREAM_WANT_TRAILERS ||
e.kind == SCR_H2_EMIT_STREAM_READY
@@ -2128,6 +2188,14 @@ static void scr_h2_proto_sweep(void) {
case SCR_H2_EMIT_STREAM_CLOSED:
scr_h2_stream_fire_close((ScrH2Stream *)e.h);
break;
case SCR_H2_EMIT_STREAM_RST: {
ScrH2Stream *st = (ScrH2Stream *)e.h;
if (st->sess != NULL && !st->sess->destroyed && !st->sess->goaway_sent &&
scr_h2_sock_alive(st->sess)) {
scr_h2_send_rst(st->sess, st->id, st->rst_code);
}
break;
}
case SCR_H2_EMIT_STREAM_DRAIN:
scr_h2_stream_drain((ScrH2Stream *)e.h);
break;
@@ -2142,6 +2210,17 @@ static void scr_h2_proto_sweep(void) {
break;
case SCR_H2_EMIT_SESSION_CLOSE: {
ScrH2Session *s = (ScrH2Session *)e.h;
if (s->srv_closing && !s->srv_close_deferred) {
/* Node's server 'close' callback runs before its sessions' 'close'
* events; one turn of deferral keeps that order. */
s->srv_close_deferred = true;
s->close_queued = false;
ScrClosure *tick = scr_closure_new((void *)&scr_h2_session_close_tick, 1);
tick->caps[0] = scr_box_new_obj(scr_http2_session_retain_v, scr_http2_session_release_v, NULL);
scr_box_set_ref(tick->caps[0], scr_http2_session_retain(s));
scr_next_tick(tick);
break;
}
if (!s->close_emitted) {
s->close_emitted = true;
scr_net_fire0_this(&s->close_ls, s, SCR_DYNH_H2_SESSION);
@@ -2329,12 +2408,85 @@ static void scr_h2_session_fail(ScrH2Session *s, const char *text, bool protocol
scr_h2_session_fail_code(s, text, protocol_error ? "ERR_HTTP2_ERROR" : NULL);
}
/* Deferred socket teardown for session.destroy(): mirrors Node's
* FinishClose + finishSessionClose (stop reading from the socket, wait for
* the peer's reply bytes such as GOAWAY to land in the kernel receive buffer,
* then end write half and close without draining them). A short fallback timer
* closes the socket if a silent peer sends nothing. */
static void scr_h2_on_closed(void *ctx);
static void scr_h2_finish_destroy_sock(ScrH2Session *s, bool from_readable) {
if (s->destroy_timer_handle > 0) {
scr_clear_interval(s->destroy_timer_handle);
s->destroy_timer_handle = 0;
}
if (scr_h2_sock_alive(s)) {
ScrNetSocket *sock = scr_net_sock_retain(s->sock);
scr_net_sock_set_native_reader_keep_ctx(sock, NULL, NULL, &scr_h2_on_closed, s);
#ifdef __APPLE__
/* Once EVFILT_READ has fired, the peer's reply bytes are already in the
* kernel receive buffer; closing directly without a preceding SHUT_WR FIN
* avoids a loopback FIN-before-RST race under CPU load on XNU. */
if (!from_readable) scr_net_sock_end(sock);
#else
(void)from_readable;
scr_net_sock_end(sock);
#endif
scr_net_sock_destroy(sock);
scr_net_sock_release(sock);
}
}
static void scr_h2_on_destroy_readable(void *ctx) {
scr_h2_finish_destroy_sock((ScrH2Session *)ctx, true);
}
static void scr_h2_destroy_fallback_tick(ScrClosure *cb) {
ScrH2Session *s = (ScrH2Session *)scr_box_get_ref(cb->caps[0]); /* +1 */
s->destroy_timer_handle = 0;
scr_h2_finish_destroy_sock(s, false);
scr_http2_session_release(s);
}
void scr_http2_session_destroy(ScrH2Session *s) {
if (s->destroyed) return;
bool alive = scr_h2_sock_alive(s);
bool sent_goaway_here = false;
/* Node's Http2Session::FinishClose sends GOAWAY(NO_ERROR) when the socket
* is established and no GOAWAY has been sent yet. */
if (alive && s->preface_done && !scr_net_sock_connecting(s->sock) && !s->goaway_sent) {
scr_h2_send_goaway(s, 0 /* NGHTTP2_NO_ERROR */);
sent_goaway_here = true;
}
s->destroyed = true;
scr_h2_session_abort_streams(s, 0 /* NGHTTP2_NO_ERROR */);
if (s->srv_timeout_handle > 0) {
scr_clear_interval(s->srv_timeout_handle);
s->srv_timeout_handle = 0;
}
if (s->sock_timeout_handle > 0) {
scr_clear_interval(s->sock_timeout_handle);
s->sock_timeout_handle = 0;
}
scr_h2_session_abort_streams(s, s->goaway_recv ? s->goaway_code
: 0 /* NGHTTP2_NO_ERROR */);
scr_h2_session_queue_close(s);
if (scr_h2_sock_alive(s)) scr_net_sock_destroy(s->sock);
if (alive && s->sock != NULL) {
ScrNetSocket *sock = s->sock;
if (scr_net_sock_connecting(sock) || !s->preface_done) {
scr_net_sock_destroy(sock);
} else if (sent_goaway_here && !s->goaway_recv) {
scr_net_sock_set_native_reader_keep_ctx(sock, NULL, &scr_h2_on_destroy_readable,
&scr_h2_on_closed, s);
ScrClosure *tick = scr_closure_new((void *)&scr_h2_destroy_fallback_tick, 1);
tick->caps[0] = scr_box_new_obj(scr_http2_session_retain_v, scr_http2_session_release_v, NULL);
scr_box_set_ref(tick->caps[0], scr_http2_session_retain(s));
double handle = scr_set_timeout_handle(tick, 50.0);
if (handle > 0) s->destroy_timer_handle = handle;
} else {
scr_net_sock_end(sock);
scr_net_sock_destroy(sock);
}
}
}
void scr_http2_session_close(ScrH2Session *s, ScrClosure *cb /*moves, nullable*/) {
@@ -2811,6 +2963,25 @@ proto_err:
}
static void scr_h2_on_data_in(void *ctx, const char *buf, size_t n);
static void scr_h2_srv_timeout_arm(ScrH2Session *s, double ms);
static void scr_h2_session_timeout_arm(ScrH2Session *s, double ms);
/* Activity (inbound reads or outbound writes) postpones both the server-level
* idle timeout and session.setTimeout on Darwin, matching Linux's
* scr_net_sock_touch and Node's session[kUpdateTimer](). */
static void scr_h2_session_touch_timeout(ScrH2Session *s) {
if (s == NULL || s->destroyed || s->close_emitted) return;
if (!s->client && s->srv_timeout_forward && s->srv_timeout_ms > 0) {
scr_h2_srv_timeout_arm(s, s->srv_timeout_ms);
}
if (s->sock_timeout_ms > 0) {
scr_h2_session_timeout_arm(s, s->sock_timeout_ms);
}
}
static void scr_h2_on_write_progress(void *ctx) {
scr_h2_session_touch_timeout((ScrH2Session *)ctx);
}
/* The socket's callbacks run in the session's context. */
static void scr_h2_on_data(void *ctx, const char *buf, size_t n) {
@@ -2822,6 +2993,7 @@ static void scr_h2_on_data(void *ctx, const char *buf, size_t n) {
static void scr_h2_on_data_in(void *ctx, const char *buf, size_t n) {
ScrH2Session *s = ctx;
if (s->destroyed) return;
scr_h2_session_touch_timeout(s);
/* append to the reassembly buffer */
if (s->rlen + n > s->rcap) {
size_t ncap = s->rcap ? s->rcap : 4096;
@@ -2921,6 +3093,10 @@ static void scr_h2_on_closed(void *ctx) {
static void scr_h2_on_closed_in(void *ctx) {
ScrH2Session *s = ctx;
s->destroyed = true;
if (s->destroy_timer_handle > 0) {
scr_clear_interval(s->destroy_timer_handle);
s->destroy_timer_handle = 0;
}
/* the socket is gone: the server no longer owns a live session */
if (s->srv != NULL) scr_h2_srv_untrack_session(s->srv, s);
scr_h2_session_abort_streams(s, 8 /* NGHTTP2_CANCEL */);
@@ -2942,8 +3118,21 @@ static bool scr_h2_on_err(void *ctx, ScrStr *msg) {
return consumed;
}
static bool scr_h2_str_ends_with(const ScrStr *s, const char *suffix) {
size_t slen = strlen(suffix);
return s != NULL && s->len >= slen && memcmp(s->data + (s->len - slen), suffix, slen) == 0;
}
static bool scr_h2_on_err_in(void *ctx, ScrStr *msg) {
ScrH2Session *s = ctx;
if (s->destroyed) return true;
/* Node's socketOnError: ignore ECONNRESET after a GOAWAY frame was received
* and destroy the session with the received GOAWAY code (no error event,
* and open streams settle with goaway_code instead of NGHTTP2_CANCEL). */
if (s->goaway_recv && scr_h2_str_ends_with(msg, "ECONNRESET")) {
scr_http2_session_destroy(s);
return true;
}
/* A server session always has a listener in Node (the server's own, which
* re-emits as 'sessionError'), so its socket error is never unhandled; a
* client session without an 'error' listener leaves it to the socket. */
@@ -3109,6 +3298,7 @@ static void scr_h2_stream_flush(ScrH2Stream *st) {
}
} else {
scr_h2_send_frame(s, SCR_H2_F_DATA, SCR_H2_FLAG_END_STREAM, st->id, NULL, 0);
scr_h2_stream_touch_timeout(st);
scr_h2_stream_mark_local_closed(st);
}
}
@@ -3356,6 +3546,7 @@ void scr_http2_stream_respond_wait(ScrH2Stream *st, ScrArr *pairs /*borrowed, nu
* END_STREAM even when the caller asked to end: the trailer block ends
* it after 'wantTrailers'. */
bool close_here = end_stream && !wait_trailers;
scr_h2_stream_touch_timeout(st);
scr_h2_send_headers(s, st->id, &block, close_here);
free(block.data);
if (close_here) {
@@ -3452,6 +3643,7 @@ void scr_http2_stream_additional_headers(ScrH2Stream *st, ScrArr *pairs /*borrow
scr_h2_hpack_encode(&block, ":status", 7, stbuf, (size_t)stn);
}
scr_h2_encode_regulars(&block, pairs);
scr_h2_stream_touch_timeout(st);
scr_h2_send_headers(st->sess, st->id, &block, false);
free(block.data);
}
@@ -3504,6 +3696,7 @@ void scr_http2_stream_send_trailers(ScrH2Stream *st, ScrArr *pairs /*borrowed, n
scr_str_release(name);
}
if (!scr_h2_regular_names_valid(pairs)) return;
scr_h2_stream_touch_timeout(st);
scr_h2_send_trailers_block(st, pairs);
}
@@ -5477,19 +5670,18 @@ static void scr_h2_fire_server_session(ScrH2Session *sess) {
* the session is destroyed (Node's unhandled server timeout). Answering
* handled keeps the net layer from firing the socket payload or destroying
* the socket itself. */
static bool scr_h2_srv_socket_timeout(void *ctx) {
ScrH2Session *s = (ScrH2Session *)ctx;
/* The net layer's surface path asks on every socket timeout: answer
* handled in each case so it never fires the socket payload or destroys
* the socket itself. A timer the SESSION armed (session.setTimeout) is not
* the server's: its own listeners fire below and the server does nothing. */
if (s == NULL || s->destroyed || s->srv == NULL) return true;
if (!s->srv_timeout_forward) return true;
/* The server-level idle timeout fired: the server's 'timeout' listeners
* hear the SESSION (Node's Http2Server), and with none the session is
* destroyed (Node's unhandled server timeout). */
static void scr_h2_srv_fire_timeout(ScrH2Session *s) {
if (s == NULL || s->destroyed || s->srv == NULL) return;
if (!s->srv_timeout_forward) return;
/* The server's idle timeout is one timer per session (Node fires it once
* and does not re-arm): the decision is consumed here, so a timer the
* SESSION arms afterwards (session.setTimeout) reaches only its own
* listeners and never the server again. */
s->srv_timeout_forward = false;
s->srv_timeout_ms = 0;
ScrH2SrvCtx *srv = s->srv;
size_t n = srv->timeout_ls.n;
if (n > 0) {
@@ -5511,9 +5703,59 @@ static bool scr_h2_srv_socket_timeout(void *ctx) {
* was a listener, so the timeout was handled (Node destroys only when no
* listener exists) */
if (!scr_exc_pending() && n == 0) scr_http2_session_destroy(s);
}
static bool scr_h2_srv_socket_timeout(void *ctx) {
/* The net layer's surface path asks on every socket timeout: answer
* handled in each case so it never fires the socket payload or destroys
* the socket itself. A timer the SESSION armed (session.setTimeout) is not
* the server's: its own listeners fire below and the server does nothing. */
scr_h2_srv_fire_timeout((ScrH2Session *)ctx);
return true;
}
/* Darwin: a session's accepted socket arms its idle timeout through the
* runtime's timer loop. The kqueue idle timer registered for the same socket
* does not wake this loop while it sleeps, so the server-level timeout is
* armed here instead; the net timer stays registered and harmless. */
static void scr_h2_srv_timeout_tick(ScrClosure *cb) {
ScrH2Session *s = (ScrH2Session *)scr_box_get_ref(cb->caps[0]); /* +1 */
s->srv_timeout_handle = 0;
scr_h2_srv_fire_timeout(s);
scr_http2_session_release(s);
}
static void scr_h2_srv_timeout_arm(ScrH2Session *s, double ms) {
#ifdef __APPLE__
if (s->srv_timeout_handle > 0) {
scr_clear_interval(s->srv_timeout_handle);
s->srv_timeout_handle = 0;
}
s->srv_timeout_ms = ms > 0 ? ms : 0;
if (!(ms > 0) || s->destroyed) return;
ScrClosure *tick = scr_closure_new((void *)&scr_h2_srv_timeout_tick, 1);
tick->caps[0] = scr_box_new_obj(scr_http2_session_retain_v, scr_http2_session_release_v, NULL);
scr_box_set_ref(tick->caps[0], scr_http2_session_retain(s));
double handle = scr_set_timeout_handle(tick, ms);
if (handle > 0) s->srv_timeout_handle = handle;
#else
(void)s;
(void)ms;
#endif
}
/* A session socket's idle period. On Darwin the runtime's timer loop owns
* the period: the socket's kqueue idle timer does not wake the loop, so it
* stays disarmed. The negated value tells scr_net.c to keep socket.timeout's
* answer without arming that timer. */
static void scr_h2_socket_set_timeout(ScrNetSocket *sock, double ms) {
#ifdef __APPLE__
scr_net_sock_set_timeout(sock, ms > 0 ? -ms : 0);
#else
scr_net_sock_set_timeout(sock, ms);
#endif
}
static void scr_h2_on_server_established(void *ctx) { scr_h2_fire_server_session(ctx); }
static void scr_h2_on_connection(void *ctx, ScrNetSocket *sock) {
@@ -5527,6 +5769,7 @@ static void scr_h2_on_connection(void *ctx, ScrNetSocket *sock) {
scr_net_sock_set_native_reader(sock, &scr_h2_on_data, &scr_h2_on_eof, &scr_h2_on_closed,
sess, &scr_h2_session_ctx_free);
scr_net_sock_set_native_events(sock, &scr_h2_on_timeout, &scr_h2_on_err);
scr_net_sock_set_native_write_progress(sock, &scr_h2_on_write_progress);
scr_net_sock_set_native_http_timeout(sock, &scr_h2_srv_socket_timeout);
/* the server's own idle timeout (server.timeout / setTimeout) arms each
* accepted session's socket, as Node's Http2Server applies it per session —
@@ -5534,7 +5777,8 @@ static void scr_h2_on_connection(void *ctx, ScrNetSocket *sock) {
ScrNetServer *netsrv = scr_net_sock_server(sock);
double server_idle_ms = netsrv != NULL ? scr_net_server_idle_ms(netsrv) : 0;
sess->srv_timeout_forward = server_idle_ms > 0;
if (server_idle_ms > 0) scr_net_sock_set_timeout(sock, server_idle_ms);
if (server_idle_ms > 0) scr_h2_socket_set_timeout(sock, server_idle_ms);
if (server_idle_ms > 0) scr_h2_srv_timeout_arm(sess, server_idle_ms);
scr_net_sock_set_h2_bound(sock);
scr_h2_send_settings(sess, 0xffffffffu);
/* 'session' fires in the connection callback, before the connection's
@@ -5823,6 +6067,7 @@ static ScrH2Session *scr_h2_handshake_with(ScrNetSocket *sock /*borrowed*/,
* path forwards its fire exactly as the accepted-connection and client
* paths do */
scr_net_sock_set_native_events(sock, &scr_h2_on_timeout, &scr_h2_on_err);
scr_net_sock_set_native_write_progress(sock, &scr_h2_on_write_progress);
scr_net_sock_set_native_http_timeout(sock, &scr_h2_srv_socket_timeout);
/* the server's own idle timeout (server.timeout / setTimeout) arms each
* accepted session's socket, as Node's Http2Server applies it per session —
@@ -5830,7 +6075,8 @@ static ScrH2Session *scr_h2_handshake_with(ScrNetSocket *sock /*borrowed*/,
ScrNetServer *netsrv = scr_net_sock_server(sock);
double server_idle_ms = netsrv != NULL ? scr_net_server_idle_ms(netsrv) : 0;
sess->srv_timeout_forward = server_idle_ms > 0;
if (server_idle_ms > 0) scr_net_sock_set_timeout(sock, server_idle_ms);
if (server_idle_ms > 0) scr_h2_socket_set_timeout(sock, server_idle_ms);
if (server_idle_ms > 0) scr_h2_srv_timeout_arm(sess, server_idle_ms);
scr_net_sock_set_h2_bound(sock);
/* The options' settings: the advertised limit goes out with the first
* SETTINGS frame and is what the peer sees; localSettings takes it when
@@ -5955,6 +6201,7 @@ ScrH2Session *scr_http2_connect(ScrStr *url /*borrowed*/, bool reject_unauthoriz
scr_net_sock_set_native_reader(sock, &scr_h2_on_data, &scr_h2_on_eof, &scr_h2_on_closed,
s, &scr_h2_session_ctx_free);
scr_net_sock_set_native_events(sock, &scr_h2_on_timeout, &scr_h2_on_err);
scr_net_sock_set_native_write_progress(sock, &scr_h2_on_write_progress);
scr_net_sock_set_h2_bound(sock);
scr_net_sock_set_native_established(sock, &scr_h2_on_established);
scr_net_sock_write_native(sock, SCR_H2_PREFACE, 24);
@@ -6160,10 +6407,44 @@ void scr_http2_server_set_timeout_cb(ScrNetServer *srv, double ms, ScrClosure *c
scr_http2_server_on_timeout(srv, cb, fn, false);
}
/* Darwin: the session socket's idle timeout runs on the runtime's timer
* loop, for the same reason as the server-level timeout above. */
static void scr_h2_session_timeout_tick(ScrClosure *cb) {
ScrH2Session *s = (ScrH2Session *)scr_box_get_ref(cb->caps[0]); /* +1 */
s->sock_timeout_handle = 0;
if (!s->destroyed && !s->close_emitted) {
scr_http2_session_retain(s);
scr_net_fire0_this(&s->timeout_ls, s, SCR_DYNH_H2_SESSION);
scr_http2_session_release(s);
}
scr_http2_session_release(s);
}
static void scr_h2_session_timeout_arm(ScrH2Session *s, double ms) {
#ifdef __APPLE__
if (s->sock_timeout_handle > 0) {
scr_clear_interval(s->sock_timeout_handle);
s->sock_timeout_handle = 0;
}
s->sock_timeout_ms = ms > 0 ? ms : 0;
if (!(ms > 0) || s->destroyed || s->close_emitted) return;
ScrClosure *tick = scr_closure_new((void *)&scr_h2_session_timeout_tick, 1);
tick->caps[0] = scr_box_new_obj(scr_http2_session_retain_v, scr_http2_session_release_v, NULL);
scr_box_set_ref(tick->caps[0], scr_http2_session_retain(s));
double handle = scr_set_timeout_handle(tick, ms);
if (handle > 0) s->sock_timeout_handle = handle;
#else
(void)s;
(void)ms;
#endif
}
void scr_http2_session_set_timeout(ScrH2Session *s, double msecs) {
if (s->destroyed || s->close_emitted) return;
if (!scr_h2_timeout_msecs_valid(msecs)) return;
if (s->sock != NULL) scr_net_sock_set_timeout(s->sock, msecs);
/* on Darwin the runtime timer loop owns the period on this platform */
if (s->sock != NULL) scr_h2_socket_set_timeout(s->sock, msecs);
scr_h2_session_timeout_arm(s, msecs);
}
void scr_http2_session_set_timeout_cb(ScrH2Session *s, double msecs, ScrClosure *cb /*moves*/) {
@@ -6175,7 +6456,8 @@ void scr_http2_session_set_timeout_cb(ScrH2Session *s, double msecs, ScrClosure
scr_closure_release(cb);
return;
}
if (s->sock != NULL) scr_net_sock_set_timeout(s->sock, msecs);
if (s->sock != NULL) scr_h2_socket_set_timeout(s->sock, msecs);
scr_h2_session_timeout_arm(s, msecs);
/* setTimeout(0, cb) disables the timer and does NOT register the
* callback; a registration of that same function leaves with it
* (Node's removeListener('timeout', callback)). */
+24 -5
View File
@@ -1059,8 +1059,21 @@ static SCR_TL size_t scr_layout_key_bytes;
static SCR_TL size_t scr_layout_array_bytes;
static SCR_TL bool scr_layout_registered;
const ScrLayout *scr_layout_root(void) { return &scr_layout_empty; }
static void scr_layout_exit_register(void);
const ScrLayout *scr_layout_root(void) {
/* Registering here keeps the reset after an island stop handler that is
* registered next: the exit stack runs newest first. */
scr_layout_exit_register();
return &scr_layout_empty;
}
/* Registered on the exit stack when the first layout is created. An island
* program may create its first layout while Node is already running (a class
* instance crossing lazily), which would put this ahead of the island's stop
* handler on the newest-first exit stack and free the layouts Node's exit
* listeners still read. A shared module or island start registers it early
* through scr_layout_root, as it does for the island's export release. */
static void scr_layout_reset(void) {
while (scr_layout_all) {
ScrLayout *layout = scr_layout_all;
@@ -1083,6 +1096,15 @@ static void scr_layout_reset(void) {
scr_layout_registered = false;
}
/* Registers the exit reset once, early enough to run after the island's
* stop handler (the exit stack is newest-first). scr_layout_root's callers
* are the registration point: the island start reads the empty root before
* its stop handler is registered. */
static void scr_layout_exit_register(void) {
if (scr_layout_registered) return;
if (scr_atexit(scr_layout_reset) == 0) scr_layout_registered = true;
}
#ifdef SCR_RC_AUDIT
/* For the runtime's unit tests: frees the layouts while no object uses one. */
void scr_layout_reset_idle(void) { scr_layout_reset(); }
@@ -1187,10 +1209,7 @@ const ScrLayout *scr_layout_add(const ScrLayout *layout, const char *key, size_t
store->items[store->used++] = (ScrLayoutKey){scr_dyn_key_copy(key, key_len), (uint32_t)key_len, hash};
*child = (ScrLayout){store->items, count, 0, NULL, parent, NULL, store, scr_layout_all, owns};
scr_layout_all = child;
if (!scr_layout_registered) {
scr_layout_registered = true;
scr_atexit(scr_layout_reset);
}
scr_layout_exit_register();
scr_layout_insert(child);
scr_layout_count++;
scr_layout_key_bytes += key_len;
+76 -22
View File
@@ -848,6 +848,7 @@ struct ScrNetSocket {
double timeout_ms;
bool timeout_ever; /* setTimeout ran: socket.timeout answers the value */
bool timeout_armed;
bool timeout_external; /* a protocol layer runs the period on its own timer */
ScrNetServer *server; /* +1 backref (accepted sockets), NULL for clients */
/* protocol layer (scr_http.c): a C-level reader — counts as a consumer
* for read-arming; its context BORROWS this socket and is freed with it */
@@ -1232,6 +1233,7 @@ static ssize_t scr_net_send(int fd, const void *buf, size_t len) {
* milliseconds. Re-arming an armed key replaces the deadline. */
static void scr_net_sock_timer_arm(ScrNetSocket *s) {
if (scr_net_poller == NULL || s->fd < 0 || s->timeout_ms <= 0) return;
if (s->timeout_external) return;
(void)scrp_timer_arm(scr_net_poller, s, s->timeout_ms, s);
s->timeout_armed = true;
}
@@ -1488,24 +1490,26 @@ static void scr_net_sock_update_read(ScrNetSocket *s) {
/* every consumer and flow change re-arms here: buffered bytes may now
* have a consumer */
scr_net_work_add(s);
bool want = s->fd >= 0 && !s->connecting && !s->rd_eof && !s->user_paused && !s->hold &&
(s->data_ls.n > 0 || s->pipe_dst != NULL || s->native_data != NULL ||
(s->tunnel != NULL && !s->tunnel->send_only) /* the proxy's CONNECT answer */ ||
s->flowing /* resume(): flow (and discard sans listeners) */ ||
s->readable_ls.n > 0 /* paused-mode consumer: bytes buffer */ ||
s->tops != NULL /* a transport is ALWAYS a consumer: the TLS
* layer must process protocol frames (the
* handshake, close_notify, 1.3 tickets)
* even when no app consumer exists, and a
* peer's FIN must reach the teardown —
* decrypted app data buffers like the
* paused-mode path's */ ||
s->wr_done /* FIN sent: drain to EOF so the peer's close is
* seen even with no consumer — Node resumes a
* finished socket the same way */ ||
(!s->eof_pending && s->rlen - s->rhead < s->read_ahead)
/* no consumer yet: read ahead into the buffer, as Node's
* stream does up to its high-water mark */) &&
bool want = s->fd >= 0 && !s->connecting && !s->rd_eof && !s->hold &&
((s->h2_bound && s->native_data == NULL && s->native_eof != NULL) ||
(!s->user_paused &&
(s->data_ls.n > 0 || s->pipe_dst != NULL || s->native_data != NULL ||
(s->tunnel != NULL && !s->tunnel->send_only) /* the proxy's CONNECT answer */ ||
s->flowing /* resume(): flow (and discard sans listeners) */ ||
s->readable_ls.n > 0 /* paused-mode consumer: bytes buffer */ ||
s->tops != NULL /* a transport is ALWAYS a consumer: the TLS
* layer must process protocol frames (the
* handshake, close_notify, 1.3 tickets)
* even when no app consumer exists, and a
* peer's FIN must reach the teardown —
* decrypted app data buffers like the
* paused-mode path's */ ||
s->wr_done /* FIN sent: drain to EOF so the peer's close is
* seen even with no consumer — Node resumes a
* finished socket the same way */ ||
(!s->eof_pending && s->rlen - s->rhead < s->read_ahead)
/* no consumer yet: read ahead into the buffer, as Node's
* stream does up to its high-water mark */))) &&
!(s->tunnel != NULL && s->tunnel->send_only);
if (want && !s->read_armed) {
scr_net_watch_read(s->fd, s, true);
@@ -1700,6 +1704,24 @@ static bool scr_net_sock_user_write(ScrNetSocket *s, const char *data, size_t le
return ok;
}
static void scr_net_sock_append_rbuf(ScrNetSocket *s, const char *data, size_t len);
/* A write failed (EPIPE/ECONNRESET), so the fd is about to close. Drain any
* bytes the peer already delivered into the kernel receive buffer first
* (for example an HTTP/2 GOAWAY frame or an early HTTP response) so the sweep
* delivers them to the protocol layer before the write error and close. */
static void scr_net_sock_drain_before_close(ScrNetSocket *s) {
if (s->fd < 0 || s->tops != NULL || s->rd_eof || s->user_paused || s->hold) return;
if (s->data_ls.n == 0 && s->pipe_dst == NULL && s->native_data == NULL && !s->flowing) return;
for (int i = 0; i < 8; i++) {
char buf[16384];
ssize_t n = read(s->fd, buf, sizeof buf);
if (n <= 0) break;
s->bytes_read += (size_t)n;
scr_net_sock_append_rbuf(s, buf, (size_t)n);
}
}
/* The write path shared by write()/end(data)/pipe delivery. Ignored on a
* dead or ended write half (Node fires 'error' there; this slice drops —
* SEMANTICS.md documents the bound). */
@@ -1760,6 +1782,7 @@ static void scr_net_sock_write_raw(ScrNetSocket *s, const char *data, size_t len
snprintf(msg, sizeof msg, "write %s", scr_net_errname(errno));
if (!s->pending_err) s->pending_err = scr_str_new(msg, strlen(msg));
s->had_error = true;
scr_net_sock_drain_before_close(s);
scr_net_sock_close_fd(s);
return;
}
@@ -1821,6 +1844,7 @@ void scr_net_sock_writev_native(ScrNetSocket *s, const ScrNetSlice *slices, size
snprintf(msg_text, sizeof msg_text, "write %s", scr_net_errname(errno));
if (!s->pending_err) s->pending_err = scr_str_new(msg_text, strlen(msg_text));
s->had_error = true;
scr_net_sock_drain_before_close(s);
scr_net_sock_close_fd(s);
return;
}
@@ -1864,6 +1888,7 @@ static void scr_net_sock_flush(ScrNetSocket *s) {
snprintf(msg, sizeof msg, "write %s", scr_net_errname(errno));
if (!s->pending_err) s->pending_err = scr_str_new(msg, strlen(msg));
s->had_error = true;
scr_net_sock_drain_before_close(s);
scr_net_sock_close_fd(s);
return;
}
@@ -2023,6 +2048,7 @@ static void scr_net_sock_read(ScrNetSocket *s) {
if (s->tops && !s->t_est) return; /* readiness feeds the handshake pump instead */
for (;;) {
if (s->fd < 0 || s->user_paused || s->hold) return;
if (s->h2_bound && s->native_data == NULL && s->native_eof != NULL) return;
bool flowing = s->data_ls.n > 0 || s->pipe_dst || s->native_data || s->flowing;
/* buffered (peeked/unshifted) bytes first — they precede the
* kernel's in the stream; a TLS engine drains them through its bio */
@@ -6763,9 +6789,23 @@ bool scr_net_sock_readable(ScrNetSocket *s) {
}
/* socket.setTimeout(ms): ms > 0 arms the idle timer NOW (Node starts the
* clock at the call — connecting time counts), ms <= 0 disables. */
* clock at the call — connecting time counts), ms <= 0 disables.
*
* An internal caller that runs the period on the runtime's timer loop
* (HTTP/2 on Darwin, where the kqueue idle timer does not wake the loop)
* passes the negated value: socket.timeout still answers the configured
* value and the socket's own idle timer stays disarmed. The program-facing
* setTimeout paths reject negative values, so the form is not reachable
* from a program. */
void scr_net_sock_set_timeout(ScrNetSocket *s, double ms) {
s->timeout_ever = true;
if (ms < 0) {
s->timeout_ms = -ms;
s->timeout_external = true;
scr_net_sock_timer_cancel(s);
return;
}
s->timeout_external = false;
if (ms > 0) {
/* the value is kept even without a descriptor: a socket configured
* before connect() keeps its deadline, which the dial arms as soon as
@@ -9864,13 +9904,22 @@ static bool scr_net_sock_settle(ScrNetSocket *sock) {
/* One socket's deferred work, in the order the sweep has always run it;
* false with an exception pending. */
static bool scr_net_sweep_sock(ScrNetSocket *sock) {
if (sock->fd >= 0 && !sock->user_paused && !sock->hold &&
if ((sock->fd >= 0 || (!sock->rd_eof && !sock->tops && sock->rlen > sock->rhead)) &&
!sock->user_paused && !sock->hold &&
(sock->data_ls.n > 0 || sock->pipe_dst || sock->native_data || sock->flowing) &&
((sock->tops && sock->t_est && sock->tops->pending && sock->tops->pending(sock->tctx)) ||
(!sock->tops && sock->rlen > sock->rhead))) {
/* deliver bytes the kernel can't re-signal (see scr_net_sock_has_work) */
ScrAlsCtx *prev = scr_als_dispatch_enter(sock->als);
scr_net_sock_read(sock);
if (sock->fd >= 0) {
scr_net_sock_read(sock);
} else {
while (!sock->user_paused && !sock->hold && sock->rlen > sock->rhead) {
char buf[65536];
size_t take = scr_net_sock_take_buffered(sock, buf, sizeof buf);
if (!scr_net_sock_deliver(sock, buf, take)) break;
}
}
scr_als_dispatch_leave(prev);
if (scr_exc_pending()) return false;
}
@@ -10167,7 +10216,12 @@ static bool scr_net_sock_event(ScrNetSocket *s, unsigned events) {
}
}
if ((events & SCRP_READABLE) && !scr_exc_pending() && s->fd >= 0) {
if (s->tunnel != NULL) scr_net_sock_tunnel_pump(s);
if (s->h2_bound && s->native_data == NULL && s->native_eof != NULL) {
ScrNetNativeEventFn cb = s->native_eof;
void *ctx = s->native_reader_ctx != NULL ? s->native_reader_ctx : s->native_ctx;
s->native_eof = NULL;
cb(ctx);
} else if (s->tunnel != NULL) scr_net_sock_tunnel_pump(s);
else if (s->tops && !s->t_est) scr_net_sock_transport_pump(s);
else scr_net_sock_read(s);
}
+6
View File
@@ -3916,6 +3916,12 @@ static void ni_start(void) {
scr_process_exit_hook = &ni_process_exit;
}
scr_ni_handles_install();
/* Registered first: the stack runs the newest entry first, so the stop
* handler below runs its exit listeners, drains their microtasks and
* stops Node before the layout reset or scr_ni_exports_release_all
* releases anything they read. */
(void)scr_layout_root();
(void)scr_ni_live_exports();
scr_atexit(ni_stop_atexit);
ni_hosted = *bridge;
ni_hosted.run_loop = &ni_run_loop;
+26 -1
View File
@@ -657,7 +657,13 @@ const void *scr_ni_export_identity(uint32_t id) {
return identity;
}
static void ni_exit_cleanup_ensure(void);
uint32_t scr_ni_live_exports(void) {
/* The island start reads this count to register the exit pass before its
* stop handler; the stack runs newest first, so the pass runs after
* Node's shutdown work. */
ni_exit_cleanup_ensure();
uint32_t n = 0;
bool held = ni_exports_take();
for (uint32_t i = 1; i < ni_exports_len; i++) n += ni_exports[i].value != NULL;
@@ -966,6 +972,23 @@ typedef struct {
} NiMethods;
static NiMethods *ni_methods = NULL;
static size_t ni_nmethods = 0, ni_methods_cap = 0;
/* The class tables, the export table and the shared modules all release in
* one pass at exit. The first registration from either side registers it:
* a program whose islands never share a module still leaves class tables,
* and the RC audit counts whatever they hold.
*
* The pass runs AFTER Node's own shutdown work. The exit stack runs newest
* first, so it must be registered before the island's stop handler
* (scr_node_island.c ni_start registers this first, then ni_stop_atexit,
* whose exit listeners, shutdown microtasks and Node stop therefore run
* before it). A class table registered lazily while Node is already running
* finds the pass already registered and does not re-register it ahead of
* the stop handler. */
static bool ni_exit_cleanup_registered = false;
static void ni_exit_cleanup_ensure(void) {
if (ni_exit_cleanup_registered) return;
if (scr_atexit(scr_ni_exports_release_all) == 0) ni_exit_cleanup_registered = true;
}
static ScrDyn *ni_methods_of(const ScrDyn *v) {
if (v->kind != SCR_DYN_TYPED_REF || v->v.typed_ref.type_key == NULL) return NULL;
@@ -991,6 +1014,7 @@ ScrDyn *scr_node_island_class_methods(ScrDyn *value, ScrDyn *builder) {
ni_methods_of(value) == NULL) {
ScrDyn *table = scr_dyn_call(builder, NULL, 0, "class methods");
if (table == NULL) return NULL;
ni_exit_cleanup_ensure();
if (ni_nmethods == ni_methods_cap) {
ni_methods_cap = ni_methods_cap ? ni_methods_cap * 2 : 8;
NiMethods *grown = realloc(ni_methods, ni_methods_cap * sizeof *grown);
@@ -1055,6 +1079,7 @@ ScrDyn *scr_node_island_class_methods_of(ScrDyn *cls, ScrDyn *builder, ScrDyn *c
ScrDyn *table = builder->kind == SCR_DYN_FUNC ? scr_dyn_call(builder, NULL, 0, "class methods")
: scr_dyn_new_obj();
if (table == NULL) return NULL;
ni_exit_cleanup_ensure();
if (ni_nmethods == ni_methods_cap) {
ni_methods_cap = ni_methods_cap ? ni_methods_cap * 2 : 8;
NiMethods *grown = realloc(ni_methods, ni_methods_cap * sizeof *grown);
@@ -1819,7 +1844,7 @@ void scr_node_island_share(ScrStr *path, ScrStr *exports, ScrDyn *accessor) {
memcmp(ni_shared[i].path->data, path->data, path->len) == 0)
return;
/* Released at exit (after Node stopped, when it started: atexit order). */
if (ni_nshared == 0 && ni_shared_cap == 0) scr_atexit(scr_ni_exports_release_all);
ni_exit_cleanup_ensure();
if (ni_nshared == ni_shared_cap) {
ni_shared_cap = ni_shared_cap ? ni_shared_cap * 2 : 8;
NiShared *grown = realloc(ni_shared, ni_shared_cap * sizeof *grown);
+7 -4
View File
@@ -1135,10 +1135,14 @@ static bool scr_rgn_try_free(ScrRgnThread *t, ScrRegion *r, bool tentative) {
bool pinned = false;
SCR_RGN_EACH(r, s, o) {
if (SCR_RC_COUNT(o) == SCR_RC_IMMORTAL) {
/* Published: other threads may hold it, uncounted. */
/* Published: other threads may hold it, uncounted. The region is
* pinned once, however many published objects it holds. */
r->state = SCR_RGN_PINNED;
t->stats.pinned++;
if (stats) fprintf(stderr, "scriptc region %llu: pinned: it holds a published object\n", (unsigned long long)r->id);
if (!pinned) {
t->stats.pinned++;
if (stats) fprintf(stderr, "scriptc region %llu: pinned: it holds a published object\n", (unsigned long long)r->id);
pinned = true;
}
#ifndef SCR_LSAN_IMMORTAL
return false;
#else
@@ -1148,7 +1152,6 @@ static bool scr_rgn_try_free(ScrRgnThread *t, ScrRegion *r, bool tentative) {
* report what a published object keeps through a layout slot, whose
* word is the cell tag over the box. No counts are settled: the pin
* is final. */
pinned = true;
continue;
#endif
}
+14 -7
View File
@@ -124,10 +124,11 @@ static void scr_ws_drop_client(ScrWs *ws) {
static void scr_ws_destroy_socket(ScrWs *ws) {
if (ws->sock == NULL) return;
scr_net_sock_clear_native_reader(ws->sock);
scr_net_sock_destroy(ws->sock);
scr_net_sock_release(ws->sock);
ScrNetSocket *sock = ws->sock;
ws->sock = NULL;
scr_net_sock_clear_native_reader(sock);
scr_net_sock_destroy(sock);
scr_net_sock_release(sock);
}
/* A handler that captures its own socket makes a cycle: the socket holds
@@ -778,8 +779,8 @@ static bool scr_ws_protocol_ok(ScrWs *ws, ScrStr *chosen) {
static void scr_ws_on_upgrade(ScrClosure *cb, ScrHttpReq *res, ScrNetSocket *socket,
ScrBytes *head) {
ScrWs *ws = scr_ws_from(cb);
scr_http_req_release(res);
if (ws == NULL) {
scr_http_req_release(res);
scr_bytes_release(head);
scr_net_sock_destroy(socket);
scr_net_sock_release(socket);
@@ -787,6 +788,7 @@ static void scr_ws_on_upgrade(ScrClosure *cb, ScrHttpReq *res, ScrNetSocket *soc
}
if (ws->discard || ws->ready_state == SCR_WS_CLOSED || ws->ready_state == SCR_WS_CLOSING) {
/* A close() during the handshake fails the connection. */
scr_http_req_release(res);
scr_bytes_release(head);
scr_net_sock_destroy(socket);
scr_net_sock_release(socket);
@@ -805,6 +807,7 @@ static void scr_ws_on_upgrade(ScrClosure *cb, ScrHttpReq *res, ScrNetSocket *soc
ScrStr *protocol_name = scr_str_new("sec-websocket-protocol", 22);
ScrStr *chosen = scr_http_req_header(res, protocol_name);
scr_str_release(protocol_name);
scr_http_req_release(res);
bool protocol_ok = scr_ws_protocol_ok(ws, chosen);
scr_str_release(chosen);
if (!accept_ok || !protocol_ok) {
@@ -816,9 +819,13 @@ static void scr_ws_on_upgrade(ScrClosure *cb, ScrHttpReq *res, ScrNetSocket *soc
return;
}
ws->sock = socket; /* takes the callback's reference */
/* The HTTP parser's context stays registered on the socket (freed at its
* death); the frame reader's callbacks receive the WebSocket instead. */
scr_net_sock_set_native_reader_keep_ctx(ws->sock, scr_ws_on_data, scr_ws_on_eof, scr_ws_on_eof, ws);
scr_ws_drop_client(ws);
/* The live socket takes ownership of the WebSocket (retiring the HTTP
* parser context until socket death), so an open WebSocket whose listeners
* do not capture the handle stays alive after the upgrade HTTP request
* settles; scr_ws_destroy_socket breaks the ws->sock edge on teardown. */
scr_net_sock_adopt_native_reader(ws->sock, scr_ws_on_data, scr_ws_on_eof, scr_ws_on_eof,
scr_ws_retain_v(ws), scr_ws_release_v);
ws->ready_state = SCR_WS_OPEN;
scr_ws_emit_type(ws, "open");
if (head != NULL && head->len > 0) scr_ws_on_data(ws, (const char *)head->data, (size_t)head->len);
+10 -6
View File
@@ -81,16 +81,20 @@ export const memoryHeavyFiles = {
// one clang per core, the largest of them 5.1 GB, beside a compile in Node
// that holds 6.5 to 7.4 GB. Beside a shard's corpus workers an OOM killed it
// intermittently (SIGKILL at 670-740 s, empty stderr, every test skipped).
// The sanitized Linux suite runs these three files in the
// native_frontend_san jobs (.github/workflows/ci.yml), one file per job with
// one worker and no corpus, on two of the runner's cores: four clangs at once
// no longer fit. The plain suite and the macOS shards keep them in
// the shard side queue, where the compiler's peak fits (macOS has no
// LeakSanitizer and runs these files one at a time beside the corpus).
// The sanitized Linux suite runs these files in the native_frontend_san jobs
// (.github/workflows/ci.yml), one file per job with one worker and no corpus,
// on two of the runner's cores: four clangs at once no longer fit.
// self-hosting-island-origin.test.ts compiles the same frontend in its own
// child process; beside a shard's corpus workers the kernel killed it with an
// empty stderr after 21 minutes, so it runs there too. The plain suite and
// the macOS shards keep them in the shard side queue, where the compiler's
// peak fits (macOS has no LeakSanitizer and runs these files one at a time
// beside the corpus).
export const nativeFrontendFiles = [
"tests/harness/self-hosting-native-frontend.test.ts",
"tests/harness/self-hosting-native-frontend-programs.test.ts",
"tests/harness/self-hosting-native-frontend-checks.test.ts",
"tests/harness/self-hosting-island-origin.test.ts",
];
/** The files a shard job leaves to a dedicated job. */
+65
View File
@@ -0,0 +1,65 @@
/* tsc-ts resolves a declaration file's /// <reference path> entries relative
* to its realpath. A pnpm install may leave @types/node/index.d.ts linked to
* the content-addressable store (a file symlink or a hardlink), where the
* sibling declaration files it references do not exist. Replace that one file
* with a fresh copy in its package directory before a build: the package's
* own siblings then resolve, and the file's content is unchanged. */
import { accessSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const scriptFile = fileURLToPath(import.meta.url);
const repositoryRoot = dirname(dirname(scriptFile));
/** Materialize `root`'s installed @types/node/index.d.ts as a fresh file.
* Returns the file it rewrote, or null when there is no installed copy. */
export function materializeNodeTypes(root = repositoryRoot) {
const candidates = [join(root, "node_modules", "@types", "node", "index.d.ts")];
if (root === repositoryRoot) {
try {
const require = createRequire(import.meta.url);
candidates.push(join(dirname(require.resolve("@types/node/package.json")), "index.d.ts"));
} catch {
// no installed Node type package; the candidate above is all there is
}
}
let file;
for (const candidate of candidates) {
try {
accessSync(candidate);
file = candidate;
break;
} catch {}
}
if (file === undefined) return null; // the build reports the missing types
let bytes;
try {
bytes = readFileSync(file);
} catch (error) {
if (error.code === "ENOENT") return null;
throw error;
}
const temporary = `${file}.scriptc-${process.pid}`;
writeFileSync(temporary, bytes);
try {
unlinkSync(file);
renameSync(temporary, file);
} catch (error) {
try {
unlinkSync(temporary);
} catch {}
// A parallel build may have replaced the file; its copy is equivalent.
try {
accessSync(file);
return file;
} catch {
throw error;
}
}
return file;
}
if (process.argv[1] !== undefined && resolve(process.argv[1]) === scriptFile)
materializeNodeTypes();
+10 -2
View File
@@ -65,15 +65,23 @@ if (missing.length > 0 || unexpected.length > 0) {
process.exit(1);
}
// The TypeScript 7 toolchain is the build's compiler. A package may run the
// repository's @types/node materializer first (it undoes a store link that
// tsc-ts would otherwise resolve beside the store file); nothing else may
// precede or replace tsc-ts.
const TSC_TS_BUILD = "node node_modules/tsc-ts/bin/tsc-ts.js -p tsconfig.json";
const MATERIALIZE_NODE_TYPES = "node ../../scripts/materialize-node-types.mjs";
const buildsWithTypeScript7 = (build) =>
build === TSC_TS_BUILD || build === `${MATERIALIZE_NODE_TYPES} && ${TSC_TS_BUILD}`;
const compilerPackage = JSON.parse(
readFileSync(resolve(repoRoot, "packages/compiler/package.json"), "utf8"),
);
if (compilerPackage.scripts?.build !== "node node_modules/tsc-ts/bin/tsc-ts.js -p tsconfig.json") {
if (!buildsWithTypeScript7(compilerPackage.scripts?.build)) {
console.error("@scriptc/compiler must build with the TypeScript 7 toolchain");
process.exit(1);
}
const cliPackage = JSON.parse(readFileSync(resolve(repoRoot, "packages/cli/package.json"), "utf8"));
if (cliPackage.scripts?.build !== "node node_modules/tsc-ts/bin/tsc-ts.js -p tsconfig.json") {
if (!buildsWithTypeScript7(cliPackage.scripts?.build)) {
console.error("scriptc must build with the TypeScript 7 toolchain");
process.exit(1);
}
@@ -31,8 +31,11 @@ server.listen(0, "127.0.0.1", () => {
agent,
headers: { "content-length": String(body.length) },
});
let settleWrite!: () => void;
const writeSettled = new Promise<void>((resolve) => (settleWrite = resolve));
first.write(body, (err?: Error) => {
writeState = (err as NodeJS.ErrnoException | undefined)?.code ?? "done";
settleWrite();
});
first.end();
first.on("error", (err: NodeJS.ErrnoException) => console.log("first error", err.code));
@@ -41,21 +44,22 @@ server.listen(0, "127.0.0.1", () => {
res.on("end", () => {
const second = http.get({ port, host: "127.0.0.1", path: "/after", agent }, (res2: http.IncomingMessage) => {
res2.resume();
res2.on("end", () => {
setTimeout(() => {
console.log(
"first",
res.statusCode,
"second",
res2.statusCode,
"write",
writeState,
"connections",
connections,
);
agent.destroy();
server.close();
}, 50);
res2.on("end", async () => {
// The upload's callback settles after the response on a loaded
// host; wait for it so the summary never races the write.
await writeSettled;
console.log(
"first",
res.statusCode,
"second",
res2.statusCode,
"write",
writeState,
"connections",
connections,
);
agent.destroy();
server.close();
});
});
second.on("error", (err: NodeJS.ErrnoException) => console.log("second error", err.code));
@@ -14,7 +14,11 @@ import * as http from "node:http";
import type { AddressInfo } from "node:net";
const BODY = "hello";
const PROBES = 10_000;
// macOS has 16,384 ephemeral ports (49152-65535) and a closed loopback
// connection keeps its client port in TIME_WAIT, so a lane that also runs
// other network programs can exhaust them; Node's oracle fails there too.
// 2,000 probes keep the repeated drop path well covered with headroom.
const PROBES = 2_000;
const server = http.createServer((_request, response) => {
response.writeHead(200, { "content-length": String(BODY.length) });
@@ -1,36 +1,68 @@
// A peer that never reads and then drops the connection while the upload is
// in flight: the request errors, and the writes whose bytes had reached the
// socket answer their callbacks with ERR_STREAM_DESTROYED after 'close'
// (Node's afterWrite on a destroyed stream).
// in flight: the request errors and a write callback settles once the stream
// is destroyed. Which event reports first, and which error code the write
// callback sees, differs between runs and platforms (Node itself varies), so
// the summary is printed once the request closes and states the stable facts.
import * as http from "node:http";
import * as net from "node:net";
let serverGotBytes = false;
const server = net.createServer((sock: net.Socket) => {
sock.once("data", () => console.log("server got bytes"));
setTimeout(() => sock.destroy(), 40);
sock.once("data", () => {
serverGotBytes = true;
sock.destroy();
});
});
server.listen(0, "127.0.0.1", () => {
const port = (server.address() as net.AddressInfo).port;
const req = http.request({ port, host: "127.0.0.1", method: "POST", path: "/" });
const chunk = Buffer.alloc(256 * 1024, 97);
let i = 0;
let reported = false;
const tick = () => {
if (i >= 64) {
req.end(() => console.log("end cb"));
let stopped = false;
let reqError = "none";
let writeCallback = false;
let finished = false;
const finish = (): void => {
if (finished) return;
finished = true;
// Two turns let the writes already issued answer their callbacks.
setImmediate(() =>
setImmediate(() => {
console.log(`server got bytes ${serverGotBytes}`);
console.log(`req error ${reqError}`);
console.log(`req close destroyed ${req.destroyed}`);
console.log(`write callback ${writeCallback}`);
server.close();
}),
);
};
const tick = (): void => {
if (stopped || i >= 64) {
if (!stopped) req.end(() => {});
return;
}
i += 1;
req.write(chunk, (err?: NodeJS.ErrnoException) => {
if (err && !reported) {
reported = true;
console.log("first write error", err.code, "destroyed", req.destroyed);
}
});
try {
req.write(chunk, () => {
writeCallback = true;
});
} catch {
// A write after the destroy throws instead of answering its callback.
}
setTimeout(tick, 5);
};
req.on("error", (e) => console.log("req error", (e as NodeJS.ErrnoException).code, "destroyed", req.destroyed));
req.on("close", () => console.log("req close destroyed", req.destroyed));
req.on("error", (e) => {
reqError = (e as NodeJS.ErrnoException).code ?? "error";
});
req.on("close", () => {
stopped = true;
finish();
});
tick();
setTimeout(() => server.close(), 900);
// Stop pacing writes if the request never closes; the harness timeout then
// names the program.
setTimeout(() => {
stopped = true;
}, 900);
});
@@ -56,7 +56,10 @@ left++;
if (!stream.destroyed) stream.end("y");
}, 50);
stream.on("close", () =>
lines.push(`2 server close rst=${stream.rstCode} aborted=${stream.aborted}`),
// The 'aborted' flag races in Node itself when the client's early break
// and its session destroy share a turn, so the line reports only the
// teardown code (0 for the clean session close on direct loopback).
lines.push(`2 server close rst=${stream.rstCode}`),
);
});
server.listen(0, "127.0.0.1", () => {
@@ -89,7 +92,15 @@ left++;
server.listen(0, "127.0.0.1", () => {
const client = connect(server);
const req = client.request({ ":path": "/" });
setTimeout(() => req.close(2), 50);
let reset = false;
const resetOnce = (): void => {
if (reset) return;
reset = true;
req.close(2);
};
// Safety for a server that never sends the chunk; the loop's own reset
// below normally wins long before this.
setTimeout(resetOnce, 500);
let closed = false;
let settled = false;
const finish = (): void => {
@@ -107,7 +118,13 @@ left++;
});
void (async () => {
try {
for await (const chunk of req) lines.push(`3 chunk ${(chunk as Buffer).toString()}`);
for await (const chunk of req) {
lines.push(`3 chunk ${(chunk as Buffer).toString()}`);
// the server writes z immediately: reset only after the loop holds
// the chunk, while its next read is pending, so the reset never
// races the first body chunk
setTimeout(resetOnce, 0);
}
lines.push("3 loop done");
} catch (err) {
lines.push(`3 caught ${(err as { code?: string }).code} ${(err as Error).message}`);
@@ -0,0 +1,154 @@
// Active outbound HTTP/2 writes refresh session, server, and stream idle
// timeouts even when the peer sends no inbound frames during the transfer,
// and the idle timeout still fires once outbound traffic stops.
import * as http2 from "node:http2";
import * as net from "node:net";
// Client preface + empty SETTINGS + HEADERS(stream 1, END_HEADERS|END_STREAM):
// :method=GET, :path=/, :scheme=http, :authority=localhost.
const REQUEST = Buffer.from([
0x50, 0x52, 0x49, 0x20, 0x2a, 0x20, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x32, 0x2e, 0x30, 0x0d, 0x0a,
0x0d, 0x0a, 0x53, 0x4d, 0x0d, 0x0a, 0x0d, 0x0a,
// SETTINGS (empty)
0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00,
// HEADERS on stream 1, flags=END_STREAM|END_HEADERS (0x05), len=14
0x00, 0x00, 0x0e, 0x01, 0x05, 0x00, 0x00, 0x00, 0x01,
// HPACK block: :method GET, :path /, :scheme http, :authority localhost
0x82, 0x84, 0x86, 0x41, 0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74,
]);
const CHUNK = Buffer.alloc(1024, 0x61);
const CHUNKS = 8; // 8 KiB total: stays well inside the 64 KiB initial window
async function runStreamingCase(
label: string,
mode: "session" | "server" | "server-unhandled",
): Promise<void> {
await new Promise<void>((resolve) => {
const server = http2.createServer();
let srvTimeouts = 0;
let sessTimeouts = 0;
let streamTimeouts = 0;
if (mode === "server") {
server.setTimeout(120);
server.on("timeout", () => {
srvTimeouts += 1;
});
} else if (mode === "server-unhandled") {
// Unhandled server timeout destroys an idle session; active outbound
// writes must keep it alive through the full transfer.
server.setTimeout(120);
}
server.on("sessionError", () => {});
server.on("session", (sess) => {
if (mode === "session") {
sess.setTimeout(120);
sess.on("timeout", () => {
sessTimeouts += 1;
});
}
});
server.on("stream", (stream) => {
stream.on("error", () => {});
stream.setTimeout(120);
stream.on("timeout", () => {
streamTimeouts += 1;
});
stream.respond({ ":status": 200 });
let sent = 0;
const sendNext = (): void => {
if (stream.destroyed) return;
sent += 1;
if (sent < CHUNKS) {
stream.write(CHUNK);
setTimeout(sendNext, 45);
} else {
stream.end(CHUNK);
}
};
setTimeout(sendNext, 45);
});
server.listen(0, "127.0.0.1", () => {
const port = (server.address() as net.AddressInfo).port;
// Raw peer sends only the request and stays silent (no WINDOW_UPDATE or
// SETTINGS ACK) so only outbound server writes refresh the timers.
const raw = net.connect(port, "127.0.0.1", () => {
raw.write(REQUEST);
});
raw.on("error", () => {});
let buf = Buffer.alloc(0);
let dataBytes = 0;
let sawEndStream = false;
let done = false;
const finish = (): void => {
if (done) return;
done = true;
console.log(
`${label}: bytes=${dataBytes} end=${sawEndStream} srvT=${srvTimeouts} sessT=${sessTimeouts} streamT=${streamTimeouts}`,
);
raw.destroy();
server.close(() => resolve());
};
raw.on("data", (chunk: Buffer) => {
buf = Buffer.concat([buf, chunk]);
while (buf.length >= 9) {
const len = buf.readUIntBE(0, 3);
if (buf.length < 9 + len) break;
const type = buf.readUInt8(3);
const flags = buf.readUInt8(4);
buf = buf.subarray(9 + len);
if (type === 0) {
dataBytes += len;
if ((flags & 0x01) !== 0) {
sawEndStream = true;
finish();
return;
}
}
}
});
raw.on("close", finish);
});
});
}
async function runIdleAfterTransferCase(): Promise<void> {
await new Promise<void>((resolve) => {
const server = http2.createServer();
let sessTimeouts = 0;
server.on("sessionError", () => {});
server.on("session", (sess) => {
sess.setTimeout(80);
sess.on("timeout", () => {
sessTimeouts += 1;
});
});
server.on("stream", (stream) => {
stream.on("error", () => {});
stream.respond({ ":status": 200 });
stream.end(CHUNK);
});
server.listen(0, "127.0.0.1", () => {
const port = (server.address() as net.AddressInfo).port;
const raw = net.connect(port, "127.0.0.1", () => {
raw.write(REQUEST);
});
raw.on("error", () => {});
raw.resume();
setTimeout(() => {
console.log(`idle-after-write: fired=${sessTimeouts > 0}`);
raw.destroy();
server.close(() => resolve());
}, 220);
});
});
}
async function main(): Promise<void> {
await runStreamingCase("session-timeout", "session");
await runStreamingCase("server-timeout", "server");
await runStreamingCase("server-unhandled", "server-unhandled");
await runIdleAfterTransferCase();
}
void main();
@@ -0,0 +1,57 @@
// A peer that sends a clean TCP FIN without any HTTP/2 GOAWAY frame closes
// open server streams with NGHTTP2_CANCEL (8) and aborted=true on both Linux
// and Darwin.
import * as http2 from "node:http2";
import * as net from "node:net";
// Client preface + empty SETTINGS + HEADERS(stream 1, END_HEADERS|END_STREAM):
// :method=GET (0x82), :path=/ (0x84), :scheme=http (0x86), :authority=localhost.
const REQUEST = Buffer.from([
0x50, 0x52, 0x49, 0x20, 0x2a, 0x20, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x32, 0x2e, 0x30, 0x0d, 0x0a,
0x0d, 0x0a, 0x53, 0x4d, 0x0d, 0x0a, 0x0d, 0x0a,
// SETTINGS (empty)
0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00,
// HEADERS on stream 1, flags=END_STREAM|END_HEADERS (0x05), len=14
0x00, 0x00, 0x0e, 0x01, 0x05, 0x00, 0x00, 0x00, 0x01,
// HPACK block: :method GET, :path /, :scheme http, :authority localhost
0x82, 0x84, 0x86, 0x41, 0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74,
]);
const server = http2.createServer();
server.on("sessionError", () => {});
server.on("stream", (stream) => {
stream.on("error", () => {});
stream.respond({ ":status": 200 });
stream.write("x");
stream.on("close", () => {
console.log(`server close rst=${stream.rstCode} aborted=${stream.aborted}`);
server.close();
});
});
server.listen(0, "127.0.0.1", () => {
const port = (server.address() as net.AddressInfo).port;
const raw = net.connect(port, "127.0.0.1", () => {
raw.write(REQUEST);
});
raw.on("error", () => {});
let buf = Buffer.alloc(0);
let ended = false;
raw.on("data", (chunk: Buffer) => {
if (ended) return;
buf = Buffer.concat([buf, chunk]);
while (buf.length >= 9) {
const len = buf.readUIntBE(0, 3);
if (buf.length < 9 + len) break;
const type = buf.readUInt8(3);
buf = buf.subarray(9 + len);
// Wait for the server's DATA frame so the stream is open and mid-response
// before sending a bare TCP FIN without GOAWAY.
if (type === 0) {
ended = true;
raw.end();
return;
}
}
});
});
+9 -3
View File
@@ -8,12 +8,18 @@ import type { AddressInfo } from "node:net";
const lines: string[] = [];
const server = http2.createServer();
server.on("session", (session) => {
const initialWindowSize = session.localSettings.initialWindowSize;
lines.push(`before ${session.pendingSettingsAck} ${session.localSettings.initialWindowSize}`);
session.setLocalWindowSize(2 ** 20);
lines.push(`after ${session.pendingSettingsAck} ${session.localSettings.initialWindowSize}`);
session.on("localSettings", (settings) =>
lines.push(`localSettings ${settings.initialWindowSize} ${session.pendingSettingsAck}`),
);
session.on("localSettings", (settings) => {
// The ACK of the session's initial SETTINGS reaches this listener only
// when it arrives after the listener is attached, which Node does not
// order; it repeats the initial record and is not what this program
// observes. Only a changed record is reported.
if (settings.initialWindowSize === initialWindowSize) return;
lines.push(`localSettings ${settings.initialWindowSize} ${session.pendingSettingsAck}`);
});
for (const value of [-5, 1.5, NaN, 2 ** 32, 2 ** 31 - 1]) {
try {
session.setLocalWindowSize(value);
@@ -1,3 +1,4 @@
// @requires-icu
// Element reads carry the type the checker gives them, as tsc and Node do.
// Without noUncheckedIndexedAccess an array, tuple, readonly-array or
// index-signature read is the element type, so a method call on it needs no
@@ -1,3 +1,4 @@
// @requires-icu
// A checked-dynamic Date (a JavaScript file's Date) reads its time value
// after the locale and options arguments, so an argument that moves the
// Date is seen by the formatter, as in Node.
@@ -1,3 +1,4 @@
// @requires-icu
// An optional locale expression evaluates once: the undefined test and the
// conversion both read the held value, so a side effect runs one time.
let evaluations = 0;
@@ -1,3 +1,4 @@
// @requires-icu
// A NumberFormat locale can be a string the program holds: ICU canonicalizes
// it, and a structurally invalid tag throws Node's RangeError.
function format(value, locale) {
@@ -14,18 +14,38 @@ const blocked = new net.BlockList();
blocked.addAddress("127.0.0.1", "ipv4");
const probe = (label: string, options: net.ServerOpts, next: () => void): void => {
const server = net.createServer(options, (socket) => {
// The server's 'connection' and the client's 'connect' race (either can
// run first, in Node too), so the two lines print in one fixed order once
// both are known. A blocked connection reports only the client side.
let accepted = false;
let connected = false;
let reported = false;
const reportBoth = (): void => {
if (reported || !accepted || !connected) return;
reported = true;
say(label, "connection");
say(label, "client connect");
};
const server = net.createServer(options, (socket) => {
accepted = true;
reportBoth();
socket.on("error", () => {});
socket.destroy();
});
server.on("error", (err) => say(label, "server error", codeOf(err)));
server.listen(0, "127.0.0.1", () => {
const client = net.connect((server.address() as { port: number }).port, "127.0.0.1");
client.on("connect", () => say(label, "client connect"));
client.on("connect", () => {
connected = true;
reportBoth();
});
client.on("data", () => {});
client.on("error", (err) => say(label, "client error", codeOf(err)));
client.on("close", () => {
if (!reported && connected) {
reported = true;
say(label, "client connect");
}
say(label, "client close");
server.close(() => {
say(label, "server closed");
@@ -0,0 +1,17 @@
// @requires-libnode
// A native class instance crosses into an island after the island started,
// so its class-method table registers while Node runs. The island keeps the
// instance and uses it from its 'beforeExit'/'exit' listeners and from the
// microtasks their handlers queue: the exit ordering must let Node's
// shutdown work finish before any native table or export is released.
import { start, install } from "exit-pkg";
start();
class Late {
label(): string {
return "late-native";
}
}
install(new Late());
@@ -0,0 +1,2 @@
export function start(): void;
export function install(value: { label(): string }): void;
@@ -0,0 +1,19 @@
"use strict";
// require('node:vm') makes the compiler serve this package from an island.
const vm = require("node:vm");
let saved = null;
exports.start = () => {
vm.runInNewContext("1");
process.on("exit", () => {
if (saved === null) return;
console.log("exit", saved.label());
Promise.resolve().then(() => console.log("micro", saved.label()));
});
process.on("beforeExit", () => {
if (saved === null) return;
Promise.resolve().then(() => console.log("beforeExit-micro", saved.label()));
});
};
exports.install = (value) => {
saved = value;
};
@@ -0,0 +1 @@
{ "name": "exit-pkg", "version": "1.0.0", "main": "index.js", "types": "index.d.ts" }
@@ -1,3 +1,4 @@
// @requires-icu
const c = process.config;
console.log("shape", typeof c, Object.isFrozen(c), Object.isFrozen(c.variables), Object.isFrozen(c.target_defaults));
console.log("keys", Object.keys(c).join(","));
+1
View File
@@ -1,3 +1,4 @@
// @requires-icu
// process.config answers the same build description from a worker: the ICU
// flag is a property of the linked binary, not of the thread that reads it.
const { Worker, isMainThread, parentPort } = require("node:worker_threads");
+14 -8
View File
@@ -13,11 +13,10 @@ const child = fork(childPath, [], {
stdio: ["ignore", "inherit", "inherit", "ipc"],
});
console.log("parent connected", child.connected);
// The parent and the child share the inherited stdout, so a line printed from
// a channel handler races the child's own send-callback lines. The handler
// lines are buffered and printed when the child exits, after its last write;
// which lines print, and their order, is unchanged.
const connected = child.connected;
// The parent and the child share the inherited stdout. Every parent line is
// held until the child exits, after its last write, so the summary order does
// not depend on how the two processes are scheduled.
const pending: string[] = [];
child.once("message", (message: { connected: boolean; echo: string }) => {
pending.push(`reply ${message.echo} ${message.connected}`);
@@ -26,7 +25,14 @@ child.once("disconnect", () => {
pending.push(`parent disconnect ${child.connected}`);
});
child.once("exit", (code) => {
for (const line of pending) console.log(line);
console.log("parent exit", code);
// 'exit' can run before a queued 'disconnect' from the closing IPC
// channel; one macrotask lets it land so the summary is the same either
// way.
setTimeout(() => {
console.log("parent connected", connected);
console.log("send", sent);
for (const line of pending) console.log(line);
console.log("parent exit", code);
}, 20);
});
console.log("send", child.send({ kind: "ping" }));
const sent = child.send({ kind: "ping" });
+1 -1
View File
@@ -98,5 +98,5 @@ server.listen(0, "127.0.0.1", () => {
if (finished) return;
console.log("timeout");
process.exit(1);
}, 2000);
}, 10000);
});
+1 -1
View File
@@ -59,5 +59,5 @@ server.listen(0, "127.0.0.1", () => {
setTimeout(() => {
console.log("timeout", closed);
process.exit(1);
}, 5000);
}, 30000);
});
@@ -0,0 +1,48 @@
// An open WebSocket whose listeners do not capture the handle stays alive after
// the HTTP 101 upgrade request settles and delivers frames that arrive later in
// a separate read (empty upgrade head).
import * as http from "node:http";
import type { Socket } from "node:net";
import { createHash } from "node:crypto";
const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
function serverFrame(opcode: number, payload: Buffer): Buffer {
return Buffer.concat([Buffer.from([0x80 | opcode, payload.length]), payload]);
}
const server = http.createServer();
server.on("upgrade", (req: http.IncomingMessage, socket: Socket) => {
const key = String(req.headers["sec-websocket-key"]);
const accept = createHash("sha1").update(key + GUID).digest("base64");
socket.on("error", () => {});
socket.write(
"HTTP/1.1 101 Switching Protocols\r\n" +
"Upgrade: websocket\r\n" +
"Connection: Upgrade\r\n" +
"Sec-WebSocket-Accept: " +
accept +
"\r\n\r\n",
);
// Delay the first WebSocket frame past the upgrade settle so head is empty.
setTimeout(() => {
socket.write(serverFrame(1, Buffer.from("delayed-hello")));
setTimeout(() => {
socket.write(serverFrame(8, Buffer.from([0x03, 0xe8])));
socket.end();
}, 20);
}, 30);
socket.on("data", () => {});
});
server.listen(0, "127.0.0.1", () => {
const port = (server.address() as { port: number }).port;
const ws = new WebSocket("ws://127.0.0.1:" + String(port) + "/");
ws.onmessage = (event) => {
console.log("message", String(event.data));
};
ws.onclose = (event) => {
console.log("close", event.code, event.wasClean);
server.close();
};
});
+26 -12
View File
@@ -144,21 +144,35 @@ test("the sanitized three.js nodes build leaves the Linux corpus for its own job
});
test("the sanitized native frontend builds leave the Linux shard side queue", () => {
const selected = (flavor: "plain" | "san", platform: string) =>
const queues = (flavor: "plain" | "san", platform: string) =>
Array.from({ length: 20 }, (_, index) =>
ciTestPlan({ shard: `${index + 1}/20`, flavor, platform }),
)
.flatMap((plan) =>
plan.side.flatMap((task) => task.args).filter((arg) => nativeFrontendFiles.includes(arg)),
)
.sort();
const all = [...nativeFrontendFiles].sort();
).map((plan) => plan.side.flatMap((task) => task.args));
for (const platform of ["linux", "darwin"]) {
// The plain compile fits in the shard's budget; the sanitized Linux one
// does not, and it runs in its own jobs instead. The macOS shards, which
// have no LeakSanitizer, keep them in the side queue.
expect(selected("plain", platform), platform).toEqual(all);
expect(selected("san", platform), platform).toEqual(platform === "linux" ? [] : all);
for (const flavor of ["plain", "san"] as const) {
// The plain compile fits in the shard's budget; the sanitized Linux one
// does not, and it runs in its own jobs instead. The macOS shards, which
// have no LeakSanitizer, keep them in the side queue. A measured file is
// named by exactly one shard; an unmeasured one is left to the
// file-sharded run, which gives each file to one shard. A shard that
// does not run the file excludes it, so none runs it twice.
const dedicated = flavor === "san" && platform === "linux";
const args = queues(flavor, platform);
for (const file of nativeFrontendFiles) {
const named = args.flat().filter((arg) => arg === file).length;
const excluded = args.every((shard) => shard.includes(`--exclude=${file}`));
if (dedicated) {
expect(named, file).toBe(0);
expect(excluded, file).toBe(true);
} else if (file in testCosts[flavor]) {
expect(named, file).toBe(1);
expect(excluded, file).toBe(true);
} else {
expect(named, file).toBe(0);
expect(excluded, file).toBe(false);
}
}
}
}
});
@@ -0,0 +1 @@
{ "plain": 20000, "san": 40000 }
+1 -1
View File
@@ -203,7 +203,7 @@ function requiresIcu(file: string): boolean {
* output to compare a compiled program against. The program still runs on
* every other platform. A program states the abort in its own comment. */
function skipsDarwin(file: string): boolean {
return directiveHead(file).some((l) => /^\/\/ @skip-darwin\s*$/.test(l));
return directiveHead(file).some((l) => /^\/\/ @skip-darwin\b/.test(l));
}
/** `// @normalize-pid` in the directive head: Node's process warnings
+22 -178
View File
@@ -389,30 +389,9 @@
"clo-i2n/U.forin": "unsupported",
"clo-i2n/I.taker": "proxy=wrong"
},
"arraybuffer.control.-": {
"T.clone": "throws",
"U.forin": "unsupported",
"U.clone": "throws"
},
"arraybuffer.p": {
"i2n/T.clone": "throws",
"i2n/U.forin": "unsupported",
"i2n/U.clone": "throws",
"n2i2n/U.forin": "unsupported",
"n2i2n/U.clone": "throws",
"clo-i2n/U.forin": "unsupported",
"clo-i2n/U.clone": "throws"
},
"arraybuffer.u": {
"i2n/T.clone": "throws",
"i2n/U.forin": "unsupported",
"i2n/U.clone": "throws",
"n2i2n/U.forin": "unsupported",
"n2i2n/U.clone": "throws",
"clo-n2i/N.callback": "clone=throws,forin=unsupported",
"clo-i2n/U.forin": "unsupported",
"clo-i2n/U.clone": "throws"
},
"arraybuffer.control.-": {},
"arraybuffer.p": {},
"arraybuffer.u": {},
"async-generator.control.-": {
"T.json": "refused:SC1090",
"T.clone": "unsupported",
@@ -461,17 +440,11 @@
"clo-i2n/I.taker": "clone=wrong,ctor=unsupported,n1=unsupported,proto=wrong,rest=throws,str=unsupported,tag=wrong"
},
"async-iterable.p": {
"i2n/N.read.sum": "throws",
"i2n/U.forin": "unsupported",
"i2n/N.param": "sum=throws",
"i2n2i/N.read@mixed.sum": "throws",
"clo-n2i/N.callback": "sum=throws",
"clo-i2n/N.read.sum": "throws",
"clo-i2n/U.forin": "unsupported"
},
"async-iterable.u": {
"i2n/U.forin": "unsupported",
"i2n/N.cast.read.sum": "throws",
"clo-n2i/N.callback": "forin=unsupported",
"clo-i2n/U.forin": "unsupported"
},
@@ -657,24 +630,10 @@
"clo-n2i/N.callback": "forin=unsupported",
"clo-i2n/U.forin": "unsupported"
},
"dataview.control.-": {
"U.clone": "wrong"
},
"dataview.p": {
"i2n/U.clone": "wrong",
"n2i2n/U.clone": "wrong",
"clo-i2n/U.clone": "wrong"
},
"dataview.u": {
"i2n/U.clone": "wrong",
"n2i2n/U.clone": "wrong",
"clo-n2i/N.callback": "clone=wrong",
"clo-i2n/U.clone": "wrong"
},
"date.control.-": {
"U.forin#valid": "unsupported",
"U.forin#invalid": "unsupported"
},
"dataview.control.-": {},
"dataview.p": {},
"dataview.u": {},
"date.control.-": {},
"date.p": {
"n2i/I.inspect#valid": "throws",
"n2i/I.read#valid": "throws",
@@ -896,44 +855,35 @@
"error.control.-": {
"N.read.keys": "refused:SC2020",
"N.read.json": "refused:SC1090",
"N.read.ctor": "refused:SC2020",
"T.json": "refused:SC1090",
"N.mapkey": "refused:SC2020",
"W.result.read.str": "refused:SC1090",
"W.result.mapkey": "refused:SC2020",
"N.cast.read.keys": "refused:SC2020",
"N.cast.read.json": "refused:SC1090",
"N.cast.read.ctor": "refused:SC2020",
"N.read@nat.keys": "refused:SC2020",
"N.read@nat.json": "refused:SC1090",
"N.read@nat.ctor": "refused:SC2020"
"N.read@nat.json": "refused:SC1090"
},
"error.p": {
"n2i/N.read@isl.keys": "refused:SC2020",
"n2i/N.read@isl.json": "refused:SC1090",
"n2i/N.read@isl.ctor": "refused:SC2020",
"i2n/S.make": "exit",
"n2i2n/N.mapkey": "refused:SC2020",
"n2i2n/N.read.keys": "refused:SC2020",
"n2i2n/N.read.json": "refused:SC1090",
"n2i2n/N.read.ctor": "refused:SC2020",
"n2i2n/P.read@back.keys": "refused:SC2020",
"n2i2n/P.read@back.json": "refused:SC1090",
"n2i2n/P.read@back.ctor": "refused:SC2020",
"n2i2n/N.read@isl.keys": "refused:SC2020",
"n2i2n/N.read@isl.json": "refused:SC1090",
"n2i2n/N.read@isl.ctor": "refused:SC2020",
"i2n2i/S.make": "exit",
"i2n2i/S.make2": "exit",
"clo-n2i/cb.keys": "refused:SC2020",
"clo-n2i/cb.json": "refused:SC1090",
"clo-n2i/cb.ctor": "refused:SC2020",
"clo-i2n/S.call": "exit"
},
"error.u": {
"n2i/P.read@isl.keys": "refused:SC2020",
"n2i/P.read@isl.json": "refused:SC1090",
"n2i/P.read@isl.ctor": "refused:SC2020",
"i2n/U.forin": "unsupported",
"i2n/N.cast": "exit",
"clo-i2n/U.forin": "unsupported"
@@ -941,7 +891,6 @@
"error.w": {
"n2i/P.read@isl.keys": "refused:SC2020",
"n2i/P.read@isl.json": "refused:SC1090",
"n2i/P.read@isl.ctor": "refused:SC2020",
"i2n/S.make": "exit",
"n2i2n/N.mapkey": "refused:SC2020",
"n2i2n/N.read.str": "refused:SC1090",
@@ -1562,8 +1511,7 @@
"clo-i2n/U.forin": "unsupported"
},
"map-obj.control.-": {
"T.json": "refused:SC1090",
"U.forin": "unsupported"
"T.json": "refused:SC1090"
},
"map-obj.p": {
"i2n/N.read.getByKey": "wrong",
@@ -1597,7 +1545,6 @@
"n2i2n/N.is": "refused:SC8010",
"n2i2n/N.mapkey": "refused:SC8010",
"n2i2n/N.indexOf": "refused:SC8010",
"n2i2n/N.read.size": "throws",
"n2i2n/N.read.getByKey": "throws",
"n2i2n/U.typeof": "refused:SC8010",
"n2i2n/U.isArray": "refused:SC8010",
@@ -1608,7 +1555,6 @@
"n2i2n/U.forin": "refused:SC8010",
"n2i2n/U.inst": "refused:SC8010",
"n2i2n/U.clone": "refused:SC8010",
"n2i2n/N.read@isl.size": "throws",
"n2i2n/N.read@isl.getByKey": "throws",
"clo-n2i/N.callback": "throws",
"clo-i2n/N.read.getByKey": "wrong",
@@ -1626,14 +1572,12 @@
"map-obj.u": {
"i2n/U.forin": "unsupported",
"i2n/N.cast": "exit",
"n2i2n/U.forin": "unsupported",
"clo-n2i/N.callback": "forin=unsupported",
"clo-i2n/U.forin": "unsupported"
},
"map.control.-": {
"N.read.json": "refused:SC1090",
"T.json": "refused:SC1090",
"U.forin": "unsupported",
"S.widen": "refused:SC1090",
"S.result": "refused:SC1090",
"N.cast.read.json": "refused:SC1090",
@@ -1674,7 +1618,6 @@
"n2i2n/N.is": "refused:SC8010",
"n2i2n/N.mapkey": "refused:SC8010",
"n2i2n/N.indexOf": "refused:SC8010",
"n2i2n/N.read.size": "throws",
"n2i2n/N.read.isMap": "refused:SC8010",
"n2i2n/N.read.json": "refused:SC8010",
"n2i2n/U.typeof": "refused:SC8010",
@@ -1687,7 +1630,6 @@
"n2i2n/U.inst": "refused:SC8010",
"n2i2n/U.clone": "refused:SC8010",
"n2i2n/P.read@back.json": "refused:SC1090",
"n2i2n/N.read@isl.size": "throws",
"n2i2n/N.read@isl.isMap": "refused:SC8010",
"n2i2n/N.read@isl.json": "refused:SC8010",
"clo-n2i/cb.json": "refused:SC1090",
@@ -1708,7 +1650,6 @@
"n2i/P.read@isl.json": "refused:SC1090",
"i2n/U.forin": "unsupported",
"i2n/N.cast": "exit",
"n2i2n/U.forin": "unsupported",
"clo-n2i/N.callback": "forin=unsupported",
"clo-i2n/U.forin": "unsupported"
},
@@ -1936,7 +1877,14 @@
"clo-i2n/U.forin": "unsupported",
"clo-i2n/I.taker": "clone=message"
},
"rec-extra.control.-": {},
"rec-extra.control.-": {
"N.read.keys": "wrong",
"N.read.json": "crash",
"N.read.n": "wrong",
"N.read.inExtra": "wrong",
"N.read.entries": "crash",
"T.json": "crash"
},
"rec-extra.i": {
"i2n/U.forin": "unsupported",
"clo-i2n/U.forin": "unsupported"
@@ -2003,113 +1951,25 @@
"clo-i2n/U.forin": "unsupported",
"clo-i2n/I.taker": "desc=wrong,ext=wrong,frozen=wrong"
},
"rec-idx.control.-": {
"N.cast.read.nope#xy": "throws",
"N.cast.read.x#order": "throws",
"N.cast.read.y#order": "throws",
"N.cast.read.nope#order": "throws",
"N.cast.read.x#empty": "throws",
"N.cast.read.y#empty": "throws",
"N.cast.read.nope#empty": "throws"
},
"rec-idx.control.-": {},
"rec-idx.p": {
"n2i/N.read@isl.y#xy": "throws",
"n2i/N.read@isl.nope#xy": "throws",
"n2i/N.read@isl.x#order": "throws",
"n2i/N.read@isl.y#order": "throws",
"n2i/N.read@isl.nope#order": "throws",
"n2i/N.read@isl.x#empty": "throws",
"n2i/N.read@isl.y#empty": "throws",
"n2i/N.read@isl.nope#empty": "throws",
"i2n/N.read.nope#xy": "throws",
"i2n/U.forin#xy": "unsupported",
"i2n/N.param#xy": "nope=throws",
"i2n/N.read@isl.y#xy": "throws",
"i2n/N.read@isl.nope#xy": "throws",
"i2n/N.read.x#order": "throws",
"i2n/N.read.y#order": "throws",
"i2n/N.read.nope#order": "throws",
"i2n/U.forin#order": "unsupported",
"i2n/N.param#order": "nope=throws,x=throws,y=throws",
"i2n/N.read@isl.x#order": "throws",
"i2n/N.read@isl.y#order": "throws",
"i2n/N.read@isl.nope#order": "throws",
"i2n/N.read.x#empty": "throws",
"i2n/N.read.y#empty": "throws",
"i2n/N.read.nope#empty": "throws",
"i2n/U.forin#empty": "unsupported",
"i2n/N.param#empty": "nope=throws,x=throws,y=throws",
"i2n/N.read@isl.x#empty": "throws",
"i2n/N.read@isl.y#empty": "throws",
"i2n/N.read@isl.nope#empty": "throws",
"i2n/N.read.nope#nullproto": "throws",
"i2n/U.forin#nullproto": "unsupported",
"i2n/U.inst#nullproto": "wrong",
"i2n/N.param#nullproto": "nope=throws",
"i2n/N.read@isl.y#nullproto": "throws",
"i2n/N.read@isl.nope#nullproto": "throws",
"n2i2n/N.read.nope#xy": "throws",
"n2i2n/P.read@back.nope#xy": "throws",
"n2i2n/N.read@isl.y#xy": "throws",
"n2i2n/N.read@isl.nope#xy": "throws",
"n2i2n/N.read.x#order": "throws",
"n2i2n/N.read.y#order": "throws",
"n2i2n/N.read.nope#order": "throws",
"n2i2n/P.read@back.y#order": "throws",
"n2i2n/P.read@back.nope#order": "throws",
"n2i2n/N.read@isl.y#order": "throws",
"n2i2n/N.read@isl.nope#order": "throws",
"n2i2n/N.read.x#empty": "throws",
"n2i2n/N.read.y#empty": "throws",
"n2i2n/N.read.nope#empty": "throws",
"n2i2n/P.read@back.y#empty": "throws",
"n2i2n/P.read@back.nope#empty": "throws",
"n2i2n/N.read@isl.y#empty": "throws",
"n2i2n/N.read@isl.nope#empty": "throws",
"i2n2i/N.read@mixed.x#order": "throws",
"i2n2i/N.read@mixed.x#empty": "throws",
"clo-n2i/N.callback#xy": "nope=throws",
"clo-n2i/N.callback#order": "nope=throws,x=throws,y=throws",
"clo-n2i/N.callback#empty": "nope=throws,x=throws,y=throws",
"clo-n2i/N.callback#nullproto": "nope=throws",
"clo-i2n/N.read.nope#xy": "throws",
"clo-i2n/U.forin#xy": "unsupported",
"clo-i2n/N.read.x#order": "throws",
"clo-i2n/N.read.y#order": "throws",
"clo-i2n/N.read.nope#order": "throws",
"clo-i2n/U.forin#order": "unsupported",
"clo-i2n/N.read.x#empty": "throws",
"clo-i2n/N.read.y#empty": "throws",
"clo-i2n/N.read.nope#empty": "throws",
"clo-i2n/U.forin#empty": "unsupported",
"clo-i2n/N.read.nope#nullproto": "throws",
"clo-i2n/U.forin#nullproto": "unsupported",
"clo-i2n/U.inst#nullproto": "wrong"
},
"rec-idx.u": {
"i2n/U.forin#xy": "unsupported",
"i2n/N.cast.read.nope#xy": "throws",
"i2n/N.cast.read@isl.y#xy": "throws",
"i2n/N.cast.read@isl.nope#xy": "throws",
"i2n/U.forin#order": "unsupported",
"i2n/N.cast.read.x#order": "throws",
"i2n/N.cast.read.y#order": "throws",
"i2n/N.cast.read.nope#order": "throws",
"i2n/N.cast.read@isl.x#order": "throws",
"i2n/N.cast.read@isl.y#order": "throws",
"i2n/N.cast.read@isl.nope#order": "throws",
"i2n/U.forin#empty": "unsupported",
"i2n/N.cast.read.x#empty": "throws",
"i2n/N.cast.read.y#empty": "throws",
"i2n/N.cast.read.nope#empty": "throws",
"i2n/N.cast.read@isl.x#empty": "throws",
"i2n/N.cast.read@isl.y#empty": "throws",
"i2n/N.cast.read@isl.nope#empty": "throws",
"i2n/U.forin#nullproto": "unsupported",
"i2n/U.inst#nullproto": "wrong",
"i2n/N.cast.read.nope#nullproto": "throws",
"i2n/N.cast.read@isl.y#nullproto": "throws",
"i2n/N.cast.read@isl.nope#nullproto": "throws",
"clo-n2i/N.callback#xy": "forin=unsupported",
"clo-n2i/N.callback#order": "forin=unsupported",
"clo-n2i/N.callback#empty": "forin=unsupported",
@@ -2161,9 +2021,7 @@
"clo-i2n/U.forin#nullproto": "unsupported",
"clo-i2n/U.inst#nullproto": "wrong"
},
"rec-nested.control.-": {
"W.result.mapkey": "wrong"
},
"rec-nested.control.-": {},
"rec-nested.i": {
"i2n/U.forin": "unsupported",
"clo-i2n/U.forin": "unsupported"
@@ -2225,9 +2083,7 @@
"clo-i2n/U.forin#undef": "unsupported",
"clo-i2n/U.forin#full": "unsupported"
},
"rec.control.-": {
"W.result.mapkey": "wrong"
},
"rec.control.-": {},
"rec.i": {
"i2n/U.forin": "unsupported",
"clo-i2n/U.forin": "unsupported"
@@ -2248,7 +2104,6 @@
"regexp.control.-": {
"T.json": "refused:SC1090",
"U.json": "unsupported",
"U.forin": "unsupported",
"U.clone": "unsupported"
},
"regexp.p": {
@@ -2319,7 +2174,6 @@
},
"sab.control.-": {
"T.clone": "throws",
"U.forin": "unsupported",
"U.clone": "throws"
},
"sab.p": {
@@ -2367,7 +2221,6 @@
"set.control.-": {
"N.read.json": "refused:SC1090",
"T.json": "refused:SC1090",
"U.forin": "unsupported",
"S.widen": "refused:SC1090",
"S.result": "refused:SC1090",
"N.cast.read.json": "refused:SC1090",
@@ -2406,7 +2259,6 @@
"n2i2n/N.is": "refused:SC8010",
"n2i2n/N.mapkey": "refused:SC8010",
"n2i2n/N.indexOf": "refused:SC8010",
"n2i2n/N.read.size": "throws",
"n2i2n/N.read.isSet": "refused:SC8010",
"n2i2n/N.read.json": "refused:SC8010",
"n2i2n/U.typeof": "refused:SC8010",
@@ -2419,7 +2271,6 @@
"n2i2n/U.inst": "refused:SC8010",
"n2i2n/U.clone": "refused:SC8010",
"n2i2n/P.read@back.json": "refused:SC1090",
"n2i2n/N.read@isl.size": "throws",
"n2i2n/N.read@isl.isSet": "refused:SC8010",
"n2i2n/N.read@isl.json": "refused:SC8010",
"clo-n2i/cb.json": "refused:SC1090",
@@ -2440,7 +2291,6 @@
"n2i/P.read@isl.json": "refused:SC1090",
"i2n/U.forin": "unsupported",
"i2n/N.cast": "exit",
"n2i2n/U.forin": "unsupported",
"clo-n2i/N.callback": "forin=unsupported",
"clo-i2n/U.forin": "unsupported"
},
@@ -2755,23 +2605,19 @@
"u8.p": {},
"u8.u": {},
"u8.w": {},
"undef.control.-": {
"T.json": "refused:SC1090"
},
"undef.control.-": {},
"undef.p": {
"i2n/T.json": "refused:SC1090",
"n2i2n/N.indexOf": "refused:SC2003"
},
"undef.u": {},
"undef.w": {
"i2n/T.json": "refused:SC1090",
"n2i2n/N.indexOf": "refused:SC2003"
},
"url.control.-": {
"T.typeof": "refused:SC1090",
"T.clone": "message",
"U.tag": "wrong",
"U.forin": "unsupported",
"U.forin": "wrong",
"U.clone": "message"
},
"url.p": {
@@ -2856,7 +2702,6 @@
"T.clone": "message",
"U.str": "wrong",
"U.json": "unsupported",
"U.forin": "unsupported",
"U.clone": "message"
},
"weakmap.p": {
@@ -2889,4 +2734,3 @@
"clo-i2n/I.taker": "throws"
}
}
+6 -1
View File
@@ -659,7 +659,12 @@ inspectTlsTest("M6: util.inspect circular-reference state is thread-local", () =
"-ffunction-sections",
"-fdata-sections",
"-Wno-comment",
...(sanitize ? ["-fsanitize=address"] : []),
// ASan registers every global, and a registered global roots its section:
// with that metadata the GC keeps scr_inspect.c's unused renderers and
// their deliberately unresolved runtime references. The probe reads the
// thread-local inspect state, not globals, so the sanitized build keeps
// stack and heap instrumentation and drops only global instrumentation.
...(sanitize ? ["-fsanitize=address", "-mllvm", "-asan-globals=0"] : []),
"-I",
join(repoRoot, "packages/runtime/src"),
join(threadFixtureDir, "probe_inspect.c"),
+1 -1
View File
@@ -120,7 +120,7 @@ function requiresIcu(file: string): boolean {
* does not finish on macOS (it aborts while exiting), so there is no
* reference output for the LLVM-built program to match. */
function skipsDarwin(file: string): boolean {
return directiveHead(file).some((l) => /^\/\/ @skip-darwin\s*$/.test(l));
return directiveHead(file).some((l) => /^\/\/ @skip-darwin\b/.test(l));
}
async function runBinary(
@@ -0,0 +1,80 @@
/* The build's @types/node materialization (scripts/materialize-node-types.mjs):
* a pnpm install can leave index.d.ts linked to the content-addressable
* store, and tsc-ts then resolves the declaration's /// <reference path>
* entries beside the store copy, which has no such siblings. The build
* materializes that one file first. */
import {
linkSync,
lstatSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, test } from "vitest";
import { materializeNodeTypes } from "../../scripts/materialize-node-types.mjs";
const directories: string[] = [];
function fixture(): { root: string; packageDir: string; storeFile: string; index: string } {
const root = mkdtempSync(join(tmpdir(), "scriptc-node-types-"));
directories.push(root);
const packageDir = join(root, "node_modules", "@types", "node");
mkdirSync(packageDir, { recursive: true });
writeFileSync(join(packageDir, "sibling.d.ts"), "export {};\n");
const storeFile = join(root, "store-file");
writeFileSync(storeFile, '/// <reference path="sibling.d.ts" />\n');
return { root, packageDir, storeFile, index: join(packageDir, "index.d.ts") };
}
afterEach(() => {
for (const directory of directories.splice(0))
rmSync(directory, { recursive: true, force: true });
});
describe("materializeNodeTypes", () => {
test("breaks a hardlink to the store so the package's siblings resolve", () => {
const { root, storeFile, index } = fixture();
linkSync(storeFile, index);
expect(lstatSync(index).nlink).toBe(2);
expect(materializeNodeTypes(root)).toBe(index);
const stat = lstatSync(index);
expect(stat.isSymbolicLink()).toBe(false);
expect(stat.nlink).toBe(1);
expect(readFileSync(index)).toEqual(readFileSync(storeFile));
});
test("breaks a symlink to the store", (context) => {
const { root, storeFile, index } = fixture();
try {
symlinkSync(storeFile, index);
} catch {
context.skip(); // unprivileged Windows cannot create file symlinks
return;
}
expect(materializeNodeTypes(root)).toBe(index);
const stat = lstatSync(index);
expect(stat.isSymbolicLink()).toBe(false);
expect(stat.nlink).toBe(1);
expect(readFileSync(index)).toEqual(readFileSync(storeFile));
});
test("replaces a regular file with an equivalent copy", () => {
const { root, index } = fixture();
writeFileSync(index, "export {};\n");
expect(materializeNodeTypes(root)).toBe(index);
expect(readFileSync(index, "utf8")).toBe("export {};\n");
});
test("answers null when no Node type package is installed", () => {
const { root } = fixture();
rmSync(join(root, "node_modules"), { recursive: true, force: true });
expect(materializeNodeTypes(root)).toBeNull();
});
});
@@ -73,7 +73,7 @@ test("an island value typed by a call signature keeps its origin natively", asyn
sanitize ? "1" : "0",
profile,
],
{ cwd: root, timeout: 1_800_000, maxBuffer: 16 * 1024 * 1024 },
{ cwd: root, timeout: 2_700_000, maxBuffer: 16 * 1024 * 1024 },
);
expect(stderr).toBe("");
const built = JSON.parse(stdout) as {
@@ -97,4 +97,4 @@ test("an island value typed by a call signature keeps its origin natively", asyn
} finally {
rmSync(directory, { recursive: true, force: true });
}
}, 1_800_000);
}, 3_000_000);
+1
View File
@@ -5,6 +5,7 @@
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2023"],
"types": ["node"],
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,