@loro-dev/loro-repo-engine 0.2.0-next.1 → 0.2.0-next.2

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 (4) hide show
  1. package/README.md +123 -15
  2. package/index.d.ts +26 -8
  3. package/index.js +2 -2
  4. package/package.json +7 -7
package/README.md CHANGED
@@ -347,10 +347,9 @@ Executes the embedded `loro-repo` CLI synchronously in the current process (`arg
347
347
  - `1`: runtime or I/O error (including `ENGINE_BUSY` if another daemon already locks `--data-dir`)
348
348
  - `2`: invalid CLI usage or bad flags
349
349
 
350
- ### Host process helpers: `closeInheritedDescriptors()` and `hardenHostProcess()`
350
+ ### Host process helpers: `hardenHostProcess()`
351
351
 
352
352
  ```ts
353
- export function closeInheritedDescriptors(): number;
354
353
  export function hardenHostProcess(): HostHardening;
355
354
  export interface HostHardening {
356
355
  coreDumpsDisabled: boolean; // RLIMIT_CORE is 0 (soft and hard)
@@ -361,22 +360,128 @@ export interface HostHardening {
361
360
  ```
362
361
 
363
362
  A dedicated process that hosts the engine holds epoch keys and writer seeds in memory. Call
364
- both first thing in that process, in this order:
363
+ `hardenHostProcess()` first thing in that process. It keeps key material out of crash
364
+ artifacts:
365
365
 
366
- 1. `closeInheritedDescriptors()` closes every descriptor above stderr that it inherited
367
- without close-on-exec, so a short-lived launcher's pipes do not stay open. It returns how
368
- many it closed; off Unix it closes nothing.
369
- 2. `hardenHostProcess()` keeps key material out of crash artifacts:
366
+ | Platform | Applied | `limitations` |
367
+ | --- | --- | --- |
368
+ | Linux | `setrlimit(RLIMIT_CORE, 0)` and `prctl(PR_SET_DUMPABLE, 0)`: no core file, and same-user processes can neither `ptrace` it nor read its memory through `/proc` | none |
369
+ | macOS | `setrlimit(RLIMIT_CORE, 0)` | no `PR_SET_DUMPABLE` equivalent; same-user debugger attach is governed by SIP and code signing, not by this call; ReportCrash reports carry stacks and registers, not memory |
370
+ | Windows | nothing in-process | Windows Error Reporting may write a dump; disable WER `LocalDumps` for the host executable |
371
+
372
+ Each item is re-read after it is applied, so the result reports what is actually in effect.
373
+ The call is idempotent and never throws.
374
+
375
+ ### Launching a dedicated host: descriptors are the launcher's job
376
+
377
+ A host outlives the application that starts it. If it keeps a descriptor that application
378
+ inherited (a pipe or socket from a test runner, for example), the application's own parent
379
+ never sees end-of-file. The host process cannot fix this itself, because it cannot tell an
380
+ inherited descriptor from one its runtime opened:
381
+
382
+ - Node marks low inherited descriptors (3 and 4 in practice) close-on-exec at startup, so
383
+ they look like Node's own.
384
+ - Electron run as Node (`ELECTRON_RUN_AS_NODE=1`) opens some of its own descriptors without
385
+ close-on-exec (its V8 snapshot, an epoll and an eventfd). Closing them leaves the
386
+ process unable to exit.
387
+ - Closing everything above stderr would also close Node's own event loop descriptors.
388
+
389
+ So the package has no in-process "close inherited descriptors" call. The launcher gives
390
+ the host nothing beyond stdio. Use `spawnDetachedHost`:
391
+
392
+ ```ts
393
+ export function spawnDetachedHost(
394
+ command: string, // path to an executable, not a shell command or batch file
395
+ args: string[],
396
+ options?: { env?: Record<string, string>; cwd?: string }, // env replaces the whole environment
397
+ ): number; // process id; nothing waits on it
398
+
399
+ const pid = spawnDetachedHost(process.execPath, [hostEntry, dataDir], {
400
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
401
+ });
402
+ ```
403
+
404
+ The child's stdio is the null device, and it inherits nothing else:
405
+
406
+ | Platform | How |
407
+ | --- | --- |
408
+ | Linux, macOS | Every descriptor above stderr is marked close-on-exec in the child before exec (Linux: one `close_range`; otherwise each descriptor up to the limit). The child runs in its own session (`setsid`). The addon reaps it when it exits. |
409
+ | Windows | `CreateProcessW` with `PROC_THREAD_ATTRIBUTE_HANDLE_LIST` naming only the null device. It uses `DETACHED_PROCESS` (no console) and a new process group. It also breaks away from the launcher's job object when the job allows that, and otherwise stays in it. |
370
410
 
371
- | Platform | Applied | `limitations` |
372
- | --- | --- | --- |
373
- | Linux | `setrlimit(RLIMIT_CORE, 0)` and `prctl(PR_SET_DUMPABLE, 0)`: no core file, and same-user processes can neither `ptrace` it nor read its memory through `/proc` | none |
374
- | macOS | `setrlimit(RLIMIT_CORE, 0)` | no `PR_SET_DUMPABLE` equivalent; same-user debugger attach is governed by SIP and code signing, not by this call; ReportCrash reports carry stacks and registers, not memory |
375
- | Windows | nothing in-process | Windows Error Reporting may write a dump; disable WER `LocalDumps` for the host executable |
411
+ Node's `child_process` cannot do this. On Windows, libuv starts every child with handle
412
+ inheritance on, so each inheritable handle in the launcher reaches the host. That
413
+ includes, for example, a test runner's stdio pipes that Electron inherited. No `stdio`
414
+ option changes that. On Linux, a child keeps every descriptor the launcher holds without
415
+ close-on-exec.
416
+
417
+ **Fallback without the addon (Linux and macOS only).** Map every descriptor slot from 3 up to
418
+ the highest one open in the launcher to `/dev/null`. The child starts with `/dev/null` in
419
+ each slot, and nothing else is inherited. (`'ignore'` covers only 0 to 2.) On macOS,
420
+ libuv already spawns with `POSIX_SPAWN_CLOEXEC_DEFAULT`, so a child inherits only the stdio
421
+ it is given. The same mapping is harmless there. On Windows there is no `child_process`
422
+ equivalent, so use `spawnDetachedHost` or a launcher such as PowerShell `Start-Process`.
423
+
424
+ ```js
425
+ const devNull = openSync("/dev/null", "r");
426
+ const open = readdirSync(process.platform === "linux" ? "/proc/self/fd" : "/dev/fd").map(Number);
427
+ const stdio = Array.from({ length: Math.max(2, ...open) + 1 }, (_, fd) => (fd < 3 ? "ignore" : devNull));
428
+ spawn(command, args, { stdio, detached: true }).unref();
429
+ closeSync(devNull);
430
+ ```
431
+
432
+ ### Lock windows: `ENGINE_STARTING`, `ENGINE_STOPPING` and their limits
433
+
434
+ A host holds `<dataDir>/files.lock` without serving in two windows. The **starting** window
435
+ runs from taking the lock to publishing `engine.json`. The **stopping** window runs from
436
+ removing `engine.json` to releasing the lock. During either window the host keeps
437
+ `<dataDir>/engine.state.json` (`0600`) current:
438
+
439
+ ```jsonc
440
+ { "phase": "starting" | "stopping", "pid": 4242, "since_ms": 1767000000000,
441
+ "step": "publish_endpoint", "limit_ms": 30000, "stalled": false }
442
+ ```
443
+
444
+ | `step` | Phase | Where the host can wait |
445
+ | --- | --- | --- |
446
+ | `open_engine` | starting | Listing `namespaces/`. Namespace databases open later, on first use, so data size barely matters. |
447
+ | `start_runtime` | starting | Building the async runtime. |
448
+ | `bind_socket` | starting | Creating the private socket or named pipe. |
449
+ | `start_live` | starting | Starting live replication tasks. |
450
+ | `publish_endpoint` | starting | Writing and syncing `engine.json`. |
451
+ | `remove_endpoint` | stopping | Removing `engine.json` and the socket. |
452
+ | `drain_work` | stopping | Waiting for requests and blocking work (SQLite writes, compaction) to finish. |
453
+ | `release_engine` | stopping | Waiting for the last reference to the engine and its databases. |
454
+
455
+ Each window has a limit: `startLimitMs` and `stopLimitMs` (default 30 000 each;
456
+ `loro-repo serve --start-limit-ms/--stop-limit-ms`).
457
+ - **Starting.** Before `engine.json` exists, the host only lists files, binds a socket and
458
+ writes one file. That takes milliseconds whatever the data size. The 30 s default leaves
459
+ room for a slow or contended disk.
460
+ - **Stopping.** Stopping waits for requests and blocking work already running. A handoff
461
+ already bounds draining requests at 10 s.
462
+ - **Lock release.** After an idle stop or a handoff, the lock is released as soon as the
463
+ engine and its databases are gone. It no longer waits for the host process to exit.
464
+
465
+ When a limit passes, the host records the phase, step and time held. It writes them to
466
+ stderr as `ENGINE_START_STALLED` or `ENGINE_STOP_STALLED`, and to
467
+ `<dataDir>/engine.stalled.json`, which is kept until the next stall. With
468
+ `exitOnStall: true` it then exits with status `75`, and the operating system releases the
469
+ lock. `loro-repo serve` always does. Only a dedicated host process should set
470
+ `exitOnStall`: a stuck thread may still be writing the directory, so an embedded engine
471
+ cannot release the lock safely and only records the stall.
472
+
473
+ On the client side, `readEngineEndpoint` (and every client function built on it) reports
474
+ the situation when there is no `engine.json`:
475
+
476
+ | Situation | Error | Fields |
477
+ | --- | --- | --- |
478
+ | A live process holds the lock while starting | `EngineNotServingError`, message `ENGINE_STARTING: …` | `code`, `pid`, `heldForMs`, `limitMs`, `step`, `stalled` |
479
+ | A live process holds the lock while stopping | `EngineNotServingError`, message `ENGINE_STOPPING: …` | same |
480
+ | No holder (none, or its pid is gone) | the file system's `ENOENT` | |
376
481
 
377
- Each item is re-read after it is applied, so the result reports what is actually in
378
- effect. The call is idempotent and never throws. Run it after
379
- `closeInheritedDescriptors()`, which lists `/dev/fd`.
482
+ A caller can wait while `heldForMs < limitMs`. A dedicated host gives up at the limit.
483
+ `stalled: true` means the holder is past its limit, and an embedded holder may never
484
+ publish.
380
485
 
381
486
  ### Error Contract
382
487
 
@@ -385,6 +490,9 @@ both first thing in that process, in this order:
385
490
  | Another live process holds `<dataDir>/files.lock` | `Error: ENGINE_BUSY: files.lock is held by another process` | Expected in multi-process setups! Read `<dataDir>/engine.json` and connect as a client (or use `ensureEngineHost`, which handles this automatically). |
386
491
  | Negative, `NaN`, or `Infinity` passed as `idleMs` | `TypeError` / N-API `InvalidArg`: `idleMs must be a finite number >= 0` | Pass a non-negative finite integer or `undefined`. |
387
492
  | Non-`u32` passed as `maxFrameBytes` | N-API `InvalidArg` | Pass a non-negative 32-bit integer or `undefined`. |
493
+ | Negative or non-finite `startLimitMs` / `stopLimitMs` | N-API `InvalidArg` | Pass a non-negative finite number or `undefined`. |
494
+ | The lock is held but `engine.json` is missing (`readEngineEndpoint`) | `EngineNotServingError` (`ENGINE_STARTING` / `ENGINE_STOPPING`) | Wait while `heldForMs < limitMs`, then report its `pid`, `step` and `stalled`. See "Lock windows". |
495
+ | A dedicated host passed a limit | Process exit status `75`, `ENGINE_START_STALLED` / `ENGINE_STOP_STALLED` on stderr, `engine.stalled.json` | Start a new host. The lock is free. |
388
496
  | Directory permission / socket bind failure | `Error` (`GenericFailure`) with OS I/O details | Ensure parent directory is writable, owned by the current user (`0700` verification fails if owned by another UID), and not corrupted. |
389
497
  | Client / host protocol version mismatch (in `client/node`) | `Error: ENGINE_PROTOCOL_MISMATCH: ...` | Prompt user to upgrade the outdated binary/app sharing that `<dataDir>` — do **not** treat `ENGINE_PROTOCOL_MISMATCH` as transient retryable failure. |
390
498
 
package/index.d.ts CHANGED
@@ -24,6 +24,16 @@ export interface EngineOptions {
24
24
  advertisedCapabilities?: string[];
25
25
  /** Report this release instead, to stand in for an older release in compatibility tests. */
26
26
  advertisedVersion?: string;
27
+ /** Longest time from taking `files.lock` to publishing `engine.json`, in ms (default 30 000). */
28
+ startLimitMs?: number;
29
+ /** Longest time from removing `engine.json` to releasing `files.lock`, in ms (default 30 000). */
30
+ stopLimitMs?: number;
31
+ /**
32
+ * A dedicated host process: when a limit passes, record why in `engine.stalled.json`
33
+ * and exit with status 75 so the lock is released. Leave off where the engine is embedded
34
+ * in a process that must keep running; then the stall is only recorded.
35
+ */
36
+ exitOnStall?: boolean;
27
37
  }
28
38
 
29
39
  /**
@@ -117,14 +127,23 @@ export declare function engineVersion(): EngineVersion;
117
127
  */
118
128
  export declare function runCli(args: string[]): number;
119
129
 
130
+ /** Options of `spawnDetachedHost`. */
131
+ export interface SpawnHostOptions {
132
+ /** The child's whole environment (default: this process's). */
133
+ env?: Record<string, string>;
134
+ /** The child's working directory (default: this process's). */
135
+ cwd?: string;
136
+ }
137
+
120
138
  /**
121
- * Closes the descriptors this process inherited from whoever launched it: every
122
- * descriptor above stderr open without close-on-exec. A long-lived host started
123
- * by a short-lived application otherwise keeps that application's sockets and
124
- * pipes open after it exits. Call it first thing in a dedicated host process.
125
- * Returns how many were closed; off Unix it closes nothing.
139
+ * Starts a dedicated host process that outlives its launcher and inherits nothing from
140
+ * it but stdio on the null device. POSIX: its own session (`setsid`) and no descriptor
141
+ * above stderr. Windows: `CreateProcessW` with a handle list naming only the null
142
+ * device, no console, a new process group, and out of the launcher's job when the job
143
+ * allows breakaway. `command` is the path to an executable, not a shell command or a
144
+ * batch file. Returns the process id; nothing waits on it.
126
145
  */
127
- export declare function closeInheritedDescriptors(): number;
146
+ export declare function spawnDetachedHost(command: string, args: string[], options?: SpawnHostOptions): number;
128
147
 
129
148
  /** What `hardenHostProcess` put into effect, each item verified after it was applied. */
130
149
  export interface HostHardening {
@@ -142,8 +161,7 @@ export interface HostHardening {
142
161
  * Hardens a process that holds key material, such as a dedicated engine host:
143
162
  * `setrlimit(RLIMIT_CORE, 0)` on Unix and, on Linux, `prctl(PR_SET_DUMPABLE, 0)`.
144
163
  * macOS gets the core limit only; Windows gets nothing in-process (see
145
- * `limitations`). Call it once, early, after `closeInheritedDescriptors()`.
146
- * Idempotent; never throws.
164
+ * `limitations`). Call it once, early. Idempotent; never throws.
147
165
  */
148
166
  export declare function hardenHostProcess(): HostHardening;
149
167
 
package/index.js CHANGED
@@ -40,8 +40,8 @@ const {
40
40
  startEngine,
41
41
  engineVersion,
42
42
  runCli,
43
- closeInheritedDescriptors,
44
43
  hardenHostProcess,
44
+ spawnDetachedHost,
45
45
  } = load();
46
46
  module.exports = {
47
47
  Engine,
@@ -49,6 +49,6 @@ module.exports = {
49
49
  startEngine,
50
50
  engineVersion,
51
51
  runCli,
52
- closeInheritedDescriptors,
53
52
  hardenHostProcess,
53
+ spawnDetachedHost,
54
54
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loro-dev/loro-repo-engine",
3
- "version": "0.2.0-next.1",
3
+ "version": "0.2.0-next.2",
4
4
  "description": "The loro-repo engine, prebuilt as a Node-API addon. Source is not public (D3).",
5
5
  "license": "UNLICENSED",
6
6
  "publishConfig": {
@@ -32,12 +32,12 @@
32
32
  ]
33
33
  },
34
34
  "optionalDependencies": {
35
- "@loro-dev/loro-repo-engine-darwin-arm64": "0.2.0-next.1",
36
- "@loro-dev/loro-repo-engine-darwin-x64": "0.2.0-next.1",
37
- "@loro-dev/loro-repo-engine-linux-x64-gnu": "0.2.0-next.1",
38
- "@loro-dev/loro-repo-engine-linux-arm64-gnu": "0.2.0-next.1",
39
- "@loro-dev/loro-repo-engine-win32-x64-msvc": "0.2.0-next.1",
40
- "@loro-dev/loro-repo-engine-win32-arm64-msvc": "0.2.0-next.1"
35
+ "@loro-dev/loro-repo-engine-darwin-arm64": "0.2.0-next.2",
36
+ "@loro-dev/loro-repo-engine-darwin-x64": "0.2.0-next.2",
37
+ "@loro-dev/loro-repo-engine-linux-x64-gnu": "0.2.0-next.2",
38
+ "@loro-dev/loro-repo-engine-linux-arm64-gnu": "0.2.0-next.2",
39
+ "@loro-dev/loro-repo-engine-win32-x64-msvc": "0.2.0-next.2",
40
+ "@loro-dev/loro-repo-engine-win32-arm64-msvc": "0.2.0-next.2"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@napi-rs/cli": "^3.10.0"