quilltap 4.15.0 → 4.16.0-dev.10
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.
- package/README.md +18 -5
- package/bin/quilltap.js +88 -110
- package/lib/__tests__/docs-write-base64.test.js +155 -0
- package/lib/db-commands.js +4 -4
- package/lib/docs-commands.js +36 -10
- package/lib/lock-helpers.js +319 -120
- package/lib/migrations.generated.js +16 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -211,11 +211,18 @@ In the REPL, `.cols <table>` and `.find <text>` mirror the subcommand helpers.
|
|
|
211
211
|
|
|
212
212
|
Everything that writes to an instance claims `<dataDir>/quilltap.lock` — the same lockfile the server itself uses — for the duration, and releases it on exit. That is `db --write` (including `db --repl --write`), `db optimize`, `maintenance run`, and `instances restore-key`. All four **refuse while the lock is held**: stop the server first. Read-only work — plain `db`, the `docs` read verbs, `memories`, `logs`, `migrations`, `maintenance status`, `db backup`, `db integrity` — never touches the lock and is safe alongside a running instance.
|
|
213
213
|
|
|
214
|
-
###
|
|
214
|
+
### When a lock counts as held
|
|
215
215
|
|
|
216
|
-
|
|
216
|
+
The server and the CLI's writers decide the same way, case for case; one table of cases is tested against both.
|
|
217
217
|
|
|
218
|
-
|
|
218
|
+
- **The recorded PID is alive on this machine and looks like Node or Quilltap.** The lock is held, under any hostname and however old its heartbeat. On a Mac whose reported hostname has changed, that process is the running server, and a heartbeat can be old while it is asleep or busy.
|
|
219
|
+
- **The lock was written on this machine, under the hostname it reports now, and its process is gone.** The lock is stale at once, and the next writer (a server starting, `--write`, `optimize`, `maintenance run`, `restore-key`) claims it.
|
|
220
|
+
- **The lock was written under this hostname, and its PID is alive but is not Node or Quilltap** — typically a crash, after which the PID went to some other program. The lock is held only until its heartbeat is **five minutes** stale, then claimed like any other stale lock. `--lock-status` calls it SUSPECT until then.
|
|
221
|
+
- **The lock was written under another hostname** (a Docker container, another machine sharing the folder, or a Mac whose reported hostname has changed) and its PID cannot be confirmed here. The heartbeat decides: the lock is held until its heartbeat is **five minutes** stale.
|
|
222
|
+
|
|
223
|
+
The server writes the heartbeat every minute. If it cannot (permissions, a full disk, a synced or network volume refusing the rename), its log says so with a warning at the first failure and an error from the third in a row, because a heartbeat that stops lets the lock go stale under a live server.
|
|
224
|
+
|
|
225
|
+
`--lock-status` and `--lock-clean` are more cautious than a writer. They treat any lock with a fresh heartbeat as active, even when its process is gone, and `--lock-clean` will not remove it until the heartbeat is five minutes stale. Cleaning a *live* instance's lock is much the worse failure.
|
|
219
226
|
|
|
220
227
|
```bash
|
|
221
228
|
quilltap db --lock-status # Who holds it, and how old the heartbeat is
|
|
@@ -232,7 +239,13 @@ Wait it out, or use --lock-override to force.
|
|
|
232
239
|
|
|
233
240
|
When a live process really does hold the lock, it refuses with "Lock is held by a live Quilltap process" instead.
|
|
234
241
|
|
|
235
|
-
**`--lock-override` exists and is almost never the right answer** — it defeats the protection the lock provides. Reach for `--lock-status` first.
|
|
242
|
+
**`--lock-override` exists and is almost never the right answer** — it defeats the protection the lock provides. Reach for `--lock-status` first. It removes the lock whatever the verdict, and says which it overrode: a stale lock plainly, a held one (`active` or `suspect`) with a warning that its holder may still be writing.
|
|
243
|
+
|
|
244
|
+
When the server itself refuses to start over a held lock, its message names the remedies that work on that lock — wait for the heartbeat to go stale, stop the holder, or `--lock-override` — and not `--lock-clean`, which refuses every lock the server does.
|
|
245
|
+
|
|
246
|
+
### A damaged lock file
|
|
247
|
+
|
|
248
|
+
A crash or power loss while the lock is being created can leave `quilltap.lock` empty or half-written. The server claims such a file at start-up, with a warning in its log, once the file has sat untouched for five seconds. The CLI's writers refuse it and say it is corrupt; `quilltap db --lock-clean` removes it (also only after those five seconds, in case another process is still writing it). A lock file that exists but cannot be read at all, for example because of its permissions, is never claimed or removed: fix the permissions, or delete the file yourself once nothing is using the instance.
|
|
236
249
|
|
|
237
250
|
## Document Stores (Scriptorium)
|
|
238
251
|
|
|
@@ -292,7 +305,7 @@ The URI authority is matched name-first, then UUID, then a former name — the s
|
|
|
292
305
|
|
|
293
306
|
### `--base64` flag
|
|
294
307
|
|
|
295
|
-
`write --base64`: reads the source bytes and sends them to the server via `PUT /api/v1/mount-points/{mountId}/files/{path}` with `{content: <base64>, encoding: "base64"}`. This is the portable path the file browser uses and handles arbitrary binary files cleanly. Server-required; the direct filesystem fallback is not available with this flag.
|
|
308
|
+
`write --base64`: reads the source bytes and sends them to the server via `PUT /api/v1/mount-points/{mountId}/files/{path}` with `{content: <base64>, encoding: "base64", force}`. This is the portable path the file browser uses and handles arbitrary binary files cleanly. Like the default write, it refuses to replace an existing file (`DEST_EXISTS`, exit code 2) unless `--force` is given. A database-backed store converts bitmap images to WebP, so the file lands at a `.webp` path with the WebP's checksum; the CLI reports the stored path and does not treat the different checksum as an error, and the existing-file check applies to that stored path. Server-required; the direct filesystem fallback is not available with this flag.
|
|
296
309
|
|
|
297
310
|
`read --base64`: fetches raw bytes via `GET /api/v1/mount-points/{mountId}/files/{path}?encoding=base64` and emits the decoded bytes to stdout, suitable for binary round-trips. Server-required.
|
|
298
311
|
|
package/bin/quilltap.js
CHANGED
|
@@ -458,53 +458,27 @@ async function main() {
|
|
|
458
458
|
// Instance Lock CLI Commands
|
|
459
459
|
// ============================================================================
|
|
460
460
|
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
return /node|electron|quilltap|next-server/i.test(cmd);
|
|
483
|
-
} catch {
|
|
484
|
-
return true; // Can't read — assume match
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
if (process.platform === 'darwin') {
|
|
488
|
-
const { execSync } = require('child_process');
|
|
489
|
-
const output = execSync(`ps -p ${pid} -o comm=`, {
|
|
490
|
-
encoding: 'utf8', timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'],
|
|
491
|
-
}).trim();
|
|
492
|
-
return /node|electron|quilltap|next-server/i.test(output);
|
|
493
|
-
}
|
|
494
|
-
if (process.platform === 'win32') {
|
|
495
|
-
const { execSync } = require('child_process');
|
|
496
|
-
const output = execSync(`tasklist /FI "PID eq ${pid}" /NH`, {
|
|
497
|
-
encoding: 'utf8', timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'],
|
|
498
|
-
}).trim();
|
|
499
|
-
return /node|electron|quilltap|next-server/i.test(output);
|
|
500
|
-
}
|
|
501
|
-
return true;
|
|
502
|
-
} catch {
|
|
503
|
-
return true;
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
|
|
507
|
-
const HEARTBEAT_FRESH_MS = 5 * 60 * 1000;
|
|
461
|
+
// The lock is read and judged in ../lib/lock-helpers.js. `assessLock` there is
|
|
462
|
+
// the one predicate for "is this lock held", shared with the commands that
|
|
463
|
+
// write (`db --write`, `db optimize`, `instances restore-key`, `maintenance
|
|
464
|
+
// run`); nothing in this file probes a PID or measures a heartbeat itself.
|
|
465
|
+
//
|
|
466
|
+
// The arms below word their output from the verdict it returns (`state`,
|
|
467
|
+
// `reason`) and the facts behind it (`alive`, `isNode`, `heartbeatFresh`,
|
|
468
|
+
// ...). In one case they are more cautious than its verdict: a fresh heartbeat
|
|
469
|
+
// over a dead PID recorded under our own hostname. The verdict there is stale
|
|
470
|
+
// — the server and the writers claim such a lock at once — but `--lock-status`
|
|
471
|
+
// shows it as ACTIVE by heartbeat and `--lock-clean` refuses to remove it
|
|
472
|
+
// until the heartbeat has aged out (lock-clean-refusal.test.ts pins that
|
|
473
|
+
// wording). `--lock-override` forces whatever the verdict, and words its
|
|
474
|
+
// warning from it.
|
|
475
|
+
const {
|
|
476
|
+
HEARTBEAT_FRESH_MS,
|
|
477
|
+
CORRUPT_LOCK_SETTLE_MS,
|
|
478
|
+
assessLock,
|
|
479
|
+
readLockRecord,
|
|
480
|
+
writeLockFileAtomic,
|
|
481
|
+
} = require('../lib/lock-helpers');
|
|
508
482
|
|
|
509
483
|
/**
|
|
510
484
|
* The freshness window in words, derived from the constant the check actually
|
|
@@ -518,37 +492,6 @@ function describeFreshWindow() {
|
|
|
518
492
|
return minutes === 1 ? '1 minute' : `${minutes} minutes`;
|
|
519
493
|
}
|
|
520
494
|
|
|
521
|
-
/**
|
|
522
|
-
* Decide whether a lock record belongs to a live process.
|
|
523
|
-
*
|
|
524
|
-
* A hostname that differs from ours does NOT mean a different machine: macOS
|
|
525
|
-
* derives gethostname() dynamically when `scutil --get HostName` is unset, so
|
|
526
|
-
* one Mac reports e.g. "MacBook-Pro.local" and "Mac" at different times. So
|
|
527
|
-
* check PID liveness regardless of the recorded name, and fall back to
|
|
528
|
-
* heartbeat freshness for any environment rather than only for containers.
|
|
529
|
-
* See bug 126.
|
|
530
|
-
*/
|
|
531
|
-
function assessLock(lock, hostname) {
|
|
532
|
-
const sameHost = lock.hostname === hostname;
|
|
533
|
-
const alive = isPidAlive(lock.pid);
|
|
534
|
-
const isNode = alive ? verifyPidIsNode(lock.pid, lock.processArgv0 || '') : false;
|
|
535
|
-
const heartbeatAgeMs = lock.lastHeartbeat
|
|
536
|
-
? Date.now() - new Date(lock.lastHeartbeat).getTime()
|
|
537
|
-
: Infinity;
|
|
538
|
-
const heartbeatFresh = heartbeatAgeMs < HEARTBEAT_FRESH_MS;
|
|
539
|
-
|
|
540
|
-
return {
|
|
541
|
-
sameHost,
|
|
542
|
-
alive,
|
|
543
|
-
isNode,
|
|
544
|
-
heartbeatAgeMs,
|
|
545
|
-
heartbeatFresh,
|
|
546
|
-
// Held by something running: a confirmed local process, or any holder
|
|
547
|
-
// still refreshing its heartbeat.
|
|
548
|
-
live: (alive && isNode) || heartbeatFresh,
|
|
549
|
-
};
|
|
550
|
-
}
|
|
551
|
-
|
|
552
495
|
/**
|
|
553
496
|
* Handle --lock-status, --lock-clean, --lock-override commands.
|
|
554
497
|
*/
|
|
@@ -557,23 +500,45 @@ function handleLockCommand(dataDir, opts) {
|
|
|
557
500
|
const hostname = require('os').hostname();
|
|
558
501
|
|
|
559
502
|
// Read lock file
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
if (fs.existsSync(lockPath)) {
|
|
563
|
-
const raw = fs.readFileSync(lockPath, 'utf8');
|
|
564
|
-
lock = JSON.parse(raw);
|
|
565
|
-
}
|
|
566
|
-
} catch (err) {
|
|
503
|
+
const read = readLockRecord(lockPath);
|
|
504
|
+
if (read.state === 'corrupt') {
|
|
567
505
|
if (opts.lockStatus) {
|
|
568
506
|
console.log('Lock file exists but is corrupt or unreadable.');
|
|
569
507
|
console.log(` Path: ${lockPath}`);
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
508
|
+
}
|
|
509
|
+
// `--lock-clean` works on its own here too: it is what `db --write` tells
|
|
510
|
+
// the operator to run when it meets a corrupt lock, and it used to do
|
|
511
|
+
// nothing unless `--lock-status` came with it.
|
|
512
|
+
if (opts.lockClean) {
|
|
513
|
+
// A file that could not be read at all (permissions, an I/O error) may be
|
|
514
|
+
// a live holder's lock, so it is not ours to remove. Only a file that
|
|
515
|
+
// was read and is not a lock record is a crash's leftover.
|
|
516
|
+
if (read.error && read.error.code) {
|
|
517
|
+
console.error(`Lock file could not be read (${read.error.code}), so it will not be removed: ${lockPath}`);
|
|
518
|
+
console.error('Fix what is stopping the read, or delete the file yourself once nothing is using the instance.');
|
|
519
|
+
process.exit(1);
|
|
573
520
|
}
|
|
521
|
+
// A file written moments ago may be a lock some process is still filling
|
|
522
|
+
// in (the same grace the server gives before it claims one).
|
|
523
|
+
let ageMs = Infinity;
|
|
524
|
+
try { ageMs = Date.now() - fs.statSync(lockPath).mtimeMs; } catch { /* gone, or not ours to stat */ }
|
|
525
|
+
if (ageMs < CORRUPT_LOCK_SETTLE_MS) {
|
|
526
|
+
console.error(
|
|
527
|
+
`Lock file is corrupt but was written ${Math.round(ageMs / 1000)}s ago; another process may still be creating it.`
|
|
528
|
+
);
|
|
529
|
+
console.error(`Run --lock-clean again in a few seconds. Path: ${lockPath}`);
|
|
530
|
+
process.exit(1);
|
|
531
|
+
}
|
|
532
|
+
fs.unlinkSync(lockPath);
|
|
533
|
+
console.log(opts.lockStatus ? ' Removed corrupt lock file.' : `Removed corrupt lock file: ${lockPath}`);
|
|
534
|
+
} else if (!opts.lockStatus) {
|
|
535
|
+
console.error(`Lock file exists but is corrupt or unreadable: ${lockPath}`);
|
|
536
|
+
console.error('Remove it with `quilltap db --lock-clean` once nothing is using the instance.');
|
|
537
|
+
process.exit(1);
|
|
574
538
|
}
|
|
575
539
|
return;
|
|
576
540
|
}
|
|
541
|
+
const lock = read.state === 'ok' ? read.lock : null;
|
|
577
542
|
|
|
578
543
|
// --lock-status: display current lock state
|
|
579
544
|
if (opts.lockStatus) {
|
|
@@ -583,20 +548,24 @@ function handleLockCommand(dataDir, opts) {
|
|
|
583
548
|
return;
|
|
584
549
|
}
|
|
585
550
|
|
|
586
|
-
const { sameHost, alive, isNode, heartbeatAgeMs, heartbeatFresh } =
|
|
551
|
+
const { state, sameHost, alive, isNode, heartbeatAgeMs, heartbeatFresh } =
|
|
587
552
|
assessLock(lock, hostname);
|
|
588
553
|
|
|
589
554
|
// Status line
|
|
590
555
|
let status;
|
|
591
556
|
if (alive && isNode) {
|
|
592
557
|
status = '\x1b[32mACTIVE\x1b[0m (process confirmed running)';
|
|
558
|
+
} else if (state === 'suspect') {
|
|
559
|
+
const ageStr = Math.round(heartbeatAgeMs / 1000) + 's';
|
|
560
|
+
status = `\x1b[33mSUSPECT\x1b[0m (PID alive but does not look like Quilltap — possible PID reuse; heartbeat ${ageStr} ago)` +
|
|
561
|
+
` — will be auto-claimed once the heartbeat is ${describeFreshWindow()} stale`;
|
|
593
562
|
} else if (heartbeatFresh) {
|
|
594
563
|
const ageStr = Math.round(heartbeatAgeMs / 1000) + 's';
|
|
595
564
|
status = `\x1b[32mACTIVE\x1b[0m (${lock.environment || 'unknown'}, heartbeat ${ageStr} ago)`;
|
|
596
|
-
} else if (alive && !isNode) {
|
|
597
|
-
status = '\x1b[33mSUSPECT\x1b[0m (PID alive but does not look like Quilltap — possible PID reuse)';
|
|
598
565
|
} else if (!sameHost) {
|
|
599
566
|
status = `\x1b[33mSTALE (${lock.environment || 'unknown'} on ${lock.hostname}, no recent heartbeat)\x1b[0m — will be auto-claimed on next startup`;
|
|
567
|
+
} else if (alive) {
|
|
568
|
+
status = '\x1b[33mSTALE (PID alive but does not look like Quilltap, and no recent heartbeat — PID reused)\x1b[0m — will be auto-claimed on next startup';
|
|
600
569
|
} else {
|
|
601
570
|
status = '\x1b[31mSTALE (process dead)\x1b[0m — will be auto-claimed on next startup';
|
|
602
571
|
}
|
|
@@ -623,8 +592,10 @@ function handleLockCommand(dataDir, opts) {
|
|
|
623
592
|
} else {
|
|
624
593
|
heartbeatDisplay = `${Math.round(heartbeatAge / 3600)}h ago`;
|
|
625
594
|
}
|
|
626
|
-
// Warn if heartbeat is older than
|
|
627
|
-
|
|
595
|
+
// Warn if a Quilltap-shaped holder's heartbeat is older than the
|
|
596
|
+
// freshness window (process may be hung). A PID that is not Quilltap's
|
|
597
|
+
// is a reused one, not a hung server.
|
|
598
|
+
if (alive && isNode && heartbeatAge > Math.round(HEARTBEAT_FRESH_MS / 1000)) {
|
|
628
599
|
heartbeatDisplay = `\x1b[33m${heartbeatDisplay} (stale — process may be hung)\x1b[0m`;
|
|
629
600
|
}
|
|
630
601
|
console.log(` Heartbeat: ${heartbeatDisplay}`);
|
|
@@ -694,9 +665,11 @@ function handleLockCommand(dataDir, opts) {
|
|
|
694
665
|
detail: `Cleaned via CLI (quilltap db --lock-clean)`,
|
|
695
666
|
});
|
|
696
667
|
|
|
697
|
-
// Write final state then remove
|
|
668
|
+
// Write final state then remove. Replaced whole, never rewritten in place:
|
|
669
|
+
// a lock file caught half-written reads as a crash leftover to a server
|
|
670
|
+
// starting at that moment.
|
|
698
671
|
try {
|
|
699
|
-
|
|
672
|
+
writeLockFileAtomic(lockPath, lock);
|
|
700
673
|
} catch { /* best effort */ }
|
|
701
674
|
|
|
702
675
|
try {
|
|
@@ -709,27 +682,32 @@ function handleLockCommand(dataDir, opts) {
|
|
|
709
682
|
return;
|
|
710
683
|
}
|
|
711
684
|
|
|
712
|
-
// --lock-override:
|
|
685
|
+
// --lock-override: remove the lock whatever its verdict
|
|
713
686
|
if (opts.lockOverride) {
|
|
714
687
|
if (!lock) {
|
|
715
688
|
console.log('No lock file found. Nothing to override.');
|
|
716
689
|
return;
|
|
717
690
|
}
|
|
718
691
|
|
|
719
|
-
|
|
720
|
-
|
|
692
|
+
// Override forces whatever the verdict. The verdict — the same one the
|
|
693
|
+
// server and the writers act on — only chooses what it warns about.
|
|
694
|
+
const { state, reason, alive, isNode, heartbeatAgeMs } = assessLock(lock, hostname);
|
|
721
695
|
|
|
722
|
-
if (
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
console.
|
|
727
|
-
process.exit(1);
|
|
696
|
+
if (state === 'active') {
|
|
697
|
+
if (alive && isNode) {
|
|
698
|
+
console.log(`WARNING: Overriding lock held by live process (PID ${lock.pid}, ${lock.environment || 'unknown'}).`);
|
|
699
|
+
} else {
|
|
700
|
+
console.log(`WARNING: Overriding a lock that is still held — ${reason}.`);
|
|
728
701
|
}
|
|
729
|
-
console.log(`WARNING: Overriding lock held by live process (PID ${lock.pid}, ${lock.environment || 'unknown'}).`);
|
|
730
702
|
console.log('The other instance may corrupt the database if it is still writing.');
|
|
703
|
+
} else if (state === 'suspect') {
|
|
704
|
+
console.log(
|
|
705
|
+
`WARNING: Overriding a lock whose PID ${lock.pid} is alive but does not look like a Quilltap process, ` +
|
|
706
|
+
`with a heartbeat only ${Math.round(heartbeatAgeMs / 1000)}s old.`
|
|
707
|
+
);
|
|
708
|
+
console.log('The PID has probably been reused, but if a Quilltap instance is still writing, it may corrupt the database.');
|
|
731
709
|
} else {
|
|
732
|
-
console.log(`Overriding stale lock (
|
|
710
|
+
console.log(`Overriding stale lock (${reason}).`);
|
|
733
711
|
}
|
|
734
712
|
|
|
735
713
|
// Record override in history
|
|
@@ -739,13 +717,13 @@ function handleLockCommand(dataDir, opts) {
|
|
|
739
717
|
pid: process.pid,
|
|
740
718
|
hostname: hostname,
|
|
741
719
|
timestamp: new Date().toISOString(),
|
|
742
|
-
detail: `Manual override via CLI (quilltap db --lock-override)` +
|
|
743
|
-
(
|
|
720
|
+
detail: `Manual override via CLI (quilltap db --lock-override) — ` +
|
|
721
|
+
(state === 'stale' ? `stale: ${reason}` : `overriding a held lock (${state}): ${reason}`),
|
|
744
722
|
});
|
|
745
723
|
|
|
746
724
|
// Write final state then remove so next startup gets a clean acquire
|
|
747
725
|
try {
|
|
748
|
-
|
|
726
|
+
writeLockFileAtomic(lockPath, lock);
|
|
749
727
|
} catch { /* best effort */ }
|
|
750
728
|
|
|
751
729
|
try {
|
|
@@ -850,7 +828,7 @@ Low-level options (legacy; still supported):
|
|
|
850
828
|
Instance Lock Commands:
|
|
851
829
|
--lock-status Show the current instance lock state
|
|
852
830
|
--lock-clean Remove stale locks (dead processes only)
|
|
853
|
-
--lock-override
|
|
831
|
+
--lock-override Remove the lock even if it is still held (warns first)
|
|
854
832
|
|
|
855
833
|
If a passphrase is required and not provided via --passphrase, the tool
|
|
856
834
|
will check the QUILLTAP_DB_PASSPHRASE environment variable, then prompt
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `quilltap docs write --base64` and `docs delete` against the item route
|
|
3
|
+
* (#396, #397).
|
|
4
|
+
*
|
|
5
|
+
* The server is a stubbed `fetch`; the mount-index database is a stub that
|
|
6
|
+
* knows one store. What is pinned:
|
|
7
|
+
* - DEST_EXISTS from the server exits 2 (as the non-base64 path does);
|
|
8
|
+
* - `--force` is sent as `force: true`;
|
|
9
|
+
* - a bitmap the server transcoded (stored path differs, sha is of the
|
|
10
|
+
* stored bytes) is a success, not a "Checksum mismatch";
|
|
11
|
+
* - a sha mismatch at the path we asked for is still an error;
|
|
12
|
+
* - `delete` on a path the server answers 404 for is a no-op, not a failure.
|
|
13
|
+
*
|
|
14
|
+
* @jest-environment node
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
'use strict';
|
|
18
|
+
|
|
19
|
+
const fs = require('fs');
|
|
20
|
+
const os = require('os');
|
|
21
|
+
const path = require('path');
|
|
22
|
+
const crypto = require('crypto');
|
|
23
|
+
|
|
24
|
+
const MOUNT_ID = '11111111-2222-3333-4444-555555555555';
|
|
25
|
+
|
|
26
|
+
jest.mock('../db-helpers', () => ({
|
|
27
|
+
resolveDataDirAndPassphrase: () => ({ dataDir: '/nowhere', passphrase: '' }),
|
|
28
|
+
printDefaultInstanceHint: () => {},
|
|
29
|
+
loadDbKey: async () => 'pepper',
|
|
30
|
+
openMountIndexDb: () => ({
|
|
31
|
+
prepare: (sql) => ({
|
|
32
|
+
get: () => (/sqlite_master/.test(sql) ? { ok: 1 } : { id: '11111111-2222-3333-4444-555555555555', name: 'Lore', mountType: 'database' }),
|
|
33
|
+
all: () => [],
|
|
34
|
+
}),
|
|
35
|
+
close: () => {},
|
|
36
|
+
}),
|
|
37
|
+
findMountByFormerName: () => null,
|
|
38
|
+
}));
|
|
39
|
+
|
|
40
|
+
const { docsCommand } = require('../docs-commands');
|
|
41
|
+
|
|
42
|
+
let tmpDir;
|
|
43
|
+
let stdout;
|
|
44
|
+
let stderr;
|
|
45
|
+
let exitCodes;
|
|
46
|
+
|
|
47
|
+
function fetchStub(status, body) {
|
|
48
|
+
const calls = [];
|
|
49
|
+
global.fetch = jest.fn(async (url, init) => {
|
|
50
|
+
calls.push({ url, init });
|
|
51
|
+
return { ok: status >= 200 && status < 300, status, json: async () => body };
|
|
52
|
+
});
|
|
53
|
+
return calls;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function run(args) {
|
|
57
|
+
try {
|
|
58
|
+
await docsCommand(args);
|
|
59
|
+
return null;
|
|
60
|
+
} catch (e) {
|
|
61
|
+
return e;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
beforeEach(() => {
|
|
66
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'docs-write-'));
|
|
67
|
+
stdout = [];
|
|
68
|
+
stderr = [];
|
|
69
|
+
exitCodes = [];
|
|
70
|
+
jest.spyOn(console, 'log').mockImplementation((...a) => { stdout.push(a.join(' ')); });
|
|
71
|
+
jest.spyOn(console, 'error').mockImplementation((...a) => { stderr.push(a.join(' ')); });
|
|
72
|
+
jest.spyOn(process.stdout, 'write').mockImplementation((s) => { stdout.push(String(s)); return true; });
|
|
73
|
+
jest.spyOn(process, 'exit').mockImplementation((code) => { exitCodes.push(code); throw new Error(`exit:${code}`); });
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
afterEach(() => {
|
|
77
|
+
jest.restoreAllMocks();
|
|
78
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
79
|
+
delete global.fetch;
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
describe('docs write --base64', () => {
|
|
83
|
+
it('exits 2 when the server refuses an existing destination', async () => {
|
|
84
|
+
const src = path.join(tmpDir, 'draft.md');
|
|
85
|
+
fs.writeFileSync(src, 'new');
|
|
86
|
+
fetchStub(409, { error: 'Destination already exists: today.md. Use force to overwrite.', code: 'DEST_EXISTS' });
|
|
87
|
+
const err = await run(['write', '--base64', MOUNT_ID, 'today.md', src]);
|
|
88
|
+
// process.exit is the real thing's last word; the stub throws, so only the
|
|
89
|
+
// first code is the command's own.
|
|
90
|
+
expect(exitCodes[0]).toBe(2);
|
|
91
|
+
expect(stderr.join('\n')).toContain('Destination already exists');
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('sends force: true with --force', async () => {
|
|
95
|
+
const src = path.join(tmpDir, 'draft.md');
|
|
96
|
+
fs.writeFileSync(src, 'new');
|
|
97
|
+
const sha = crypto.createHash('sha256').update('new').digest('hex');
|
|
98
|
+
const calls = fetchStub(200, { relativePath: 'today.md', sha256: sha, sizeBytes: 3 });
|
|
99
|
+
await run(['write', '--base64', '--force', MOUNT_ID, 'today.md', src]);
|
|
100
|
+
expect(JSON.parse(calls[0].init.body)).toMatchObject({ encoding: 'base64', force: true });
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('sends force: false without it', async () => {
|
|
104
|
+
const src = path.join(tmpDir, 'draft.md');
|
|
105
|
+
fs.writeFileSync(src, 'new');
|
|
106
|
+
const sha = crypto.createHash('sha256').update('new').digest('hex');
|
|
107
|
+
const calls = fetchStub(200, { relativePath: 'today.md', sha256: sha, sizeBytes: 3 });
|
|
108
|
+
await run(['write', '--base64', MOUNT_ID, 'today.md', src]);
|
|
109
|
+
expect(JSON.parse(calls[0].init.body).force).toBe(false);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it('treats a transcoded bitmap (stored path and sha differ) as a success', async () => {
|
|
113
|
+
const src = path.join(tmpDir, 'pic.png');
|
|
114
|
+
fs.writeFileSync(src, 'png-bytes');
|
|
115
|
+
fetchStub(200, { relativePath: 'art/pic.webp', sha256: 'f'.repeat(64), sizeBytes: 5 });
|
|
116
|
+
const err = await run(['write', '--base64', MOUNT_ID, 'art/pic.png', src]);
|
|
117
|
+
expect(err).toBeNull();
|
|
118
|
+
expect(stderr.join('\n')).not.toContain('Checksum mismatch');
|
|
119
|
+
expect(stdout.join('\n')).toContain('art/pic.webp');
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it('flags a transcode in --json output', async () => {
|
|
123
|
+
const src = path.join(tmpDir, 'pic.png');
|
|
124
|
+
fs.writeFileSync(src, 'png-bytes');
|
|
125
|
+
fetchStub(200, { relativePath: 'pic.webp', sha256: 'f'.repeat(64), sizeBytes: 5 });
|
|
126
|
+
await run(['write', '--base64', '--json', MOUNT_ID, 'pic.png', src]);
|
|
127
|
+
const out = JSON.parse(stdout.join(''));
|
|
128
|
+
expect(out.transcoded).toBe(true);
|
|
129
|
+
expect(out.relativePath).toBe('pic.webp');
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it('still fails a sha mismatch at the path it asked for', async () => {
|
|
133
|
+
const src = path.join(tmpDir, 'draft.md');
|
|
134
|
+
fs.writeFileSync(src, 'new');
|
|
135
|
+
fetchStub(200, { relativePath: 'today.md', sha256: 'e'.repeat(64), sizeBytes: 3 });
|
|
136
|
+
const err = await run(['write', '--base64', MOUNT_ID, 'today.md', src]);
|
|
137
|
+
expect(exitCodes[0]).toBe(1);
|
|
138
|
+
expect(stderr.join('\n')).toContain('Checksum mismatch');
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
describe('docs delete', () => {
|
|
143
|
+
it('treats the server\'s 404 as the no-op it has always been', async () => {
|
|
144
|
+
fetchStub(404, { error: 'File not found' });
|
|
145
|
+
const err = await run(['delete', MOUNT_ID, 'gone.md']);
|
|
146
|
+
expect(err).toBeNull();
|
|
147
|
+
expect(stdout.join('\n')).toContain('did not exist');
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it('still fails on other errors', async () => {
|
|
151
|
+
fetchStub(500, { error: 'boom' });
|
|
152
|
+
const err = await run(['delete', MOUNT_ID, 'a.md']);
|
|
153
|
+
expect(exitCodes[0]).toBe(1);
|
|
154
|
+
});
|
|
155
|
+
});
|
package/lib/db-commands.js
CHANGED
|
@@ -15,7 +15,7 @@ const {
|
|
|
15
15
|
resolveChat,
|
|
16
16
|
resolveProject,
|
|
17
17
|
} = require('./db-helpers');
|
|
18
|
-
const { getLockStatus } = require('./lock-helpers');
|
|
18
|
+
const { getLockStatus, HEARTBEAT_FRESH_MS } = require('./lock-helpers');
|
|
19
19
|
const { decodeText } = require('./text-codec');
|
|
20
20
|
|
|
21
21
|
// Tables grouped by domain for `db schema` (with-no-arg) overview, and for
|
|
@@ -1398,9 +1398,9 @@ function cmdOptimize(args, ctx) {
|
|
|
1398
1398
|
? `Database is currently in use — ${lockStatus.reason}.\n` +
|
|
1399
1399
|
`Stop the running Quilltap instance before optimizing, then try again.\n` +
|
|
1400
1400
|
`(See \`quilltap db --lock-status\` for details.)`
|
|
1401
|
-
: `
|
|
1402
|
-
`
|
|
1403
|
-
|
|
1401
|
+
: `Database lock looks suspect — ${lockStatus.reason}.\n` +
|
|
1402
|
+
`Its PID may have been reused since a crash. The lock is claimed automatically once its\n` +
|
|
1403
|
+
`heartbeat is ${Math.round(HEARTBEAT_FRESH_MS / 60000)} minutes old; try again then. (See \`quilltap db --lock-status\` for details.)`;
|
|
1404
1404
|
const err = new Error(msg);
|
|
1405
1405
|
err.locked = true;
|
|
1406
1406
|
throw err;
|
package/lib/docs-commands.js
CHANGED
|
@@ -23,6 +23,14 @@ const CYAN = '\x1b[36m';
|
|
|
23
23
|
const TEXT_FILE_TYPES = new Set(['markdown', 'txt', 'json', 'jsonl']);
|
|
24
24
|
const BINARY_FILE_TYPES = new Set(['pdf', 'docx', 'blob']);
|
|
25
25
|
|
|
26
|
+
// Where a link's bytes live, as the server's link projection reports it: a link
|
|
27
|
+
// in a database-backed store reads from the database whatever its content row
|
|
28
|
+
// says. A content row is shared by every link to the same bytes, and one
|
|
29
|
+
// written before 4.16 can say `filesystem` under a database store's link
|
|
30
|
+
// (#398), so `f.source` alone is not to be trusted.
|
|
31
|
+
const LINK_SOURCE_SQL = `(CASE WHEN (SELECT mp.mountType FROM doc_mount_points mp WHERE mp.id = l.mountPointId) = 'database'
|
|
32
|
+
THEN 'database' ELSE f.source END) AS source`;
|
|
33
|
+
|
|
26
34
|
// Single-character markers for the `ls` "text" column:
|
|
27
35
|
// = raw bytes are already textual (markdown/txt/json/jsonl)
|
|
28
36
|
// T separately-extracted plaintext is stored on the link row
|
|
@@ -665,7 +673,7 @@ async function handleFiles(flags, id) {
|
|
|
665
673
|
if (flags.folder) {
|
|
666
674
|
const prefix = flags.folder.replace(/\/+$/, '') + '/';
|
|
667
675
|
rows = db.prepare(`
|
|
668
|
-
SELECT l.relativePath, f.fileType,
|
|
676
|
+
SELECT l.relativePath, f.fileType, ${LINK_SOURCE_SQL}, f.fileSizeBytes,
|
|
669
677
|
l.chunkCount, l.conversionStatus
|
|
670
678
|
FROM doc_mount_file_links l
|
|
671
679
|
JOIN doc_mount_files f ON f.id = l.fileId
|
|
@@ -674,7 +682,7 @@ async function handleFiles(flags, id) {
|
|
|
674
682
|
`).all(mount.id, prefix + '%');
|
|
675
683
|
} else {
|
|
676
684
|
rows = db.prepare(`
|
|
677
|
-
SELECT l.relativePath, f.fileType,
|
|
685
|
+
SELECT l.relativePath, f.fileType, ${LINK_SOURCE_SQL}, f.fileSizeBytes,
|
|
678
686
|
l.chunkCount, l.conversionStatus
|
|
679
687
|
FROM doc_mount_file_links l
|
|
680
688
|
JOIN doc_mount_files f ON f.id = l.fileId
|
|
@@ -761,7 +769,7 @@ function lsFileColumns(db) {
|
|
|
761
769
|
${linkGroupId} AS linkGroupId,
|
|
762
770
|
l.id AS linkId, l.fileId, l.relativePath, l.fileName, l.lastModified,
|
|
763
771
|
l.extractionStatus, l.extractedTextSha256, l.chunkCount,
|
|
764
|
-
f.fileType, f.fileSizeBytes,
|
|
772
|
+
f.fileType, f.fileSizeBytes, ${LINK_SOURCE_SQL}, f.sha256,
|
|
765
773
|
${linkCount} AS linkCount,
|
|
766
774
|
(SELECT COUNT(*) FROM doc_mount_chunks
|
|
767
775
|
WHERE linkId = l.id AND embedding IS NOT NULL) AS embeddedChunkCount
|
|
@@ -1388,7 +1396,7 @@ async function handleRead(flags, id, relativePath) {
|
|
|
1388
1396
|
|
|
1389
1397
|
function readRaw(db, mount, relativePath, flags) {
|
|
1390
1398
|
const file = db.prepare(`
|
|
1391
|
-
SELECT l.fileId,
|
|
1399
|
+
SELECT l.fileId, ${LINK_SOURCE_SQL}, f.fileType
|
|
1392
1400
|
FROM doc_mount_file_links l
|
|
1393
1401
|
JOIN doc_mount_files f ON f.id = l.fileId
|
|
1394
1402
|
WHERE l.mountPointId = ? AND l.relativePath = ?
|
|
@@ -1448,7 +1456,7 @@ function readRendered(db, mount, relativePath) {
|
|
|
1448
1456
|
// 1. Look up the link row (it carries extractedText now).
|
|
1449
1457
|
const file = db.prepare(`
|
|
1450
1458
|
SELECT l.id AS linkId, l.fileId, l.extractedText,
|
|
1451
|
-
|
|
1459
|
+
${LINK_SOURCE_SQL}, f.fileType
|
|
1452
1460
|
FROM doc_mount_file_links l
|
|
1453
1461
|
JOIN doc_mount_files f ON f.id = l.fileId
|
|
1454
1462
|
WHERE l.mountPointId = ? AND l.relativePath = ?
|
|
@@ -1529,7 +1537,7 @@ async function handleExport(flags, id, outputDir) {
|
|
|
1529
1537
|
const mount = requireMount(db, id);
|
|
1530
1538
|
|
|
1531
1539
|
const files = db.prepare(`
|
|
1532
|
-
SELECT l.fileId, l.relativePath,
|
|
1540
|
+
SELECT l.fileId, l.relativePath, ${LINK_SOURCE_SQL}, f.fileType
|
|
1533
1541
|
FROM doc_mount_file_links l
|
|
1534
1542
|
JOIN doc_mount_files f ON f.id = l.fileId
|
|
1535
1543
|
WHERE l.mountPointId = ?
|
|
@@ -1821,15 +1829,22 @@ async function handleWrite(flags, positional) {
|
|
|
1821
1829
|
process.exit(http.code === 'DEST_EXISTS' ? 2 : 1);
|
|
1822
1830
|
}
|
|
1823
1831
|
const r = http.result;
|
|
1824
|
-
|
|
1832
|
+
// A database-backed store transcodes bitmaps to WebP, so it reports a
|
|
1833
|
+
// different stored path and the sha256 of the stored bytes. That is the
|
|
1834
|
+
// store doing its job, not corruption: only a mismatch at the path we
|
|
1835
|
+
// asked for is one.
|
|
1836
|
+
const storedPath = r.relativePath ?? relativePath;
|
|
1837
|
+
const transcoded = storedPath.replace(/^\/+/, '') !== relativePath.replace(/^\/+/, '');
|
|
1838
|
+
if (r.sha256 !== sourceSha && !transcoded) {
|
|
1825
1839
|
console.error(`Checksum mismatch: source ${sourceSha} != dest ${r.sha256}`);
|
|
1826
1840
|
process.exit(1);
|
|
1827
1841
|
}
|
|
1828
1842
|
if (flags.json) {
|
|
1829
|
-
process.stdout.write(JSON.stringify({ ...r, sourceSha256: sourceSha }, null, 2) + '\n');
|
|
1843
|
+
process.stdout.write(JSON.stringify({ ...r, sourceSha256: sourceSha, transcoded }, null, 2) + '\n');
|
|
1830
1844
|
return;
|
|
1831
1845
|
}
|
|
1832
|
-
|
|
1846
|
+
const note = transcoded ? ` ${DIM}[stored as ${storedPath}; the store converted it]${RESET}` : '';
|
|
1847
|
+
console.log(`${GREEN}Wrote${RESET} ${mount.name}:${storedPath} (${formatBytes(r.sizeBytes)}, sha=${r.sha256.slice(0, 12)}…)${note}`);
|
|
1833
1848
|
return;
|
|
1834
1849
|
}
|
|
1835
1850
|
|
|
@@ -1924,6 +1939,17 @@ async function handleDelete(flags, positional) {
|
|
|
1924
1939
|
|
|
1925
1940
|
const http = await deleteViaHttp(flags.port, mount.id, relativePath);
|
|
1926
1941
|
if (http.reachable) {
|
|
1942
|
+
if (!http.ok && http.status === 404) {
|
|
1943
|
+
// The server answers 404 for a path that holds nothing; for the CLI that
|
|
1944
|
+
// is still the no-op it has always been.
|
|
1945
|
+
const r = { deleted: false, mountPointId: mount.id, path: relativePath };
|
|
1946
|
+
if (flags.json) {
|
|
1947
|
+
process.stdout.write(JSON.stringify(r, null, 2) + '\n');
|
|
1948
|
+
return;
|
|
1949
|
+
}
|
|
1950
|
+
console.log(`${DIM}No-op${RESET} ${mount.name}:${relativePath} (did not exist)`);
|
|
1951
|
+
return;
|
|
1952
|
+
}
|
|
1927
1953
|
if (!http.ok) {
|
|
1928
1954
|
console.error(`Delete failed: ${http.error}`);
|
|
1929
1955
|
process.exit(1);
|
|
@@ -2630,7 +2656,7 @@ async function handleGrep(flags, positional) {
|
|
|
2630
2656
|
|
|
2631
2657
|
const linksByMount = db.prepare(`
|
|
2632
2658
|
SELECT l.id AS linkId, l.fileId, l.relativePath, l.extractedText,
|
|
2633
|
-
|
|
2659
|
+
${LINK_SOURCE_SQL}, f.fileType
|
|
2634
2660
|
FROM doc_mount_file_links l
|
|
2635
2661
|
JOIN doc_mount_files f ON f.id = l.fileId
|
|
2636
2662
|
WHERE l.mountPointId = ?
|
package/lib/lock-helpers.js
CHANGED
|
@@ -1,13 +1,46 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const crypto = require('crypto');
|
|
3
4
|
const fs = require('fs');
|
|
4
5
|
const os = require('os');
|
|
5
6
|
const path = require('path');
|
|
6
|
-
const {
|
|
7
|
+
const { execFileSync } = require('child_process');
|
|
7
8
|
|
|
9
|
+
// ============================================================================
|
|
10
|
+
// Is this lock held?
|
|
11
|
+
//
|
|
12
|
+
// One predicate answers that for the whole CLI: the writers (`db --write`,
|
|
13
|
+
// `db optimize`, `instances restore-key`, `maintenance run`) through
|
|
14
|
+
// getLockStatus(), and `db --lock-status` / `--lock-clean` / `--lock-override`
|
|
15
|
+
// through assessLock() directly. It mirrors the server's own decision in
|
|
16
|
+
// lib/database/backends/sqlite/instance-lock.ts (decideLockClaim), which this
|
|
17
|
+
// plain-JS package cannot import. So that the two cannot drift, both are run
|
|
18
|
+
// against one table of cases:
|
|
19
|
+
// __tests__/unit/lib/database/instance-lock-verdicts.fixture.json.
|
|
20
|
+
//
|
|
21
|
+
// A hostname that differs from ours does NOT mean a different machine. macOS
|
|
22
|
+
// derives gethostname() dynamically when `scutil --get HostName` is unset, so
|
|
23
|
+
// one Mac reports e.g. "MacBook-Pro.local" and "Mac" at different times (bug
|
|
24
|
+
// 126). Reading "different hostname" as "someone else's dead lock" is how a
|
|
25
|
+
// writer came to open the database beside a running server.
|
|
26
|
+
// ============================================================================
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* How long a lock's heartbeat may go unrefreshed before its holder is presumed
|
|
30
|
+
* gone. Must equal HEARTBEAT_FRESH_MS in the server's instance-lock.ts; the
|
|
31
|
+
* shared verdict table pins both.
|
|
32
|
+
*/
|
|
8
33
|
const HEARTBEAT_FRESH_MS = 5 * 60 * 1000;
|
|
9
|
-
const VM_ENVIRONMENTS = new Set(['docker']);
|
|
10
34
|
|
|
35
|
+
/**
|
|
36
|
+
* How long a lock file that is not a lock record must have sat untouched
|
|
37
|
+
* before it may be removed as a crash's leftover. A writer that creates the
|
|
38
|
+
* file and then fills it in leaves it empty for an instant. Equals
|
|
39
|
+
* CORRUPT_LOCK_SETTLE_MS in the server's instance-lock.ts.
|
|
40
|
+
*/
|
|
41
|
+
const CORRUPT_LOCK_SETTLE_MS = 5000;
|
|
42
|
+
|
|
43
|
+
/** Check whether a PID is alive using signal 0. EPERM means it exists. */
|
|
11
44
|
function isPidAlive(pid) {
|
|
12
45
|
try {
|
|
13
46
|
process.kill(pid, 0);
|
|
@@ -17,28 +50,27 @@ function isPidAlive(pid) {
|
|
|
17
50
|
}
|
|
18
51
|
}
|
|
19
52
|
|
|
53
|
+
/** Command names a Quilltap server runs under; the server's probe uses the same. */
|
|
54
|
+
const QUILLTAP_PROCESS_PATTERN = /node|electron|quilltap|next-server/i;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Does this PID look like a Node/Quilltap process (best effort)? Conservative:
|
|
58
|
+
* answers true whenever it cannot tell. The server's copy is
|
|
59
|
+
* `pidLooksLikeNode` in lib/database/backends/sqlite/instance-lock.ts.
|
|
60
|
+
*/
|
|
20
61
|
function verifyPidIsNode(pid) {
|
|
62
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
63
|
+
const probe = { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'pipe'] };
|
|
21
64
|
try {
|
|
22
65
|
if (process.platform === 'linux') {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const cmd = cmdline.split('\0')[0] || '';
|
|
26
|
-
return /node|electron|quilltap|next-server/i.test(cmd);
|
|
27
|
-
} catch {
|
|
28
|
-
return true;
|
|
29
|
-
}
|
|
66
|
+
const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
|
|
67
|
+
return QUILLTAP_PROCESS_PATTERN.test(cmdline.split('\0')[0] || '');
|
|
30
68
|
}
|
|
31
69
|
if (process.platform === 'darwin') {
|
|
32
|
-
|
|
33
|
-
encoding: 'utf8', timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'],
|
|
34
|
-
}).trim();
|
|
35
|
-
return /node|electron|quilltap|next-server/i.test(output);
|
|
70
|
+
return QUILLTAP_PROCESS_PATTERN.test(execFileSync('ps', ['-p', String(pid), '-o', 'comm='], probe).trim());
|
|
36
71
|
}
|
|
37
72
|
if (process.platform === 'win32') {
|
|
38
|
-
|
|
39
|
-
encoding: 'utf8', timeout: 2000, stdio: ['pipe', 'pipe', 'pipe'],
|
|
40
|
-
}).trim();
|
|
41
|
-
return /node|electron|quilltap|next-server/i.test(output);
|
|
73
|
+
return QUILLTAP_PROCESS_PATTERN.test(execFileSync('tasklist', ['/FI', `PID eq ${pid}`, '/NH'], probe).trim());
|
|
42
74
|
}
|
|
43
75
|
return true;
|
|
44
76
|
} catch {
|
|
@@ -46,68 +78,143 @@ function verifyPidIsNode(pid) {
|
|
|
46
78
|
}
|
|
47
79
|
}
|
|
48
80
|
|
|
81
|
+
/**
|
|
82
|
+
* THE predicate. Pure: every fact about the outside world comes in as an
|
|
83
|
+
* argument, which is what lets the shared verdict table drive it.
|
|
84
|
+
*
|
|
85
|
+
* The rule, which is the server's, case for case:
|
|
86
|
+
* - The PID is alive here and looks like Node/Quilltap: active, under any
|
|
87
|
+
* hostname and however old the heartbeat. On a Mac whose hostname has
|
|
88
|
+
* flipped that PID is the running server, and a heartbeat can be old while
|
|
89
|
+
* the process is asleep or busy.
|
|
90
|
+
* - Same hostname, PID dead: stale at once, whatever the heartbeat says.
|
|
91
|
+
* - Same hostname, PID alive but not Node/Quilltap: the PID has most likely
|
|
92
|
+
* been reused since a crash. `suspect` (held) while the heartbeat is
|
|
93
|
+
* fresh, stale once it is not.
|
|
94
|
+
* - Different hostname otherwise: held while the heartbeat is fresh, in ANY
|
|
95
|
+
* environment, not only Docker.
|
|
96
|
+
*
|
|
97
|
+
|
|
98
|
+
* @param {object} lock The parsed lock record.
|
|
99
|
+
* @param {{ hostname: string, pidAlive: boolean, looksLikeNode: boolean, now: number }} facts
|
|
100
|
+
* `hostname` is the name this machine reports now; `pidAlive` whether
|
|
101
|
+
* lock.pid exists here; `looksLikeNode` whether that process looks like
|
|
102
|
+
* Node/Quilltap (ignored when the PID is dead); `now` in epoch ms.
|
|
103
|
+
* @returns {{ state: 'active'|'suspect'|'stale', reason: string, sameHost: boolean,
|
|
104
|
+
* alive: boolean, isNode: boolean, heartbeatAgeMs: number, heartbeatFresh: boolean }}
|
|
105
|
+
* A writer may claim the lock only when `state` is 'stale'.
|
|
106
|
+
*/
|
|
107
|
+
function assessLockRecord(lock, { hostname, pidAlive, looksLikeNode, now }) {
|
|
108
|
+
const sameHost = lock.hostname === hostname;
|
|
109
|
+
const alive = Boolean(pidAlive);
|
|
110
|
+
const isNode = alive && Boolean(looksLikeNode);
|
|
111
|
+
const heartbeatAgeMs = lock.lastHeartbeat
|
|
112
|
+
? now - new Date(lock.lastHeartbeat).getTime()
|
|
113
|
+
: Infinity;
|
|
114
|
+
const heartbeatFresh = heartbeatAgeMs < HEARTBEAT_FRESH_MS;
|
|
115
|
+
const verdict = (state, reason) => ({
|
|
116
|
+
state, reason, sameHost, alive, isNode, heartbeatAgeMs, heartbeatFresh,
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
if (sameHost) {
|
|
120
|
+
if (!alive) {
|
|
121
|
+
return verdict('stale', `PID ${lock.pid} is no longer running`);
|
|
122
|
+
}
|
|
123
|
+
if (isNode) {
|
|
124
|
+
return verdict('active', `held by PID ${lock.pid} on this host`);
|
|
125
|
+
}
|
|
126
|
+
if (heartbeatFresh) {
|
|
127
|
+
return verdict(
|
|
128
|
+
'suspect',
|
|
129
|
+
`PID ${lock.pid} is alive but does not look like a Quilltap process, and its heartbeat is still fresh`,
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
return verdict(
|
|
133
|
+
'stale',
|
|
134
|
+
`PID ${lock.pid} is alive but does not look like a Quilltap process, and the lock has no recent heartbeat — the PID has been reused`,
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (isNode) {
|
|
139
|
+
return verdict(
|
|
140
|
+
'active',
|
|
141
|
+
`held by PID ${lock.pid}, which is alive on this machine (the lock was recorded under hostname ${lock.hostname})`,
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
if (heartbeatFresh) {
|
|
145
|
+
const ageStr = Math.round(heartbeatAgeMs / 1000) + 's';
|
|
146
|
+
return verdict(
|
|
147
|
+
'active',
|
|
148
|
+
`held by ${lock.environment || 'unknown'} instance on ${lock.hostname} (heartbeat ${ageStr} ago)`,
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
return verdict('stale', `held by ${lock.hostname} but no recent heartbeat`);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The predicate applied to this machine, now: probes the PID and reads the
|
|
156
|
+
* clock, then defers to assessLockRecord(). The PID is probed whatever
|
|
157
|
+
* hostname the lock records.
|
|
158
|
+
*/
|
|
159
|
+
function assessLock(lock, hostname = os.hostname()) {
|
|
160
|
+
const pidAlive = isPidAlive(lock.pid);
|
|
161
|
+
const looksLikeNode = pidAlive ? verifyPidIsNode(lock.pid) : false;
|
|
162
|
+
return assessLockRecord(lock, { hostname, pidAlive, looksLikeNode, now: Date.now() });
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Read the lock file.
|
|
167
|
+
*
|
|
168
|
+
* @returns {{ state: 'absent' } | { state: 'corrupt', error: Error } | { state: 'ok', lock: object }}
|
|
169
|
+
* `corrupt` covers a file that cannot be read and one that is not a JSON
|
|
170
|
+
* object; either way nothing here may be taken for "no lock".
|
|
171
|
+
*/
|
|
172
|
+
function readLockRecord(lockPath) {
|
|
173
|
+
let raw;
|
|
174
|
+
try {
|
|
175
|
+
raw = fs.readFileSync(lockPath, 'utf8');
|
|
176
|
+
} catch (err) {
|
|
177
|
+
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return { state: 'absent' };
|
|
178
|
+
return { state: 'corrupt', error: err };
|
|
179
|
+
}
|
|
180
|
+
let lock;
|
|
181
|
+
try {
|
|
182
|
+
lock = JSON.parse(raw);
|
|
183
|
+
} catch (err) {
|
|
184
|
+
return { state: 'corrupt', error: err };
|
|
185
|
+
}
|
|
186
|
+
if (lock === null || typeof lock !== 'object' || Array.isArray(lock)) {
|
|
187
|
+
return { state: 'corrupt', error: new Error('lock file is not a JSON object') };
|
|
188
|
+
}
|
|
189
|
+
return { state: 'ok', lock };
|
|
190
|
+
}
|
|
191
|
+
|
|
49
192
|
/**
|
|
50
193
|
* Inspect the instance lock at <dataDir>/quilltap.lock and decide whether it
|
|
51
194
|
* is *actively* held by a live Quilltap process.
|
|
52
195
|
*
|
|
53
196
|
* Returns:
|
|
54
|
-
* { state: 'absent' }
|
|
197
|
+
* { state: 'absent', lockPath } — no lock file
|
|
55
198
|
* { state: 'corrupt', lockPath } — file exists but unreadable
|
|
56
199
|
* { state: 'active', lock, lockPath, reason } — held by a live owner
|
|
57
200
|
* { state: 'stale', lock, lockPath, reason } — owner is gone
|
|
58
201
|
* { state: 'suspect', lock, lockPath, reason } — PID alive but not Quilltap-shaped
|
|
202
|
+
*
|
|
203
|
+
* The last three are assessLock()'s verdict, unaltered.
|
|
59
204
|
*/
|
|
60
205
|
function getLockStatus(dataDir) {
|
|
61
206
|
const lockPath = path.join(dataDir, 'quilltap.lock');
|
|
207
|
+
const read = readLockRecord(lockPath);
|
|
62
208
|
|
|
63
|
-
if (
|
|
209
|
+
if (read.state === 'absent') {
|
|
64
210
|
return { state: 'absent', lockPath };
|
|
65
211
|
}
|
|
66
|
-
|
|
67
|
-
let lock;
|
|
68
|
-
try {
|
|
69
|
-
lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
|
|
70
|
-
} catch {
|
|
212
|
+
if (read.state === 'corrupt') {
|
|
71
213
|
return { state: 'corrupt', lockPath };
|
|
72
214
|
}
|
|
73
215
|
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
if (sameHost) {
|
|
78
|
-
const alive = isPidAlive(lock.pid);
|
|
79
|
-
if (!alive) {
|
|
80
|
-
return { state: 'stale', lock, lockPath, reason: `PID ${lock.pid} is no longer running` };
|
|
81
|
-
}
|
|
82
|
-
const isNode = verifyPidIsNode(lock.pid);
|
|
83
|
-
if (!isNode) {
|
|
84
|
-
return {
|
|
85
|
-
state: 'suspect',
|
|
86
|
-
lock, lockPath,
|
|
87
|
-
reason: `PID ${lock.pid} is alive but does not look like a Quilltap process`,
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
return { state: 'active', lock, lockPath, reason: `held by PID ${lock.pid} on this host` };
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// Different hostname — could be a VM/container sharing the data dir.
|
|
94
|
-
const isVM = VM_ENVIRONMENTS.has(lock.environment);
|
|
95
|
-
const heartbeatAgeMs = lock.lastHeartbeat
|
|
96
|
-
? Date.now() - new Date(lock.lastHeartbeat).getTime()
|
|
97
|
-
: Infinity;
|
|
98
|
-
if (isVM && heartbeatAgeMs < HEARTBEAT_FRESH_MS) {
|
|
99
|
-
const ageStr = Math.round(heartbeatAgeMs / 1000) + 's';
|
|
100
|
-
return {
|
|
101
|
-
state: 'active',
|
|
102
|
-
lock, lockPath,
|
|
103
|
-
reason: `held by ${lock.environment} instance on ${lock.hostname} (heartbeat ${ageStr} ago)`,
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
return {
|
|
107
|
-
state: 'stale',
|
|
108
|
-
lock, lockPath,
|
|
109
|
-
reason: `held by ${lock.hostname} but no recent heartbeat`,
|
|
110
|
-
};
|
|
216
|
+
const { state, reason } = assessLock(read.lock);
|
|
217
|
+
return { state, lock: read.lock, lockPath, reason };
|
|
111
218
|
}
|
|
112
219
|
|
|
113
220
|
// ============================================================================
|
|
@@ -174,6 +281,7 @@ function resolveServerPort({ port, instance, dataDir } = {}) {
|
|
|
174
281
|
};
|
|
175
282
|
}
|
|
176
283
|
|
|
284
|
+
|
|
177
285
|
// ============================================================================
|
|
178
286
|
// Write-lock acquire / release
|
|
179
287
|
//
|
|
@@ -192,12 +300,29 @@ function resolveServerPort({ port, instance, dataDir } = {}) {
|
|
|
192
300
|
|
|
193
301
|
const MAX_HISTORY_ENTRIES = 50;
|
|
194
302
|
|
|
195
|
-
//
|
|
196
|
-
//
|
|
197
|
-
|
|
303
|
+
// The lock record this process wrote, captured at write time: where it is, and
|
|
304
|
+
// the PID and acquisition timestamp in it. "Is this lock mine" is answered
|
|
305
|
+
// against this snapshot, the way the server answers it — never by comparing
|
|
306
|
+
// hostnames, which can change under a long `db --repl --write` session and
|
|
307
|
+
// would then make us drop our own heartbeat and leave our own lock behind.
|
|
308
|
+
// Any process that takes the lock overwrites both fields, so a real takeover
|
|
309
|
+
// still shows.
|
|
310
|
+
let ownedLock = null;
|
|
198
311
|
let heartbeatTimer = null;
|
|
199
312
|
let exitHandlersRegistered = false;
|
|
200
313
|
|
|
314
|
+
function rememberOwnedLock(lockPath, content) {
|
|
315
|
+
ownedLock = { lockPath, pid: content.pid, startedAt: content.startedAt };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Is the record at `lockPath` still the one this process wrote? */
|
|
319
|
+
function isOwnedLock(lockPath, lock) {
|
|
320
|
+
return ownedLock !== null &&
|
|
321
|
+
ownedLock.lockPath === lockPath &&
|
|
322
|
+
lock.pid === ownedLock.pid &&
|
|
323
|
+
lock.startedAt === ownedLock.startedAt;
|
|
324
|
+
}
|
|
325
|
+
|
|
201
326
|
/**
|
|
202
327
|
* Detect the runtime environment for lock metadata. JS port of the server's
|
|
203
328
|
* detectEnvironmentType() so a CLI run inside Docker writes the right
|
|
@@ -241,9 +366,18 @@ function addHistoryEntry(content, event, detail) {
|
|
|
241
366
|
return { ...content, history };
|
|
242
367
|
}
|
|
243
368
|
|
|
244
|
-
/**
|
|
369
|
+
/**
|
|
370
|
+
* A temp name beside the lock that no other writer will pick. Two processes
|
|
371
|
+
* sharing one temp name could rename each other's half-written file into
|
|
372
|
+
* place, and a file at the lock path must always be a complete record.
|
|
373
|
+
*/
|
|
374
|
+
function tempPathFor(lockPath) {
|
|
375
|
+
return `${lockPath}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** Replace the lock file atomically via tmp + rename (matches the server). */
|
|
245
379
|
function writeLockFileAtomic(lockPath, content) {
|
|
246
|
-
const tmpPath = lockPath
|
|
380
|
+
const tmpPath = tempPathFor(lockPath);
|
|
247
381
|
try {
|
|
248
382
|
fs.writeFileSync(tmpPath, JSON.stringify(content, null, 2) + '\n', 'utf8');
|
|
249
383
|
fs.renameSync(tmpPath, lockPath);
|
|
@@ -253,6 +387,73 @@ function writeLockFileAtomic(lockPath, content) {
|
|
|
253
387
|
}
|
|
254
388
|
}
|
|
255
389
|
|
|
390
|
+
/** Write `data` to an open descriptor and push it to disk where the filesystem can. */
|
|
391
|
+
function writeAndSync(fd, data) {
|
|
392
|
+
fs.writeSync(fd, data, 0, 'utf8');
|
|
393
|
+
try { fs.fsyncSync(fd); } catch { /* not every filesystem can; nothing depends on it */ }
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Create the lock file, failing if one exists, so that it is never visible
|
|
398
|
+
* half-written (matches the server's createLockFileExclusive).
|
|
399
|
+
*
|
|
400
|
+
* The record is written to a temp file and hard-linked into place: link()
|
|
401
|
+
* fails with EEXIST when a lock is already there, and the name appears with
|
|
402
|
+
* the whole record behind it. The server claims a lock file that is not a
|
|
403
|
+
* complete record as left over from a crash, which is only safe if no live
|
|
404
|
+
* writer ever shows one — an exclusive create followed by a write does.
|
|
405
|
+
*
|
|
406
|
+
* @returns {boolean} true if we created the lock; false if one is there.
|
|
407
|
+
*/
|
|
408
|
+
function createLockFileExclusive(lockPath, content) {
|
|
409
|
+
const data = JSON.stringify(content, null, 2) + '\n';
|
|
410
|
+
const tmpPath = tempPathFor(lockPath);
|
|
411
|
+
try {
|
|
412
|
+
const fd = fs.openSync(tmpPath, 'wx');
|
|
413
|
+
try {
|
|
414
|
+
writeAndSync(fd, data);
|
|
415
|
+
} finally {
|
|
416
|
+
fs.closeSync(fd);
|
|
417
|
+
}
|
|
418
|
+
try {
|
|
419
|
+
fs.linkSync(tmpPath, lockPath);
|
|
420
|
+
return true;
|
|
421
|
+
} catch (err) {
|
|
422
|
+
if (err.code === 'EEXIST') return false;
|
|
423
|
+
// Anything else, having just written a file in this directory, means the
|
|
424
|
+
// filesystem has no hard links (exFAT, some network mounts). Fall through.
|
|
425
|
+
}
|
|
426
|
+
} finally {
|
|
427
|
+
try { fs.unlinkSync(tmpPath); } catch { /* ignore cleanup failure */ }
|
|
428
|
+
}
|
|
429
|
+
return createLockFileWithoutHardLinks(lockPath, content, data);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Exclusive create for a filesystem without hard links. Still exclusive, but
|
|
434
|
+
* the file exists empty for an instant before the record lands in it, and a
|
|
435
|
+
* process reading it in that instant takes it for a crash leftover and claims
|
|
436
|
+
* it. So the create only counts if our record is what is there afterwards.
|
|
437
|
+
*/
|
|
438
|
+
function createLockFileWithoutHardLinks(lockPath, content, data) {
|
|
439
|
+
let fd;
|
|
440
|
+
try {
|
|
441
|
+
fd = fs.openSync(lockPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY);
|
|
442
|
+
} catch (err) {
|
|
443
|
+
if (err.code === 'EEXIST') return false;
|
|
444
|
+
throw err;
|
|
445
|
+
}
|
|
446
|
+
try {
|
|
447
|
+
writeAndSync(fd, data);
|
|
448
|
+
} finally {
|
|
449
|
+
fs.closeSync(fd);
|
|
450
|
+
}
|
|
451
|
+
const read = readLockRecord(lockPath);
|
|
452
|
+
return read.state === 'ok' &&
|
|
453
|
+
read.lock.pid === content.pid &&
|
|
454
|
+
read.lock.startedAt === content.startedAt;
|
|
455
|
+
}
|
|
456
|
+
|
|
256
457
|
function startHeartbeat(lockPath) {
|
|
257
458
|
stopHeartbeat();
|
|
258
459
|
// 60s like the server. unref() so a one-shot command (which exits in
|
|
@@ -260,14 +461,18 @@ function startHeartbeat(lockPath) {
|
|
|
260
461
|
// sessions ever actually beat.
|
|
261
462
|
heartbeatTimer = setInterval(() => {
|
|
262
463
|
try {
|
|
263
|
-
const
|
|
264
|
-
|
|
265
|
-
if (
|
|
464
|
+
const read = readLockRecord(lockPath);
|
|
465
|
+
// Gone, or unreadable this tick: nothing to refresh. Try again next tick.
|
|
466
|
+
if (read.state !== 'ok') return;
|
|
467
|
+
if (!isOwnedLock(lockPath, read.lock)) {
|
|
266
468
|
// We no longer own the lock — stop beating, don't fight over it.
|
|
267
469
|
stopHeartbeat();
|
|
268
470
|
return;
|
|
269
471
|
}
|
|
472
|
+
const lock = read.lock;
|
|
270
473
|
lock.lastHeartbeat = new Date().toISOString();
|
|
474
|
+
// The hostname is a label; keep it current when the OS renames us.
|
|
475
|
+
lock.hostname = os.hostname();
|
|
271
476
|
writeLockFileAtomic(lockPath, lock);
|
|
272
477
|
} catch { /* best effort */ }
|
|
273
478
|
}, 60_000);
|
|
@@ -309,8 +514,9 @@ function acquireWriteLock(dataDir) {
|
|
|
309
514
|
if (status.state === 'active') {
|
|
310
515
|
lines.push('Stop the running Quilltap instance before opening the database read-write.');
|
|
311
516
|
} else {
|
|
312
|
-
|
|
313
|
-
lines.push('
|
|
517
|
+
// `--lock-clean` refuses a fresh heartbeat, and a suspect lock has one.
|
|
518
|
+
lines.push('Its PID may have been reused since a crash. The lock is claimed automatically once its');
|
|
519
|
+
lines.push(`heartbeat is ${Math.round(HEARTBEAT_FRESH_MS / 60000)} minutes old; try again then.`);
|
|
314
520
|
}
|
|
315
521
|
lines.push('(See `quilltap db --lock-status` for details.)');
|
|
316
522
|
const err = new Error(lines.join('\n'));
|
|
@@ -326,94 +532,87 @@ function acquireWriteLock(dataDir) {
|
|
|
326
532
|
|
|
327
533
|
if (status.state === 'stale') {
|
|
328
534
|
// Dead PID / no recent heartbeat — claim it, preserving history.
|
|
329
|
-
claimStaleLock(lockPath, status.lock, status.reason);
|
|
330
|
-
finishAcquire(dataDir, lockPath);
|
|
535
|
+
finishAcquire(dataDir, lockPath, claimStaleLock(lockPath, status.lock, status.reason));
|
|
331
536
|
return;
|
|
332
537
|
}
|
|
333
538
|
|
|
334
|
-
// Absent —
|
|
539
|
+
// Absent — exclusive create so we lose cleanly to any racing process.
|
|
335
540
|
const content = addHistoryEntry(buildLockContent(), 'acquired', 'Read-write CLI session (quilltap db --write)');
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
const fd = fs.openSync(lockPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY);
|
|
339
|
-
try {
|
|
340
|
-
fs.writeSync(fd, jsonData, 0, 'utf8');
|
|
341
|
-
} finally {
|
|
342
|
-
fs.closeSync(fd);
|
|
343
|
-
}
|
|
344
|
-
finishAcquire(dataDir, lockPath);
|
|
541
|
+
if (createLockFileExclusive(lockPath, content)) {
|
|
542
|
+
finishAcquire(dataDir, lockPath, content);
|
|
345
543
|
return;
|
|
346
|
-
} catch (err) {
|
|
347
|
-
if (err.code !== 'EEXIST') throw err;
|
|
348
|
-
// Someone created the lock between our check and our create. Re-decide.
|
|
349
|
-
const recheck = getLockStatus(dataDir);
|
|
350
|
-
if (recheck.state === 'active' || recheck.state === 'suspect' || recheck.state === 'corrupt') {
|
|
351
|
-
const e = new Error(
|
|
352
|
-
`Database is currently in use — ${recheck.reason || 'lock just claimed by another process'}.\n` +
|
|
353
|
-
'Stop the running Quilltap instance before opening the database read-write.',
|
|
354
|
-
);
|
|
355
|
-
e.locked = true;
|
|
356
|
-
throw e;
|
|
357
|
-
}
|
|
358
|
-
// Now stale (or absent again) — claim it.
|
|
359
|
-
claimStaleLock(lockPath, recheck.lock || buildLockContent(), recheck.reason || 'reclaimed after race');
|
|
360
|
-
finishAcquire(dataDir, lockPath);
|
|
361
544
|
}
|
|
545
|
+
|
|
546
|
+
// Someone created the lock between our check and our create. Re-decide.
|
|
547
|
+
const recheck = getLockStatus(dataDir);
|
|
548
|
+
if (recheck.state === 'active' || recheck.state === 'suspect' || recheck.state === 'corrupt') {
|
|
549
|
+
const e = new Error(
|
|
550
|
+
`Database is currently in use — ${recheck.reason || 'lock just claimed by another process'}.\n` +
|
|
551
|
+
'Stop the running Quilltap instance before opening the database read-write.',
|
|
552
|
+
);
|
|
553
|
+
e.locked = true;
|
|
554
|
+
throw e;
|
|
555
|
+
}
|
|
556
|
+
// Now stale (or absent again) — claim it.
|
|
557
|
+
finishAcquire(
|
|
558
|
+
dataDir,
|
|
559
|
+
lockPath,
|
|
560
|
+
claimStaleLock(lockPath, recheck.lock || buildLockContent(), recheck.reason || 'reclaimed after race'),
|
|
561
|
+
);
|
|
362
562
|
}
|
|
363
563
|
|
|
364
|
-
/**
|
|
564
|
+
/**
|
|
565
|
+
* Overwrite a stale lock with our process info, preserving prior history.
|
|
566
|
+
* Returns the record written.
|
|
567
|
+
*/
|
|
365
568
|
function claimStaleLock(lockPath, existing, reason) {
|
|
366
569
|
let content = { ...buildLockContent(), history: (existing && existing.history) || [] };
|
|
367
570
|
content = addHistoryEntry(content, 'stale-detected', reason);
|
|
368
571
|
content = addHistoryEntry(content, 'stale-claimed', `Claimed by PID ${process.pid} (quilltap db --write)`);
|
|
369
572
|
writeLockFileAtomic(lockPath, content);
|
|
573
|
+
return content;
|
|
370
574
|
}
|
|
371
575
|
|
|
372
|
-
function finishAcquire(dataDir, lockPath) {
|
|
373
|
-
|
|
576
|
+
function finishAcquire(dataDir, lockPath, content) {
|
|
577
|
+
rememberOwnedLock(lockPath, content);
|
|
374
578
|
startHeartbeat(lockPath);
|
|
375
579
|
registerExitHandlers(dataDir);
|
|
376
580
|
}
|
|
377
581
|
|
|
378
582
|
/**
|
|
379
|
-
* Release the lock if (and only if)
|
|
583
|
+
* Release the lock if (and only if) it is still the record this process
|
|
584
|
+
* wrote. Idempotent; never throws.
|
|
380
585
|
*/
|
|
381
586
|
function releaseWriteLock(dataDir) {
|
|
382
587
|
stopHeartbeat();
|
|
383
588
|
const lockPath = path.join(dataDir, 'quilltap.lock');
|
|
384
|
-
if (ownedLockPath !== lockPath && ownedLockPath !== null) {
|
|
385
|
-
// Owned a different path (shouldn't happen in one CLI run) — be conservative.
|
|
386
|
-
}
|
|
387
589
|
try {
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
}
|
|
393
|
-
// Corrupt — don't touch a lock we can't prove is ours.
|
|
394
|
-
ownedLockPath = null;
|
|
395
|
-
return;
|
|
396
|
-
}
|
|
397
|
-
if (lock.pid !== process.pid || lock.hostname !== os.hostname()) {
|
|
398
|
-
ownedLockPath = null;
|
|
399
|
-
return;
|
|
400
|
-
}
|
|
401
|
-
const updated = addHistoryEntry(lock, 'released', `Released by PID ${process.pid} (quilltap db --write)`);
|
|
590
|
+
const read = readLockRecord(lockPath);
|
|
591
|
+
// Gone already, or unreadable — don't touch a lock we can't prove is ours.
|
|
592
|
+
if (read.state !== 'ok') return;
|
|
593
|
+
if (!isOwnedLock(lockPath, read.lock)) return;
|
|
594
|
+
const updated = addHistoryEntry(read.lock, 'released', `Released by PID ${process.pid} (quilltap db --write)`);
|
|
402
595
|
try { writeLockFileAtomic(lockPath, updated); } catch { /* best effort */ }
|
|
403
596
|
try { fs.unlinkSync(lockPath); } catch { /* best effort */ }
|
|
404
597
|
} catch {
|
|
405
598
|
/* never throw from release */
|
|
406
599
|
} finally {
|
|
407
|
-
|
|
600
|
+
if (ownedLock !== null && ownedLock.lockPath === lockPath) ownedLock = null;
|
|
408
601
|
}
|
|
409
602
|
}
|
|
410
603
|
|
|
411
604
|
module.exports = {
|
|
605
|
+
HEARTBEAT_FRESH_MS,
|
|
606
|
+
CORRUPT_LOCK_SETTLE_MS,
|
|
412
607
|
getLockStatus,
|
|
608
|
+
assessLock,
|
|
609
|
+
assessLockRecord,
|
|
610
|
+
readLockRecord,
|
|
413
611
|
isPidAlive,
|
|
414
612
|
verifyPidIsNode,
|
|
415
613
|
acquireWriteLock,
|
|
416
614
|
releaseWriteLock,
|
|
615
|
+
writeLockFileAtomic,
|
|
417
616
|
detectEnvironmentType,
|
|
418
617
|
resolveServerPort,
|
|
419
618
|
DEFAULT_SERVER_PORT,
|
|
@@ -1035,5 +1035,21 @@ module.exports = [
|
|
|
1035
1035
|
{
|
|
1036
1036
|
"id": "add-chat-settings-timezone-v1",
|
|
1037
1037
|
"description": "Chat settings: the timezone column the instance default time zone never had"
|
|
1038
|
+
},
|
|
1039
|
+
{
|
|
1040
|
+
"id": "collapse-duplicate-provider-models-v1",
|
|
1041
|
+
"description": "Provider models: one row per (provider, modelType, modelId, baseUrl), unique-indexed (#414)"
|
|
1042
|
+
},
|
|
1043
|
+
{
|
|
1044
|
+
"id": "collapse-duplicate-chat-documents-v1",
|
|
1045
|
+
"description": "Chat documents: one row per document per chat, the store compared through COALESCE (#414)"
|
|
1046
|
+
},
|
|
1047
|
+
{
|
|
1048
|
+
"id": "add-files-mount-link-id-v1",
|
|
1049
|
+
"description": "Files: the document-store link a mount-blob row's write created (#401)"
|
|
1050
|
+
},
|
|
1051
|
+
{
|
|
1052
|
+
"id": "move-general-doc-files-to-store-v1",
|
|
1053
|
+
"description": "Document stores: the loose _general/ files moved into the Quilltap General store (#402)"
|
|
1038
1054
|
}
|
|
1039
1055
|
];
|