@amritk/nish-x86_64-linux 0.36.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/INSTALL.md +92 -71
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +75 -14
  4. package/package.json +1 -1
  5. package/runtime/async.d.mts +2 -0
  6. package/runtime/async.mjs +7 -0
  7. package/runtime/core/arrays.d.ts +4 -0
  8. package/runtime/core/arrays.mjs +33 -0
  9. package/runtime/nish.d.ts +1045 -512
  10. package/runtime/nish.h +53 -6
  11. package/runtime/page.d.ts +53 -0
  12. package/runtime/page.mjs +146 -0
  13. package/runtime/runtime-async.c +740 -0
  14. package/runtime/runtime-cross.c +2 -1
  15. package/runtime/runtime-region.c +85 -7
  16. package/runtime/runtime-text.c +1068 -0
  17. package/runtime/runtime-wasm.c +65 -9
  18. package/runtime/runtime.c +50 -961
  19. package/runtime/vite.mjs +48 -11
  20. package/scripts/build.sh +231 -31
  21. package/std/LICENSE-fdlibm +8 -0
  22. package/std/README.md +109 -82
  23. package/std/array.ts +266 -0
  24. package/std/bytes.ts +23 -19
  25. package/std/compress/checksum.ts +1 -1
  26. package/std/crypto/aes.ts +48 -43
  27. package/std/crypto/base64url.ts +7 -5
  28. package/std/crypto/bcrypt-batch.ts +13 -13
  29. package/std/crypto/bcrypt.ts +33 -27
  30. package/std/crypto/chacha20poly1305.ts +16 -14
  31. package/std/crypto/ed25519.ts +19 -16
  32. package/std/crypto/hmac.ts +7 -6
  33. package/std/crypto/jwt.ts +23 -20
  34. package/std/crypto/p256.ts +63 -56
  35. package/std/crypto/p384.ts +23 -20
  36. package/std/crypto/pki.ts +18 -15
  37. package/std/crypto/rsa.ts +23 -19
  38. package/std/crypto/x25519.ts +11 -10
  39. package/std/crypto/x509.ts +69 -62
  40. package/std/host/ring.ts +124 -0
  41. package/std/host/text.ts +86 -0
  42. package/std/json-equal.ts +12 -11
  43. package/std/json-number.ts +12 -12
  44. package/std/json-tokenizer.ts +26 -22
  45. package/std/json-typed.ts +92 -78
  46. package/std/json-value.ts +38 -33
  47. package/std/json.ts +32 -28
  48. package/std/math.ts +743 -41
  49. package/std/net/dns-resolver.ts +46 -6
  50. package/std/net/dns.ts +50 -13
  51. package/std/net/fetch.ts +1744 -295
  52. package/std/net/handler.ts +30 -0
  53. package/std/net/hpack.ts +29 -26
  54. package/std/net/http-compress.ts +42 -28
  55. package/std/net/http-fields.ts +19 -4
  56. package/std/net/http1-client-codec.ts +29 -25
  57. package/std/net/http1-codec.ts +62 -91
  58. package/std/net/http1-server.ts +79 -57
  59. package/std/net/http2-frame.ts +17 -16
  60. package/std/net/http2-tls.ts +17 -15
  61. package/std/net/http2.ts +67 -54
  62. package/std/net/http3-frame.ts +11 -10
  63. package/std/net/http3-server.ts +36 -35
  64. package/std/net/http3.ts +70 -58
  65. package/std/net/postgres-async.ts +1005 -0
  66. package/std/net/postgres.ts +185 -164
  67. package/std/net/prefork.ts +38 -34
  68. package/std/net/qpack.ts +15 -14
  69. package/std/net/quic-conn-ack.ts +1 -0
  70. package/std/net/quic-conn-cid.ts +11 -0
  71. package/std/net/quic-conn-params.ts +41 -14
  72. package/std/net/quic-datagram.ts +7 -0
  73. package/std/net/quic-frame.ts +48 -12
  74. package/std/net/quic-listener.ts +61 -44
  75. package/std/net/quic-packet.ts +71 -52
  76. package/std/net/quic-recovery.ts +59 -21
  77. package/std/net/quic-stream.ts +83 -55
  78. package/std/net/quic.ts +204 -152
  79. package/std/net/serve.ts +763 -0
  80. package/std/net/tls/client.ts +1 -0
  81. package/std/net/tls/codec.ts +81 -12
  82. package/std/net/tls/record-client.ts +30 -18
  83. package/std/net/tls/record-server.ts +74 -46
  84. package/std/net/tls/record.ts +33 -24
  85. package/std/net/tls/ticket.ts +2 -0
  86. package/std/net/tls/verify.ts +8 -7
  87. package/std/net/tls-tcp.ts +58 -50
  88. package/std/net/tls.ts +55 -43
  89. package/std/net/url.ts +12 -9
  90. package/std/net/websocket.ts +23 -19
  91. package/std/net/webtransport.ts +24 -18
  92. package/std/random.ts +8 -6
  93. package/std/regex.ts +70 -59
  94. package/std/sync/ring.ts +24 -21
  95. package/std/sync/shm.ts +9 -7
  96. package/std/term-io.ts +17 -14
  97. package/std/term-probe.ts +11 -10
  98. package/std/term-rate.ts +71 -61
  99. package/std/term.ts +73 -59
  100. package/std/text.ts +242 -15
  101. package/std/threads.ts +19 -15
  102. package/std/yaml-json.ts +17 -15
  103. package/std/yaml-write.ts +21 -14
@@ -0,0 +1,740 @@
1
+ /* Nish runtime, the async half: the executor that resumes `async` tasks when
2
+ * the kernel says a file descriptor is ready or a timer is due
3
+ * (docs/wp49-async-server.md, "Stage 5, part 1"; security record
4
+ * docs/security/async.md).
5
+ *
6
+ * A translation unit of its own, paired with runtime.c in scripts/build.sh's
7
+ * `halves` and src/run-cache.ts's `runtimeUnits()` like the others, and linked
8
+ * only into a program whose IR names `@nish_async_`: one with no `async`
9
+ * function links none of it. The wasm profiles refuse `async` (NL2652), so
10
+ * under wasm this file is empty.
11
+ *
12
+ * **A task is a node.** The compiler sizes each spawned function's frame and
13
+ * hands the size to `nish_async_spawn`, which answers a node: this header,
14
+ * then the frame at `NISH_ASYNC_HEADER` bytes. Nodes come from one slab per
15
+ * task kind: a free list, refilled by chunks of nodes whose count doubles, so
16
+ * a program's slab grows to the most tasks it ever had in flight and is then
17
+ * reused; a node is never given back to `malloc`. The compiled driver
18
+ * (`@nish.async.run`, emitted by src/emit-async.ts) resumes a node through a
19
+ * switch over the kinds, not a function pointer, so nothing here calls into
20
+ * the program.
21
+ *
22
+ * **Every node has a permanent index and a generation.** The index is its
23
+ * place in the task table, given once; the generation moves on each time the
24
+ * node is reused. A wait records the (index, generation) of the task that
25
+ * made it, so a completion that arrives after its task finished -- an orphan
26
+ * wait, or a node already reused by another task -- is dropped and counted
27
+ * (`nish_async_stat(1)`) rather than resuming the wrong task. Index 0 is
28
+ * `main`'s, a static node with kind -1 that is never reused.
29
+ *
30
+ * **A wait is a token.** `nish_async_wait_fd` and `nish_async_sleep` answer
31
+ * `(generation << 32) | (slot + 1)` for a slot of the wait table, and the
32
+ * caller polls it with `nish_async_poll` (-1 pending, else the answer, which
33
+ * frees the slot). A wait that can be answered at once -- a bad descriptor,
34
+ * a regular file, a negative sleep -- is made already fired, so the poll in
35
+ * the same resume reads it and the task never suspends.
36
+ *
37
+ * **The loop.** `nish_async_next` answers the next task to resume: the head
38
+ * of the ready queue, or, when the queue is empty and something waits, the
39
+ * first task a blocking kernel wait wakes. Each wait reports the kernel's
40
+ * ready descriptors in the order the kernel listed them, then the timers that
41
+ * expired, earliest deadline first (a binary heap, ties broken by the order
42
+ * they were made). It answers null when nothing is ready and nothing waits,
43
+ * which ends the loop.
44
+ *
45
+ * **A descriptor wait owns a duplicate.** The descriptor is duplicated
46
+ * (`F_DUPFD_CLOEXEC`) and the duplicate registered one-shot, so two tasks can
47
+ * wait on one descriptor, and a program that closes the descriptor while a
48
+ * task waits on it cannot have the registration answer for whatever the
49
+ * number is reused for. The duplicate is closed when the wait fires.
50
+ *
51
+ * **Regions.** Each spawned task owns a region (runtime-region.c), entered
52
+ * whenever the task runs and freed when it finishes, so whatever a task
53
+ * allocates is given back when it ends. The driver enters and leaves around
54
+ * each resume (`nish_async_enter`, `nish_async_leave`).
55
+ *
56
+ * **Cancellation.** `nish_async_cancel` marks a task cancelled
57
+ * (`NISH_TASK_CANCELLED`, a bit beside the queued bit) and fails each wait it
58
+ * has pending, so every parked await answers false and the task is queued; a
59
+ * wait the task makes afterwards is made already failed. Nothing is unwound:
60
+ * the task runs on from each failed await to its end, its `using` bindings
61
+ * dispose as they do on any return, and `nish_async_done` frees its region.
62
+ * `nish_async_cancel_after` arms a deadline that cancels a task when it
63
+ * passes, a timer in the heap that `done` takes out, and
64
+ * `nish_async_wait_fd_within` a descriptor wait that fails when its own
65
+ * deadline passes first. A timer leaves the heap the moment its wait is
66
+ * answered either way (`heap_at`), so the heap holds only live timers.
67
+ *
68
+ * The executor runs on the thread that runs `main`; its state is not shared
69
+ * with the threads of `nish/threads`. */
70
+
71
+ #if defined(__wasi__) || defined(__wasm__)
72
+ typedef int nish_async_unused_in_wasm;
73
+ #else
74
+ #if defined(__linux__)
75
+ /* glibc declares `clock_gettime`, `nanosleep` and `F_DUPFD_CLOEXEC` under a feature macro. */
76
+ #define _GNU_SOURCE
77
+ #else
78
+ #define _DARWIN_C_SOURCE
79
+ #endif
80
+
81
+ #include <errno.h>
82
+ #include <fcntl.h>
83
+ #include <stddef.h>
84
+ #include <stdint.h>
85
+ #include <stdlib.h>
86
+ #include <string.h>
87
+ #include <time.h>
88
+ #include <unistd.h>
89
+ #if defined(__linux__)
90
+ #include <sys/epoll.h>
91
+ #else
92
+ #include <sys/event.h>
93
+ #include <sys/stat.h>
94
+ #include <sys/time.h>
95
+ #include <sys/types.h>
96
+ #endif
97
+
98
+ #include "nish.h"
99
+
100
+ #define NISH_COLD __attribute__((noreturn, cold, noinline))
101
+
102
+ /* The bytes ahead of a frame in a node; src/emit-async.ts's NODE_HEADER. */
103
+ #define NISH_ASYNC_HEADER 32
104
+
105
+ typedef struct nish_task {
106
+ struct nish_task *next; /* the ready queue's link, or the free list's */
107
+ int32_t kind; /* the spawned function's kind; -1 for `main` */
108
+ uint32_t gen; /* moves on each time the node is reused */
109
+ uint64_t region; /* the task's region; 0 for `main` and a free node */
110
+ uint32_t index; /* the node's place in the task table, for ever */
111
+ uint32_t flags; /* NISH_TASK_QUEUED, NISH_TASK_CANCELLED */
112
+ } nish_task;
113
+
114
+ /* On the ready queue, so it is queued once. */
115
+ #define NISH_TASK_QUEUED 1u
116
+ /* Cancelled: each wait it has, or makes, answers false at once. */
117
+ #define NISH_TASK_CANCELLED 2u
118
+
119
+ _Static_assert(sizeof(nish_task) <= NISH_ASYNC_HEADER, "a node's header holds a task");
120
+ _Static_assert(offsetof(nish_task, kind) == 8, "the driver reads the kind at byte 8");
121
+
122
+ typedef struct nish_slab {
123
+ nish_task *free;
124
+ uint64_t stride; /* header and frame, rounded to 16 */
125
+ uint64_t chunk; /* nodes in the next chunk */
126
+ } nish_slab;
127
+
128
+ enum { NISH_WAIT_FREE, NISH_WAIT_PENDING, NISH_WAIT_FIRED };
129
+
130
+ typedef struct nish_wait {
131
+ uint32_t gen; /* moves on each time the slot is freed */
132
+ uint32_t task; /* the waiting task's index ... */
133
+ uint32_t task_gen; /* ... and its generation when it waited */
134
+ int32_t state;
135
+ int32_t answer;
136
+ int32_t fd; /* the registered duplicate, or -1 for a timer */
137
+ int64_t deadline; /* a timer's, in CLOCK_MONOTONIC nanoseconds */
138
+ uint64_t seq; /* a timer's place among equal deadlines */
139
+ int32_t heap_at; /* its place in the timer heap, or -1 */
140
+ int32_t cancels; /* a task's deadline: firing cancels the task, waking nothing */
141
+ } nish_wait;
142
+
143
+ static nish_task nish_async_main_task = {NULL, -1, 1, 0, 0, 0};
144
+ static nish_task *nish_async_current = &nish_async_main_task;
145
+
146
+ static nish_task **nish_async_tasks;
147
+ static uint32_t nish_async_task_count;
148
+ static uint32_t nish_async_task_cap;
149
+
150
+ static nish_slab *nish_async_slabs;
151
+ static uint32_t nish_async_slab_count;
152
+
153
+ static nish_task *nish_async_head;
154
+ static nish_task *nish_async_tail;
155
+
156
+ static nish_wait *nish_async_waits;
157
+ static uint32_t nish_async_wait_count;
158
+ static uint32_t nish_async_wait_cap;
159
+ static uint32_t *nish_async_wait_free;
160
+ static uint32_t nish_async_wait_free_len;
161
+
162
+ static uint32_t *nish_async_heap;
163
+ static uint32_t nish_async_heap_len;
164
+ static uint32_t nish_async_heap_cap;
165
+ static uint64_t nish_async_seq;
166
+
167
+ /* Per task index, the slot + 1 of its armed deadline, or 0. */
168
+ static uint32_t *nish_async_deadlines;
169
+ static uint32_t nish_async_deadline_cap;
170
+
171
+ static int nish_async_poller = -1;
172
+ static uint32_t nish_async_fd_waits;
173
+
174
+ static int32_t nish_async_allocated;
175
+ static int32_t nish_async_late;
176
+ static int32_t nish_async_live; /* spawned tasks not yet done, each holding a region */
177
+
178
+ enum { NISH_ASYNC_OOM, NISH_ASYNC_POLLER, NISH_ASYNC_TOO_MANY, NISH_ASYNC_WAIT };
179
+ #define NISH_ASYNC_MSG(text) { sizeof text - 1, text }
180
+ static const struct { uint64_t len; char data[64]; } nish_async_messages[] = {
181
+ NISH_ASYNC_MSG("nish: out of memory"),
182
+ NISH_ASYNC_MSG("nish: the async event loop could not be made"),
183
+ NISH_ASYNC_MSG("nish: more than 4294967294 async tasks or waits"),
184
+ NISH_ASYNC_MSG("nish: the async event loop could not wait"),
185
+ };
186
+
187
+ static NISH_COLD void nish_async_die(int why) {
188
+ nish_panic((const nish_str *)&nish_async_messages[why]);
189
+ }
190
+
191
+ /* Grow `*items` (of `size`-byte entries, `*cap` of them) to hold one more. */
192
+ static void *nish_async_grow(void *items, uint32_t *cap, size_t size) {
193
+ if (*cap >= UINT32_MAX / 2) nish_async_die(NISH_ASYNC_TOO_MANY);
194
+ uint32_t want = *cap ? *cap * 2 : 16;
195
+ void *grown = realloc(items, (size_t)want * size);
196
+ if (!grown) nish_async_die(NISH_ASYNC_OOM);
197
+ *cap = want;
198
+ return grown;
199
+ }
200
+
201
+ static void nish_async_table_add(nish_task *t) {
202
+ if (!nish_async_tasks) {
203
+ nish_async_tasks = nish_async_grow(NULL, &nish_async_task_cap, sizeof *nish_async_tasks);
204
+ nish_async_tasks[0] = &nish_async_main_task;
205
+ nish_async_task_count = 1;
206
+ }
207
+ if (nish_async_task_count == nish_async_task_cap)
208
+ nish_async_tasks = nish_async_grow(nish_async_tasks, &nish_async_task_cap, sizeof *nish_async_tasks);
209
+ while (nish_async_task_count >= nish_async_deadline_cap) {
210
+ uint32_t had = nish_async_deadline_cap;
211
+ nish_async_deadlines = nish_async_grow(nish_async_deadlines, &nish_async_deadline_cap, sizeof *nish_async_deadlines);
212
+ memset(nish_async_deadlines + had, 0, (size_t)(nish_async_deadline_cap - had) * sizeof *nish_async_deadlines);
213
+ }
214
+ t->index = nish_async_task_count;
215
+ nish_async_tasks[nish_async_task_count++] = t;
216
+ }
217
+
218
+ static int64_t nish_async_now(void) {
219
+ struct timespec ts;
220
+ clock_gettime(CLOCK_MONOTONIC, &ts);
221
+ return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
222
+ }
223
+
224
+ static void nish_async_enqueue(nish_task *t) {
225
+ if (t->flags & NISH_TASK_QUEUED) return;
226
+ t->flags |= NISH_TASK_QUEUED;
227
+ t->next = NULL;
228
+ if (nish_async_tail) nish_async_tail->next = t;
229
+ else nish_async_head = t;
230
+ nish_async_tail = t;
231
+ }
232
+
233
+ /* ---- Tasks --------------------------------------------------------------- */
234
+
235
+ void *nish_async_spawn(int32_t kind, uint64_t bytes) {
236
+ if (kind < 0) nish_async_die(NISH_ASYNC_TOO_MANY);
237
+ if ((uint32_t)kind >= nish_async_slab_count) {
238
+ uint32_t want = (uint32_t)kind + 1;
239
+ nish_slab *grown = realloc(nish_async_slabs, (size_t)want * sizeof *grown);
240
+ if (!grown) nish_async_die(NISH_ASYNC_OOM);
241
+ memset(grown + nish_async_slab_count, 0, (size_t)(want - nish_async_slab_count) * sizeof *grown);
242
+ nish_async_slabs = grown;
243
+ nish_async_slab_count = want;
244
+ }
245
+ nish_slab *slab = &nish_async_slabs[kind];
246
+ if (!slab->free) {
247
+ if (!slab->stride) {
248
+ slab->stride = (NISH_ASYNC_HEADER + bytes + 15) & ~(uint64_t)15;
249
+ slab->chunk = 4;
250
+ }
251
+ uint64_t count = slab->chunk;
252
+ char *chunk = malloc(count * slab->stride);
253
+ if (!chunk) nish_async_die(NISH_ASYNC_OOM);
254
+ slab->chunk = count * 2;
255
+ for (uint64_t i = count; i-- > 0;) {
256
+ nish_task *t = (nish_task *)(chunk + i * slab->stride);
257
+ t->gen = 1;
258
+ t->region = 0;
259
+ t->flags = 0;
260
+ nish_async_table_add(t);
261
+ t->next = slab->free;
262
+ slab->free = t;
263
+ nish_async_allocated++;
264
+ }
265
+ }
266
+ nish_task *t = slab->free;
267
+ slab->free = t->next;
268
+ t->next = NULL;
269
+ t->kind = kind;
270
+ t->flags = 0;
271
+ t->region = nish_region_new();
272
+ nish_async_live++;
273
+ return t;
274
+ }
275
+
276
+ /* Make `node` the running task and enter its region; answers the task that was running. */
277
+ void *nish_async_enter(void *node) {
278
+ nish_task *t = node;
279
+ nish_task *prev = nish_async_current;
280
+ nish_async_current = t;
281
+ if (t->region) nish_region_enter(t->region);
282
+ return prev;
283
+ }
284
+
285
+ /* Leave `node`'s region and make `prev`, what `nish_async_enter` answered, the running task again. */
286
+ void nish_async_leave(void *node, void *prev) {
287
+ nish_task *t = node;
288
+ if (t->region) nish_region_leave(t->region, NULL);
289
+ nish_async_current = prev;
290
+ }
291
+
292
+ static void nish_async_disarm(nish_task *t);
293
+
294
+ /* A task finished: take out its deadline, free its region and put its node
295
+ back, a generation on. */
296
+ void nish_async_done(void *node) {
297
+ nish_task *t = node;
298
+ if (t->kind < 0) return;
299
+ nish_async_disarm(t);
300
+ /* A task that cancelled itself while awaitAll ran its calls was queued by
301
+ its own failed waits and may finish still on the ready queue: take it
302
+ off, so the queue never holds a node on the free list. */
303
+ if (t->flags & NISH_TASK_QUEUED) {
304
+ nish_task **at = &nish_async_head;
305
+ nish_task *before = NULL;
306
+ while (*at && *at != t) {
307
+ before = *at;
308
+ at = &(*at)->next;
309
+ }
310
+ if (*at) {
311
+ *at = t->next;
312
+ if (nish_async_tail == t) nish_async_tail = before;
313
+ }
314
+ t->flags &= ~NISH_TASK_QUEUED;
315
+ }
316
+ nish_region_free(t->region);
317
+ t->region = 0;
318
+ nish_async_live--;
319
+ t->gen = t->gen == UINT32_MAX ? 1 : t->gen + 1;
320
+ nish_slab *slab = &nish_async_slabs[t->kind];
321
+ t->next = slab->free;
322
+ slab->free = t;
323
+ }
324
+
325
+ /* ---- Waits --------------------------------------------------------------- */
326
+
327
+ static uint64_t nish_async_token(uint32_t slot) {
328
+ return ((uint64_t)nish_async_waits[slot].gen << 32) | ((uint64_t)slot + 1);
329
+ }
330
+
331
+ /* The slot `token` names, or -1 for one that is not a live wait. */
332
+ static int64_t nish_async_slot_of(uint64_t token) {
333
+ uint64_t low = token & 0xffffffffu;
334
+ if (low == 0 || low > nish_async_wait_count) return -1;
335
+ uint32_t slot = (uint32_t)(low - 1);
336
+ nish_wait *w = &nish_async_waits[slot];
337
+ if (w->gen != (uint32_t)(token >> 32) || w->state == NISH_WAIT_FREE) return -1;
338
+ return slot;
339
+ }
340
+
341
+ static uint32_t nish_async_wait_new(void) {
342
+ uint32_t slot;
343
+ if (nish_async_wait_free_len) {
344
+ slot = nish_async_wait_free[--nish_async_wait_free_len];
345
+ } else {
346
+ if (nish_async_wait_count == nish_async_wait_cap) {
347
+ uint32_t cap = nish_async_wait_cap;
348
+ nish_async_waits = nish_async_grow(nish_async_waits, &nish_async_wait_cap, sizeof *nish_async_waits);
349
+ nish_async_wait_free = nish_async_grow(nish_async_wait_free, &cap, sizeof *nish_async_wait_free);
350
+ }
351
+ slot = nish_async_wait_count++;
352
+ nish_async_waits[slot].gen = 1;
353
+ }
354
+ nish_wait *w = &nish_async_waits[slot];
355
+ w->task = nish_async_current->index;
356
+ w->task_gen = nish_async_current->gen;
357
+ w->state = NISH_WAIT_PENDING;
358
+ w->answer = 0;
359
+ w->fd = -1;
360
+ w->deadline = 0;
361
+ w->seq = 0;
362
+ w->heap_at = -1;
363
+ w->cancels = 0;
364
+ return slot;
365
+ }
366
+
367
+ static void nish_async_wait_free_slot(uint32_t slot) {
368
+ nish_wait *w = &nish_async_waits[slot];
369
+ w->state = NISH_WAIT_FREE;
370
+ w->gen = w->gen == UINT32_MAX ? 1 : w->gen + 1;
371
+ nish_async_wait_free[nish_async_wait_free_len++] = slot;
372
+ }
373
+
374
+ /* A wait answered before anyone polled it: the poll in the same resume reads it. */
375
+ static uint64_t nish_async_fired_now(uint32_t slot, int32_t answer) {
376
+ nish_async_waits[slot].state = NISH_WAIT_FIRED;
377
+ nish_async_waits[slot].answer = answer;
378
+ return nish_async_token(slot);
379
+ }
380
+
381
+ /* ---- The timer heap ---------------------------------------------------- */
382
+
383
+ static int nish_async_timer_before(uint32_t a, uint32_t b) {
384
+ nish_wait *x = &nish_async_waits[a];
385
+ nish_wait *y = &nish_async_waits[b];
386
+ return x->deadline < y->deadline || (x->deadline == y->deadline && x->seq < y->seq);
387
+ }
388
+
389
+ static void nish_async_heap_set(uint32_t at, uint32_t slot) {
390
+ nish_async_heap[at] = slot;
391
+ nish_async_waits[slot].heap_at = (int32_t)at;
392
+ }
393
+
394
+ static void nish_async_heap_up(uint32_t at) {
395
+ uint32_t slot = nish_async_heap[at];
396
+ while (at > 0) {
397
+ uint32_t up = (at - 1) / 2;
398
+ if (!nish_async_timer_before(slot, nish_async_heap[up])) break;
399
+ nish_async_heap_set(at, nish_async_heap[up]);
400
+ at = up;
401
+ }
402
+ nish_async_heap_set(at, slot);
403
+ }
404
+
405
+ static void nish_async_heap_down(uint32_t at) {
406
+ uint32_t slot = nish_async_heap[at];
407
+ for (;;) {
408
+ uint32_t kid = at * 2 + 1;
409
+ if (kid >= nish_async_heap_len) break;
410
+ if (kid + 1 < nish_async_heap_len && nish_async_timer_before(nish_async_heap[kid + 1], nish_async_heap[kid]))
411
+ kid++;
412
+ if (!nish_async_timer_before(nish_async_heap[kid], slot)) break;
413
+ nish_async_heap_set(at, nish_async_heap[kid]);
414
+ at = kid;
415
+ }
416
+ nish_async_heap_set(at, slot);
417
+ }
418
+
419
+ static void nish_async_heap_push(uint32_t slot) {
420
+ if (nish_async_heap_len == nish_async_heap_cap)
421
+ nish_async_heap = nish_async_grow(nish_async_heap, &nish_async_heap_cap, sizeof *nish_async_heap);
422
+ nish_async_heap_set(nish_async_heap_len++, slot);
423
+ nish_async_heap_up(nish_async_heap_len - 1);
424
+ }
425
+
426
+ /* Take the timer of `slot` out of the heap, wherever it is. */
427
+ static void nish_async_heap_remove(uint32_t slot) {
428
+ int32_t at = nish_async_waits[slot].heap_at;
429
+ if (at < 0) return;
430
+ nish_async_waits[slot].heap_at = -1;
431
+ uint32_t last = nish_async_heap[--nish_async_heap_len];
432
+ if ((uint32_t)at == nish_async_heap_len) return;
433
+ nish_async_heap_set((uint32_t)at, last);
434
+ nish_async_heap_up((uint32_t)at);
435
+ nish_async_heap_down((uint32_t)nish_async_waits[last].heap_at);
436
+ }
437
+
438
+ /* ---- Answering a wait ---------------------------------------------------- */
439
+
440
+ static nish_task *nish_async_task_at(uint32_t index, uint32_t gen) {
441
+ nish_task *t = index == 0 ? &nish_async_main_task
442
+ : index < nish_async_task_count ? nish_async_tasks[index] : NULL;
443
+ return t && t->gen == gen ? t : NULL;
444
+ }
445
+
446
+ static void nish_async_cancel_task(nish_task *t);
447
+
448
+ /* The wait in `slot` completed with `answer`: queue its task, or drop it when
449
+ the task it was made for has finished. A task's deadline cancels the task
450
+ instead. */
451
+ static void nish_async_fire(uint32_t slot, int32_t answer) {
452
+ nish_wait *w = &nish_async_waits[slot];
453
+ if (w->state != NISH_WAIT_PENDING) return;
454
+ nish_async_heap_remove(slot);
455
+ if (w->fd >= 0) {
456
+ #if defined(__linux__)
457
+ epoll_ctl(nish_async_poller, EPOLL_CTL_DEL, w->fd, NULL);
458
+ #endif
459
+ close(w->fd);
460
+ w->fd = -1;
461
+ nish_async_fd_waits--;
462
+ }
463
+ w->state = NISH_WAIT_FIRED;
464
+ w->answer = answer;
465
+ nish_task *t = nish_async_task_at(w->task, w->task_gen);
466
+ if (w->cancels) {
467
+ if (nish_async_deadlines[w->task] == slot + 1) nish_async_deadlines[w->task] = 0;
468
+ nish_async_wait_free_slot(slot);
469
+ if (t) nish_async_cancel_task(t);
470
+ return;
471
+ }
472
+ if (!t) {
473
+ nish_async_late++;
474
+ nish_async_wait_free_slot(slot);
475
+ return;
476
+ }
477
+ nish_async_enqueue(t);
478
+ }
479
+
480
+ /* A timer came due: a sleep is over (true), a descriptor wait's deadline
481
+ passed first (false), a task's deadline cancels it. */
482
+ static void nish_async_expire(uint32_t slot) {
483
+ nish_async_fire(slot, nish_async_waits[slot].fd >= 0 ? 0 : 1);
484
+ }
485
+
486
+ /* ---- Cancellation -------------------------------------------------------- */
487
+
488
+ /* Mark `t` cancelled and fail each wait it has pending. */
489
+ static void nish_async_cancel_task(nish_task *t) {
490
+ if (t->flags & NISH_TASK_CANCELLED) return;
491
+ t->flags |= NISH_TASK_CANCELLED;
492
+ nish_async_disarm(t);
493
+ for (uint32_t slot = 0; slot < nish_async_wait_count; slot++) {
494
+ nish_wait *w = &nish_async_waits[slot];
495
+ if (w->state == NISH_WAIT_PENDING && !w->cancels && w->task == t->index && w->task_gen == t->gen)
496
+ nish_async_fire(slot, 0);
497
+ }
498
+ }
499
+
500
+ /* Take out `t`'s armed deadline, if it has one. */
501
+ static void nish_async_disarm(nish_task *t) {
502
+ if (!nish_async_deadlines || t->index >= nish_async_deadline_cap) return;
503
+ uint32_t armed = nish_async_deadlines[t->index];
504
+ if (!armed) return;
505
+ nish_async_deadlines[t->index] = 0;
506
+ nish_async_heap_remove(armed - 1);
507
+ nish_async_wait_free_slot(armed - 1);
508
+ }
509
+
510
+ /* The task `handle` names (`nish_async_task_id`), or null for one that has
511
+ finished, `main`, or no task. */
512
+ static nish_task *nish_async_task_of(int64_t handle) {
513
+ uint32_t index = (uint32_t)((uint64_t)handle & 0xffffffffu);
514
+ if (index == 0) return NULL;
515
+ return nish_async_task_at(index, (uint32_t)((uint64_t)handle >> 32));
516
+ }
517
+
518
+ /* The running task's handle: its generation, then its index; 0 for `main`. */
519
+ int64_t nish_async_task_id(void) {
520
+ nish_task *t = nish_async_current;
521
+ if (t == &nish_async_main_task) return 0;
522
+ return (int64_t)(((uint64_t)t->gen << 32) | t->index);
523
+ }
524
+
525
+ /* Cancel the task `handle` names: true when it is still running (a second
526
+ cancel too), false for one that has finished, or `main`. */
527
+ int32_t nish_async_cancel(int64_t handle) {
528
+ nish_task *t = nish_async_task_of(handle);
529
+ if (!t) return 0;
530
+ nish_async_cancel_task(t);
531
+ return 1;
532
+ }
533
+
534
+ /* Whether the running task is cancelled. */
535
+ int32_t nish_async_cancelled(void) {
536
+ return (nish_async_current->flags & NISH_TASK_CANCELLED) != 0;
537
+ }
538
+
539
+ /* Cancel the task `handle` names `ms` milliseconds from now, in place of any
540
+ deadline it had; a negative `ms` only takes the old one out. False for a
541
+ task that has finished, or `main`. */
542
+ int32_t nish_async_cancel_after(int64_t handle, int32_t ms) {
543
+ nish_task *t = nish_async_task_of(handle);
544
+ if (!t) return 0;
545
+ nish_async_disarm(t);
546
+ if (ms < 0 || (t->flags & NISH_TASK_CANCELLED)) return 1;
547
+ nish_task *running = nish_async_current;
548
+ nish_async_current = t;
549
+ uint32_t slot = nish_async_wait_new();
550
+ nish_async_current = running;
551
+ nish_wait *w = &nish_async_waits[slot];
552
+ w->cancels = 1;
553
+ w->deadline = nish_async_now() + (int64_t)ms * 1000000;
554
+ w->seq = nish_async_seq++;
555
+ nish_async_heap_push(slot);
556
+ nish_async_deadlines[t->index] = slot + 1;
557
+ return 1;
558
+ }
559
+
560
+ /* A wait for `fd` to be readable (`dir` 0) or writable (`dir` 1). */
561
+ uint64_t nish_async_wait_fd(int32_t fd, int32_t dir) {
562
+ uint32_t slot = nish_async_wait_new();
563
+ if (fd < 0 || (nish_async_current->flags & NISH_TASK_CANCELLED)) return nish_async_fired_now(slot, 0);
564
+ if (nish_async_poller < 0) {
565
+ #if defined(__linux__)
566
+ nish_async_poller = epoll_create1(EPOLL_CLOEXEC);
567
+ #else
568
+ nish_async_poller = kqueue();
569
+ if (nish_async_poller >= 0) fcntl(nish_async_poller, F_SETFD, FD_CLOEXEC);
570
+ #endif
571
+ if (nish_async_poller < 0) nish_async_die(NISH_ASYNC_POLLER);
572
+ }
573
+ int dup = fcntl(fd, F_DUPFD_CLOEXEC, 0);
574
+ if (dup < 0) return nish_async_fired_now(slot, 0);
575
+ #if !defined(__linux__)
576
+ /* kqueue accepts a regular file and reports it readable only while it has
577
+ bytes left, so one at its end would park the task for ever; epoll refuses
578
+ it below. A regular file never blocks: it is ready, on both kernels. */
579
+ struct stat st;
580
+ if (fstat(dup, &st) == 0 && S_ISREG(st.st_mode)) {
581
+ close(dup);
582
+ return nish_async_fired_now(slot, 1);
583
+ }
584
+ #endif
585
+ uint64_t token = nish_async_token(slot);
586
+ #if defined(__linux__)
587
+ struct epoll_event ev;
588
+ memset(&ev, 0, sizeof ev);
589
+ ev.events = (dir ? EPOLLOUT : EPOLLIN) | EPOLLONESHOT;
590
+ ev.data.u64 = token;
591
+ int rc = epoll_ctl(nish_async_poller, EPOLL_CTL_ADD, dup, &ev);
592
+ #else
593
+ struct kevent ev;
594
+ EV_SET(&ev, (uintptr_t)dup, dir ? EVFILT_WRITE : EVFILT_READ, EV_ADD | EV_ONESHOT, 0, 0,
595
+ (void *)(uintptr_t)token);
596
+ int rc = kevent(nish_async_poller, &ev, 1, NULL, 0, NULL);
597
+ #endif
598
+ if (rc < 0) {
599
+ /* epoll refuses a regular file (EPERM), which never blocks: it is ready. */
600
+ int ready = errno == EPERM;
601
+ close(dup);
602
+ return nish_async_fired_now(slot, ready);
603
+ }
604
+ nish_async_waits[slot].fd = dup;
605
+ nish_async_fd_waits++;
606
+ return token;
607
+ }
608
+
609
+ /* A descriptor wait that fails (answers false) when `ms` milliseconds pass
610
+ before `fd` is ready; a negative `ms` waits as long as it takes. */
611
+ uint64_t nish_async_wait_fd_within(int32_t fd, int32_t dir, int32_t ms) {
612
+ uint64_t token = nish_async_wait_fd(fd, dir);
613
+ uint32_t slot = (uint32_t)(token & 0xffffffffu) - 1;
614
+ nish_wait *w = &nish_async_waits[slot];
615
+ if (ms < 0 || w->state != NISH_WAIT_PENDING) return token;
616
+ w->deadline = nish_async_now() + (int64_t)ms * 1000000;
617
+ w->seq = nish_async_seq++;
618
+ nish_async_heap_push(slot);
619
+ return token;
620
+ }
621
+
622
+ /* A wait for `ms` milliseconds; a negative `ms`, or a cancelled task, answers false at once. */
623
+ uint64_t nish_async_sleep(int32_t ms) {
624
+ uint32_t slot = nish_async_wait_new();
625
+ if (ms < 0 || (nish_async_current->flags & NISH_TASK_CANCELLED)) return nish_async_fired_now(slot, 0);
626
+ nish_async_waits[slot].deadline = nish_async_now() + (int64_t)ms * 1000000;
627
+ nish_async_waits[slot].seq = nish_async_seq++;
628
+ nish_async_heap_push(slot);
629
+ return nish_async_token(slot);
630
+ }
631
+
632
+ /* -1 while the wait is pending; else its answer (1 ready, 0 failed), and the token is spent. */
633
+ int32_t nish_async_poll(uint64_t token) {
634
+ int64_t slot = nish_async_slot_of(token);
635
+ if (slot < 0) return 0;
636
+ nish_wait *w = &nish_async_waits[slot];
637
+ if (w->state == NISH_WAIT_PENDING) return -1;
638
+ int32_t answer = w->answer;
639
+ nish_async_wait_free_slot((uint32_t)slot);
640
+ return answer;
641
+ }
642
+
643
+ /* ---- The loop ------------------------------------------------------------ */
644
+
645
+ /* Block until a descriptor is ready or the first timer is due, then queue
646
+ what woke: the descriptors in the kernel's order, then the expired timers
647
+ by deadline. */
648
+ static void nish_async_block(void) {
649
+ int64_t wait_ns = -1;
650
+ if (nish_async_heap_len) {
651
+ wait_ns = nish_async_waits[nish_async_heap[0]].deadline - nish_async_now();
652
+ if (wait_ns < 0) wait_ns = 0;
653
+ }
654
+ if (nish_async_fd_waits) {
655
+ #if defined(__linux__)
656
+ struct epoll_event evs[64];
657
+ int timeout = -1;
658
+ if (wait_ns >= 0) {
659
+ int64_t ms = (wait_ns + 999999) / 1000000;
660
+ timeout = ms > 0x7fffffff ? 0x7fffffff : (int)ms;
661
+ }
662
+ int n = epoll_wait(nish_async_poller, evs, 64, timeout);
663
+ /* A signal ends the wait early and the caller waits again; any other
664
+ failure would recur on every call and spin, so it ends the program. */
665
+ if (n < 0 && errno != EINTR) nish_async_die(NISH_ASYNC_WAIT);
666
+ for (int i = 0; i < n; i++) {
667
+ int64_t slot = nish_async_slot_of(evs[i].data.u64);
668
+ if (slot < 0) {
669
+ nish_async_late++;
670
+ continue;
671
+ }
672
+ nish_async_fire((uint32_t)slot, 1);
673
+ }
674
+ #else
675
+ struct kevent evs[64];
676
+ struct timespec ts;
677
+ struct timespec *tp = NULL;
678
+ if (wait_ns >= 0) {
679
+ ts.tv_sec = wait_ns / 1000000000;
680
+ ts.tv_nsec = wait_ns % 1000000000;
681
+ tp = &ts;
682
+ }
683
+ int n = kevent(nish_async_poller, NULL, 0, evs, 64, tp);
684
+ if (n < 0 && errno != EINTR) nish_async_die(NISH_ASYNC_WAIT);
685
+ for (int i = 0; i < n; i++) {
686
+ int64_t slot = nish_async_slot_of((uint64_t)(uintptr_t)evs[i].udata);
687
+ if (slot < 0) {
688
+ nish_async_late++;
689
+ continue;
690
+ }
691
+ nish_async_fire((uint32_t)slot, 1);
692
+ }
693
+ #endif
694
+ } else if (wait_ns > 0) {
695
+ struct timespec ts;
696
+ ts.tv_sec = wait_ns / 1000000000;
697
+ ts.tv_nsec = wait_ns % 1000000000;
698
+ while (nanosleep(&ts, &ts) < 0 && errno == EINTR) {
699
+ }
700
+ }
701
+ int64_t now = nish_async_now();
702
+ while (nish_async_heap_len && nish_async_waits[nish_async_heap[0]].deadline <= now)
703
+ nish_async_expire(nish_async_heap[0]);
704
+ }
705
+
706
+ /* The next task to resume, waiting on the kernel for one when none is ready;
707
+ null when nothing is ready and nothing waits. */
708
+ void *nish_async_next(void) {
709
+ while (!nish_async_head) {
710
+ if (!nish_async_fd_waits && !nish_async_heap_len) return NULL;
711
+ nish_async_block();
712
+ }
713
+ nish_task *t = nish_async_head;
714
+ nish_async_head = t->next;
715
+ if (!nish_async_head) nish_async_tail = NULL;
716
+ t->next = NULL;
717
+ t->flags &= ~NISH_TASK_QUEUED;
718
+ return t;
719
+ }
720
+
721
+ /* A spawned task's string argument, copied into the arena that is current --
722
+ * the task's region, which the spawn has just entered -- so the task never
723
+ * reads memory its spawner's arena owns after the spawner has returned. */
724
+ void *nish_async_copy_str(const void *s) {
725
+ const nish_str *from = s;
726
+ return nish_str_new(from->data, from->len);
727
+ }
728
+
729
+ /* 0: nodes the slabs ever allocated; 1: completions dropped because their task
730
+ had finished; 2: spawned tasks not yet finished, each of which holds a region;
731
+ 3: timers in the heap (sleeps, bounded waits and armed deadlines). */
732
+ int32_t nish_async_stat(int32_t which) {
733
+ if (which == 0) return nish_async_allocated;
734
+ if (which == 1) return nish_async_late;
735
+ if (which == 2) return nish_async_live;
736
+ if (which == 3) return (int32_t)nish_async_heap_len;
737
+ return -1;
738
+ }
739
+
740
+ #endif