knitting 0.1.53 → 0.1.55

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 (135) hide show
  1. package/README.md +38 -27
  2. package/knitting.d.ts +797 -5
  3. package/knitting.js +9780 -5
  4. package/map.md +9 -12
  5. package/package.json +14 -13
  6. package/shared-memory.d.ts +155 -0
  7. package/shared-memory.js +1342 -0
  8. package/unsafe.d.ts +71 -1
  9. package/unsafe.js +878 -1
  10. package/utils.d.ts +31 -1
  11. package/utils.js +116 -1
  12. package/process-shared-buffer.d.ts +0 -1
  13. package/process-shared-buffer.js +0 -1
  14. package/src/api.d.ts +0 -69
  15. package/src/api.js +0 -555
  16. package/src/common/envelope.d.ts +0 -17
  17. package/src/common/envelope.js +0 -22
  18. package/src/common/module-url.d.ts +0 -1
  19. package/src/common/module-url.js +0 -24
  20. package/src/common/node-compat.d.ts +0 -20
  21. package/src/common/node-compat.js +0 -24
  22. package/src/common/path-canonical.d.ts +0 -6
  23. package/src/common/path-canonical.js +0 -41
  24. package/src/common/runtime.d.ts +0 -15
  25. package/src/common/runtime.js +0 -91
  26. package/src/common/shared-buffer-region.d.ts +0 -11
  27. package/src/common/shared-buffer-region.js +0 -21
  28. package/src/common/shared-buffer-text.d.ts +0 -16
  29. package/src/common/shared-buffer-text.js +0 -65
  30. package/src/common/task-source.d.ts +0 -3
  31. package/src/common/task-source.js +0 -84
  32. package/src/common/task-symbol.d.ts +0 -1
  33. package/src/common/task-symbol.js +0 -1
  34. package/src/common/with-resolvers.d.ts +0 -9
  35. package/src/common/with-resolvers.js +0 -23
  36. package/src/common/worker-runtime.d.ts +0 -42
  37. package/src/common/worker-runtime.js +0 -61
  38. package/src/connections/buffer-reference-native.d.ts +0 -56
  39. package/src/connections/buffer-reference-native.js +0 -217
  40. package/src/connections/buffer-reference.d.ts +0 -78
  41. package/src/connections/buffer-reference.js +0 -461
  42. package/src/connections/bun.d.ts +0 -22
  43. package/src/connections/bun.js +0 -214
  44. package/src/connections/deno.d.ts +0 -22
  45. package/src/connections/deno.js +0 -205
  46. package/src/connections/file-descriptor.d.ts +0 -39
  47. package/src/connections/file-descriptor.js +0 -161
  48. package/src/connections/index.d.ts +0 -4
  49. package/src/connections/index.js +0 -4
  50. package/src/connections/node-addons.d.ts +0 -5
  51. package/src/connections/node-addons.js +0 -43
  52. package/src/connections/node-buffer-pointer.d.ts +0 -20
  53. package/src/connections/node-buffer-pointer.js +0 -16
  54. package/src/connections/node.d.ts +0 -30
  55. package/src/connections/node.js +0 -62
  56. package/src/connections/posix.d.ts +0 -32
  57. package/src/connections/posix.js +0 -77
  58. package/src/connections/process-shared-buffer.d.ts +0 -75
  59. package/src/connections/process-shared-buffer.js +0 -279
  60. package/src/connections/shared-array-buffer-payload.d.ts +0 -36
  61. package/src/connections/shared-array-buffer-payload.js +0 -235
  62. package/src/connections/types.d.ts +0 -50
  63. package/src/connections/types.js +0 -37
  64. package/src/connections/windows.d.ts +0 -28
  65. package/src/connections/windows.js +0 -224
  66. package/src/debug/env-diff.d.ts +0 -26
  67. package/src/debug/env-diff.js +0 -49
  68. package/src/debug/gate.d.ts +0 -18
  69. package/src/debug/gate.js +0 -69
  70. package/src/debug/handle.d.ts +0 -23
  71. package/src/debug/handle.js +0 -48
  72. package/src/error.d.ts +0 -13
  73. package/src/error.js +0 -49
  74. package/src/ipc/tools/ring-queue.d.ts +0 -33
  75. package/src/ipc/tools/ring-queue.js +0 -159
  76. package/src/ipc/transport/shared-memory.d.ts +0 -23
  77. package/src/ipc/transport/shared-memory.js +0 -35
  78. package/src/memory/byte-carpet.d.ts +0 -73
  79. package/src/memory/byte-carpet.js +0 -157
  80. package/src/memory/lock.d.ts +0 -201
  81. package/src/memory/lock.js +0 -739
  82. package/src/memory/payload-config.d.ts +0 -31
  83. package/src/memory/payload-config.js +0 -67
  84. package/src/memory/payloadCodec.d.ts +0 -46
  85. package/src/memory/payloadCodec.js +0 -1334
  86. package/src/memory/regionRegistry.d.ts +0 -17
  87. package/src/memory/regionRegistry.js +0 -285
  88. package/src/memory/shared-buffer-io.d.ts +0 -55
  89. package/src/memory/shared-buffer-io.js +0 -403
  90. package/src/permission/index.d.ts +0 -2
  91. package/src/permission/index.js +0 -2
  92. package/src/permission/protocol.d.ts +0 -166
  93. package/src/permission/protocol.js +0 -650
  94. package/src/runtime/balancer.d.ts +0 -19
  95. package/src/runtime/balancer.js +0 -149
  96. package/src/runtime/dispatcher.d.ts +0 -34
  97. package/src/runtime/dispatcher.js +0 -142
  98. package/src/runtime/inline-executor.d.ts +0 -10
  99. package/src/runtime/inline-executor.js +0 -282
  100. package/src/runtime/pool.d.ts +0 -30
  101. package/src/runtime/pool.js +0 -391
  102. package/src/runtime/process-worker.d.ts +0 -92
  103. package/src/runtime/process-worker.js +0 -673
  104. package/src/runtime/tx-queue.d.ts +0 -26
  105. package/src/runtime/tx-queue.js +0 -151
  106. package/src/shared/abortSignal.d.ts +0 -23
  107. package/src/shared/abortSignal.js +0 -134
  108. package/src/types.d.ts +0 -346
  109. package/src/types.js +0 -2
  110. package/src/utils/http.d.ts +0 -29
  111. package/src/utils/http.js +0 -100
  112. package/src/worker/bootstrap.d.ts +0 -5
  113. package/src/worker/bootstrap.js +0 -78
  114. package/src/worker/composable-runners.d.ts +0 -12
  115. package/src/worker/composable-runners.js +0 -97
  116. package/src/worker/loop.d.ts +0 -2
  117. package/src/worker/loop.js +0 -382
  118. package/src/worker/process-worker-bootstrap.d.ts +0 -8
  119. package/src/worker/process-worker-bootstrap.js +0 -160
  120. package/src/worker/rx-queue.d.ts +0 -25
  121. package/src/worker/rx-queue.js +0 -173
  122. package/src/worker/safety/index.d.ts +0 -4
  123. package/src/worker/safety/index.js +0 -4
  124. package/src/worker/safety/performance.d.ts +0 -1
  125. package/src/worker/safety/performance.js +0 -17
  126. package/src/worker/safety/process.d.ts +0 -2
  127. package/src/worker/safety/process.js +0 -79
  128. package/src/worker/safety/startup.d.ts +0 -16
  129. package/src/worker/safety/startup.js +0 -30
  130. package/src/worker/safety/worker-data.d.ts +0 -2
  131. package/src/worker/safety/worker-data.js +0 -36
  132. package/src/worker/task-loader.d.ts +0 -27
  133. package/src/worker/task-loader.js +0 -78
  134. package/src/worker/timers.d.ts +0 -18
  135. package/src/worker/timers.js +0 -116
package/src/debug/gate.js DELETED
@@ -1,69 +0,0 @@
1
- /**
2
- * Zero-cost debug gate.
3
- *
4
- * Read once at module load from `KNITTING_DEBUG`. This module is deliberately
5
- * tiny and dependency-light: importing it must never pull in the logger or the
6
- * environment-diff machinery. Callers branch on {@link DEBUG_ENABLED} and only
7
- * then `await import("./handle.ts")`, so when debug is off nothing else under
8
- * `src/debug` is ever loaded — literally zero cost, not merely cheap.
9
- *
10
- * `KNITTING_DEBUG` is a comma-separated list of namespaces:
11
- * KNITTING_DEBUG=host,imports # only those
12
- * KNITTING_DEBUG=* # everything
13
- */
14
- import { getNodeProcess } from "../common/node-compat.js";
15
- const readEnv = (key) => {
16
- // Deno: `process.env` exists under node-compat, but reading it may require
17
- // --allow-env. Prefer the typed `Deno.env` and swallow permission errors.
18
- const denoEnv = globalThis.Deno?.env;
19
- if (typeof denoEnv?.get === "function") {
20
- try {
21
- return denoEnv.get(key);
22
- }
23
- catch {
24
- /* env permission denied — fall through to node/bun */
25
- }
26
- }
27
- try {
28
- return getNodeProcess()?.env?.[key];
29
- }
30
- catch {
31
- return undefined;
32
- }
33
- };
34
- const raw = readEnv("KNITTING_DEBUG");
35
- /** Namespaces explicitly requested via `KNITTING_DEBUG`. */
36
- export const DEBUG_NAMESPACES = new Set((raw ?? "")
37
- .split(",")
38
- .map((part) => part.trim())
39
- .filter((part) => part.length > 0));
40
- /**
41
- * True when at least one namespace is requested via the env var alone. Guards
42
- * the env-only paths; callers that also accept a `debug` option should use
43
- * {@link resolveDebugNamespaces} instead.
44
- */
45
- export const DEBUG_ENABLED = DEBUG_NAMESPACES.size > 0;
46
- /**
47
- * Merge the namespaces requested through the `debug` pool option with those from
48
- * `KNITTING_DEBUG`; either source can enable a namespace. Returns an empty set
49
- * when nothing is requested, so callers use `.size === 0` to keep the rest of
50
- * `src/debug` unloaded — zero cost when off.
51
- */
52
- export const resolveDebugNamespaces = (debug) => {
53
- const namespaces = new Set(DEBUG_NAMESPACES);
54
- if (debug === true) {
55
- namespaces.add("*");
56
- }
57
- else if (debug !== undefined && debug !== false) {
58
- for (const [key, value] of Object.entries(debug)) {
59
- if (value === true)
60
- namespaces.add(key);
61
- }
62
- }
63
- return namespaces;
64
- };
65
- /** True when `namespace` (or `"*"`) is active for the given `debug` config + env. */
66
- export const debugHas = (debug, namespace) => {
67
- const namespaces = resolveDebugNamespaces(debug);
68
- return namespaces.has("*") || namespaces.has(namespace);
69
- };
@@ -1,23 +0,0 @@
1
- export type DebugInit = {
2
- /** Identity prefix for log tags, e.g. `"w0"` for a worker or `"main"`. */
3
- readonly name: string;
4
- readonly runtime: string;
5
- readonly namespaces: ReadonlySet<string>;
6
- };
7
- export type Debug = {
8
- /**
9
- * Is a namespace active? Capture this once before a hot loop and branch on
10
- * the boolean — never call per-iteration.
11
- */
12
- enabled: (namespace: string) => boolean;
13
- /** Emit a tagged line to stderr when `namespace` is active. */
14
- log: (namespace: string, message: string) => void;
15
- /**
16
- * Re-snapshot `globalThis` and report what changed since the previous phase.
17
- * Drives two-phase pollution attribution (e.g. `"bootstrap"` then
18
- * `"tasks"`), so you can see which loader injected which global. No-op unless
19
- * the `globals` namespace is active.
20
- */
21
- envPhase: (label: string) => void;
22
- };
23
- export declare const initDebug: ({ name, runtime, namespaces }: DebugInit) => Debug;
@@ -1,48 +0,0 @@
1
- /**
2
- * Worker-side debug handle. Lazily imported (see {@link ./gate.ts}) only when
3
- * `KNITTING_DEBUG` names at least one namespace, so neither this code nor the
4
- * baseline snapshot it takes exists when debug is off.
5
- *
6
- * Diagnostics go to stderr so they never corrupt a worker's stdout, and every
7
- * line is tagged with the worker id, runtime, and a clock relative to when this
8
- * worker's debug initialised. The clock is worker-local on purpose: a main-thread
9
- * timestamp can't be compared against `performance.now()` here because the time
10
- * origins differ across the thread/process boundary (it would read negative).
11
- */
12
- import { describeGlobalKey, diffGlobals, snapshotGlobals, } from "./env-diff.js";
13
- export const initDebug = ({ name, runtime, namespaces }) => {
14
- const all = namespaces.has("*");
15
- const enabled = (namespace) => all || namespaces.has(namespace);
16
- const base = performance.now();
17
- const tag = `${name}·${runtime}`;
18
- const log = (namespace, message) => {
19
- if (!enabled(namespace))
20
- return;
21
- const elapsed = (performance.now() - base).toFixed(1);
22
- console.error(`[${tag}·+${elapsed}ms] ${namespace}: ${message}`);
23
- };
24
- // Baseline for the environment diff, taken the moment debug initialises:
25
- // before worker bootstrap and before any task module is imported. Only paid
26
- // when `globals` tracing is actually on.
27
- let previous = enabled("globals")
28
- ? snapshotGlobals()
29
- : undefined;
30
- const envPhase = (label) => {
31
- if (previous === undefined)
32
- return;
33
- const current = snapshotGlobals();
34
- const { added, removed } = diffGlobals(previous, current);
35
- previous = current;
36
- if (added.length === 0 && removed.length === 0) {
37
- log("globals", `${label}: no new globals`);
38
- return;
39
- }
40
- if (added.length > 0) {
41
- log("globals", `${label} +${added.length}: ${added.map(describeGlobalKey).join(" ")}`);
42
- }
43
- if (removed.length > 0) {
44
- log("globals", `${label} -${removed.length}: ${removed.map(String).join(" ")}`);
45
- }
46
- };
47
- return { enabled, log, envPhase };
48
- };
package/src/error.d.ts DELETED
@@ -1,13 +0,0 @@
1
- import { type PromisePayloadHandler, type Task } from "./memory/lock.js";
2
- export declare enum ErrorKnitting {
3
- Function = 0,
4
- Symbol = 1,
5
- Json = 2,
6
- Serializable = 3
7
- }
8
- export declare const encoderError: ({ task, type, onPromise, detail, }: {
9
- task: Task;
10
- type: ErrorKnitting;
11
- onPromise?: PromisePayloadHandler;
12
- detail?: string;
13
- }) => false;
package/src/error.js DELETED
@@ -1,49 +0,0 @@
1
- import { beginPromisePayload, finishPromisePayload, TaskFlag, TaskIndex, } from "./memory/lock.js";
2
- import { RUNTIME_IS_MAIN_THREAD } from "./common/worker-runtime.js";
3
- export var ErrorKnitting;
4
- (function (ErrorKnitting) {
5
- ErrorKnitting[ErrorKnitting["Function"] = 0] = "Function";
6
- ErrorKnitting[ErrorKnitting["Symbol"] = 1] = "Symbol";
7
- ErrorKnitting[ErrorKnitting["Json"] = 2] = "Json";
8
- ErrorKnitting[ErrorKnitting["Serializable"] = 3] = "Serializable";
9
- })(ErrorKnitting || (ErrorKnitting = {}));
10
- const reasonFrom = (task, type, detail) => {
11
- switch (type) {
12
- case ErrorKnitting.Function: {
13
- const name = typeof task.value === "function"
14
- ? (task.value.name || "<anonymous>")
15
- : "<unknown>";
16
- return `KNT_ERROR_0: Function is not a valid type; name: ${name}`;
17
- }
18
- case ErrorKnitting.Symbol:
19
- return "KNT_ERROR_1: Symbol must use Symbol.for(...) keys";
20
- case ErrorKnitting.Json:
21
- return detail == null || detail.length === 0
22
- ? "KNT_ERROR_2: JSON stringify failed; payload must be JSON-safe"
23
- : `KNT_ERROR_2: JSON stringify failed; ${detail}`;
24
- case ErrorKnitting.Serializable:
25
- return detail == null || detail.length === 0
26
- ? "KNT_ERROR_3: Unsupported payload type; serialize it yourself"
27
- : `KNT_ERROR_3: Unsupported payload type; ${detail}`;
28
- }
29
- };
30
- export const encoderError = ({ task, type, onPromise, detail, }) => {
31
- const reason = reasonFrom(task, type, detail);
32
- if (!RUNTIME_IS_MAIN_THREAD) {
33
- task.value = reason;
34
- task[TaskIndex.FlagsToHost] = TaskFlag.Reject;
35
- return false;
36
- }
37
- // Fallback for direct codec usage where no async settle callback is wired.
38
- if (onPromise == null) {
39
- throw new TypeError(reason);
40
- }
41
- if (!beginPromisePayload(task))
42
- return false;
43
- queueMicrotask(() => {
44
- finishPromisePayload(task);
45
- task.value = reason;
46
- onPromise(task, true, reason);
47
- });
48
- return false;
49
- };
@@ -1,33 +0,0 @@
1
- export default class RingQueue<T> implements Iterable<T> {
2
- #private;
3
- constructor(capacity?: number);
4
- get size(): number;
5
- get isEmpty(): boolean;
6
- get capacity(): number;
7
- clear(): void;
8
- peek(): T | undefined;
9
- /** Ensure internal capacity >= requested (rounds up to next power of two). */
10
- reserve(minCapacity: number): void;
11
- /**
12
- * Push to back
13
- * Always succeeds (grows if full)
14
- */
15
- push(value: T): true;
16
- /**
17
- * Push to front (unshift)
18
- * Always succeeds (grows if full)
19
- */
20
- unshift(value: T): true;
21
- /**
22
- * Pop from front (shift)
23
- */
24
- shift(): T | undefined;
25
- /**
26
- * Pop from front (shift) without clearing the slot.
27
- * Use only for internal pooled-object queues where retaining references is acceptable.
28
- */
29
- shiftNoClear(): T | undefined;
30
- [Symbol.iterator](): Generator<T, void, void>;
31
- toArray(): T[];
32
- get [Symbol.toStringTag](): string;
33
- }
@@ -1,159 +0,0 @@
1
- ;
2
- export default class RingQueue {
3
- #buf;
4
- #mask;
5
- #head = 0;
6
- #tail = 0;
7
- #size = 0;
8
- constructor(capacity = 512) {
9
- let cap = 2;
10
- while (cap < capacity)
11
- cap <<= 1;
12
- // Keep the array packed (avoid holey elements in hot queue paths).
13
- this.#buf = new Array(cap).fill(null);
14
- this.#mask = cap - 1;
15
- }
16
- get size() {
17
- return this.#size;
18
- }
19
- get isEmpty() {
20
- return this.#size === 0;
21
- }
22
- get capacity() {
23
- return this.#mask + 1;
24
- }
25
- clear() {
26
- // Keep buffer allocated; reset pointers (fast)
27
- // (optional) also drop references to help GC if you want:
28
- // for (let i = 0; i < this.#size; i++) this.#buf[(this.#head + i) & this.#mask] = null;
29
- this.#head = 0;
30
- this.#tail = 0;
31
- this.#size = 0;
32
- }
33
- peek() {
34
- return this.#size === 0 ? undefined : this.#buf[this.#head];
35
- }
36
- /** Ensure internal capacity >= requested (rounds up to next power of two). */
37
- reserve(minCapacity) {
38
- if (minCapacity <= this.capacity)
39
- return;
40
- let cap = this.capacity;
41
- while (cap < minCapacity)
42
- cap <<= 1;
43
- this.#growTo(cap);
44
- }
45
- // --- hot path internal ---
46
- #growIfFull() {
47
- if (this.#size !== (this.#mask + 1))
48
- return;
49
- this.#growTo((this.#mask + 1) << 1);
50
- }
51
- #growTo(newCap) {
52
- const oldBuf = this.#buf;
53
- const oldCap = this.#mask + 1;
54
- const n = this.#size;
55
- const next = new Array(newCap).fill(null);
56
- const head = this.#head;
57
- const firstLen = Math.min(n, oldCap - head);
58
- // copy [head..end)
59
- for (let i = 0; i < firstLen; i++) {
60
- next[i] = oldBuf[head + i];
61
- }
62
- // copy [0..remaining)
63
- for (let i = firstLen; i < n; i++) {
64
- next[i] = oldBuf[i - firstLen];
65
- }
66
- this.#buf = next;
67
- this.#mask = newCap - 1;
68
- this.#head = 0;
69
- this.#tail = n;
70
- }
71
- /**
72
- * Push to back
73
- * Always succeeds (grows if full)
74
- */
75
- push(value) {
76
- this.#growIfFull();
77
- const buf = this.#buf;
78
- const mask = this.#mask;
79
- const tail = this.#tail;
80
- buf[tail] = value;
81
- this.#tail = (tail + 1) & mask;
82
- this.#size++;
83
- return true;
84
- }
85
- /**
86
- * Push to front (unshift)
87
- * Always succeeds (grows if full)
88
- */
89
- unshift(value) {
90
- this.#growIfFull();
91
- const buf = this.#buf;
92
- const mask = this.#mask;
93
- const head = (this.#head - 1) & mask;
94
- this.#head = head;
95
- buf[head] = value;
96
- this.#size++;
97
- return true;
98
- }
99
- /**
100
- * Pop from front (shift)
101
- */
102
- shift() {
103
- const size = this.#size;
104
- if (size === 0)
105
- return undefined;
106
- const head = this.#head;
107
- const buf = this.#buf;
108
- const v = buf[head];
109
- buf[head] = null; // help GC while keeping packed elements
110
- this.#head = (head + 1) & this.#mask;
111
- this.#size = size - 1;
112
- return v;
113
- }
114
- /**
115
- * Pop from front (shift) without clearing the slot.
116
- * Use only for internal pooled-object queues where retaining references is acceptable.
117
- */
118
- shiftNoClear() {
119
- const size = this.#size;
120
- if (size === 0)
121
- return undefined;
122
- const head = this.#head;
123
- const v = this.#buf[head];
124
- this.#head = (head + 1) & this.#mask;
125
- this.#size = size - 1;
126
- return v;
127
- }
128
- *[Symbol.iterator]() {
129
- const buf = this.#buf;
130
- const mask = this.#mask;
131
- let idx = this.#head;
132
- let i = 0;
133
- const n = this.#size;
134
- while (i < n) {
135
- // values should never be null inside active range, but keep it safe
136
- const v = buf[idx];
137
- if (v !== null)
138
- yield v;
139
- idx = (idx + 1) & mask;
140
- i++;
141
- }
142
- }
143
- toArray() {
144
- // faster than Array.from(this) in some cases because it avoids iterator overhead,
145
- // but keep iterator version if you prefer simplicity.
146
- const out = new Array(this.#size);
147
- const buf = this.#buf;
148
- const mask = this.#mask;
149
- let idx = this.#head;
150
- for (let i = 0; i < out.length; i++) {
151
- out[i] = buf[idx];
152
- idx = (idx + 1) & mask;
153
- }
154
- return out;
155
- }
156
- get [Symbol.toStringTag]() {
157
- return `RingQueue(size=${this.#size}, cap=${this.capacity})`;
158
- }
159
- }
@@ -1,23 +0,0 @@
1
- export type SignalArguments = ReturnType<typeof createSharedMemoryTransport>;
2
- import { type SharedBufferSource } from "../../common/shared-buffer-region.js";
3
- export declare const TRANSPORT_SIGNAL_BYTES: number;
4
- export type Sab = {
5
- size?: number;
6
- sharedSab?: SharedBufferSource;
7
- };
8
- type SignalForWorker = {
9
- sabObject?: Sab;
10
- isMain: boolean;
11
- thread: number;
12
- startTime?: number;
13
- };
14
- export declare const createSharedMemoryTransport: ({ sabObject, isMain, startTime }: SignalForWorker) => {
15
- sab: import("../../common/shared-buffer-region.js").SharedBufferRegion;
16
- op: Int32Array<import("../../common/shared-buffer-region.js").SharedBuffer>;
17
- startAt: number;
18
- opView: Int32Array<import("../../common/shared-buffer-region.js").SharedBuffer>;
19
- rxStatus: Int32Array<import("../../common/shared-buffer-region.js").SharedBuffer>;
20
- txStatus: Int32Array<import("../../common/shared-buffer-region.js").SharedBuffer>;
21
- };
22
- export type MainSignal = Pick<SignalArguments, "opView" | "startAt" | "rxStatus" | "txStatus">;
23
- export {};
@@ -1,35 +0,0 @@
1
- import { createSharedArrayBuffer } from "../../common/runtime.js";
2
- import { toSharedBufferRegion, } from "../../common/shared-buffer-region.js";
3
- const page = 1024 * 4;
4
- const CACHE_LINE_BYTES = 64;
5
- // Keep hot signals on separate cache lines to avoid false sharing.
6
- const SIGNAL_OFFSETS = {
7
- op: 0,
8
- rxStatus: CACHE_LINE_BYTES,
9
- txStatus: CACHE_LINE_BYTES * 2,
10
- };
11
- export const TRANSPORT_SIGNAL_BYTES = CACHE_LINE_BYTES * 3;
12
- const a_store = Atomics.store;
13
- export const createSharedMemoryTransport = ({ sabObject, isMain, startTime }) => {
14
- const toGrow = sabObject?.size ?? page;
15
- const roundedSize = toGrow + ((page - (toGrow % page)) % page);
16
- const signalRegion = toSharedBufferRegion(sabObject?.sharedSab
17
- ? sabObject.sharedSab
18
- : createSharedArrayBuffer(roundedSize, page * page));
19
- const sab = signalRegion.sab;
20
- const baseByteOffset = signalRegion.byteOffset;
21
- const startAt = startTime ?? performance.now();
22
- const opView = new Int32Array(sab, baseByteOffset + SIGNAL_OFFSETS.op, 1);
23
- if (isMain)
24
- a_store(opView, 0, 0);
25
- const rxStatus = new Int32Array(sab, baseByteOffset + SIGNAL_OFFSETS.rxStatus, 1);
26
- a_store(rxStatus, 0, 1);
27
- return {
28
- sab: signalRegion,
29
- op: opView,
30
- startAt,
31
- opView,
32
- rxStatus,
33
- txStatus: new Int32Array(sab, baseByteOffset + SIGNAL_OFFSETS.txStatus, 1),
34
- };
35
- };
@@ -1,73 +0,0 @@
1
- import type { SharedBuffer, SharedBufferRegion } from "../common/shared-buffer-region.js";
2
- export declare const BYTE_CARPET_ALIGN_BYTES = 64;
3
- export declare const alignBytes: (value: number, alignment?: number) => number;
4
- export declare const makeSharedBufferRegion: (sab: SharedBuffer, byteOffset: number, byteLength: number) => SharedBufferRegion;
5
- export type ByteCarpetSlice = {
6
- name: string;
7
- byteOffset: number;
8
- byteLength: number;
9
- reservedByteLength: number;
10
- };
11
- export declare const createByteCarpet: ({ alignTo, startByteOffset, }?: {
12
- alignTo?: number;
13
- startByteOffset?: number;
14
- }) => {
15
- slices: ByteCarpetSlice[];
16
- take: (name: string, byteLength: number, { alignTo: sliceAlignment, reserveByteLength, }?: {
17
- alignTo?: number;
18
- reserveByteLength?: number;
19
- }) => ByteCarpetSlice;
20
- byteLength: () => number;
21
- bind: (sab: SharedBuffer, slice: ByteCarpetSlice) => SharedBufferRegion;
22
- };
23
- export declare const getStridedSlotOffsetU32: ({ slotIndex, slotStrideU32, baseU32, extraU32, }: {
24
- slotIndex: number;
25
- slotStrideU32: number;
26
- baseU32?: number;
27
- extraU32?: number;
28
- }) => number;
29
- export declare const getStridedSlotByteOffset: ({ slotIndex, slotStrideU32, baseByteOffset, baseU32, extraU32, }: {
30
- slotIndex: number;
31
- slotStrideU32: number;
32
- baseByteOffset?: number;
33
- baseU32?: number;
34
- extraU32?: number;
35
- }) => number;
36
- export declare const getStridedRegionSpanBytes: ({ slotCount, slotStrideU32, slotLengthU32, baseU32, }: {
37
- slotCount: number;
38
- slotStrideU32: number;
39
- slotLengthU32: number;
40
- baseU32?: number;
41
- }) => number;
42
- export declare const getInterleavedSlotStrideU32: (slotStrideU32: number) => number;
43
- export declare const getHeaderBlockByteLength: ({ slotCount, slotStrideU32, queues, alignTo, }: {
44
- slotCount: number;
45
- slotStrideU32: number;
46
- queues?: number;
47
- alignTo?: number;
48
- }) => number;
49
- export type HeaderLayoutMode = "split" | "interleaved";
50
- export type QueueControlByteLayout = {
51
- headers: SharedBufferRegion;
52
- headerSlotStrideU32: number;
53
- lockSector: SharedBufferRegion;
54
- payloadSector: SharedBufferRegion;
55
- };
56
- export type LockControlCarpet = {
57
- controlSAB: SharedBuffer;
58
- signals: SharedBufferRegion;
59
- abortSignals: SharedBufferRegion;
60
- lock: QueueControlByteLayout;
61
- returnLock: QueueControlByteLayout;
62
- slices: readonly ByteCarpetSlice[];
63
- };
64
- export declare const createLockControlCarpet: ({ signalBytes, abortBytes, lockSectorBytes, headerSlotStrideU32, slotCount, headerLayout, alignTo, createBuffer, }: {
65
- signalBytes: number;
66
- abortBytes: number;
67
- lockSectorBytes: number;
68
- headerSlotStrideU32: number;
69
- slotCount: number;
70
- headerLayout?: HeaderLayoutMode;
71
- alignTo?: number;
72
- createBuffer?: (byteLength: number) => SharedBuffer;
73
- }) => LockControlCarpet;