@jc_stack/ez-library 0.1.0-beta.18 → 0.1.0-beta.19

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/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.0-beta.19
4
+
5
+ - Writers wait up to 60 seconds for a live holder of the Library writer lock (named in its `owner` file) instead of failing `BUSY` at once, so concurrent agent writes and the resident sync no longer fail on a brief overlap. A lock without an owner still fails closed after a one-second grace; a lock held by the same process fails at once; the resident worker stops waiting when told to stop.
6
+ - Requires Ez core 0.1.0-beta.50 or newer (unchanged).
7
+
3
8
  ## 0.1.0-beta.18
4
9
 
5
10
  - Reuse unchanged file digests in the resident sync worker: inventory scans skip rereading files whose device, inode, size, mtime and ctime are unchanged, and the text mirror rewrites only changed files and skips fetch, push and verification when the remote head already matches. Idle sync cycles no longer hash every original twice per minute.
package/README.md CHANGED
@@ -153,7 +153,7 @@ The named `data` volume contains `/state/files`, `settings.json`, `operations`,
153
153
 
154
154
  Stop the plugin before an operator takes a volume snapshot using an existing backup tool. Preserve originals, settings, receipts and history together. QMD indexes/models are rebuildable. Uninstall removes the deployment and registry binding but preserves volumes. Account revocation is a separate action in the provider's plugin/account. See [release and rollback practices](docs/releasing.md).
155
155
 
156
- An interrupted command may leave `/state/.writer-lock`, or QMD's own embed lock below `/state/qmd/cache/qmd`. Confirm no Library client/embedding command is active before removing only the stale lock. Never delete the index or originals as a lock workaround. Run `operation` to reconcile an interrupted file write. Concurrent writes directly to `/state/files` are unsupported. Edit the mapped external folder instead, or use guarded Library commands.
156
+ Library writers take `/state/.writer-lock` in turn: a command waits up to 60 seconds for a live writer (named in the lock's `owner` file) before returning `BUSY`, and a lock without an owner returns `BUSY` after a one-second grace. An interrupted command may leave `/state/.writer-lock`, or QMD's own embed lock below `/state/qmd/cache/qmd`. Confirm no Library client/embedding command is active before removing only the stale lock. Never delete the index or originals as a lock workaround. Run `operation` to reconcile an interrupted file write. Concurrent writes directly to `/state/files` are unsupported. Edit the mapped external folder instead, or use guarded Library commands.
157
157
 
158
158
  ## Development
159
159
 
package/ez-plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "id": "library",
4
- "version": "0.1.0-beta.18",
4
+ "version": "0.1.0-beta.19",
5
5
  "description": "Dockerized agent library files, QMD retrieval and explicit persistence settings",
6
6
  "example": "library search 'quarterly budget' --all --limit 5",
7
7
  "commands": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jc_stack/ez-library",
3
- "version": "0.1.0-beta.18",
3
+ "version": "0.1.0-beta.19",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "latest"
package/src/store.mjs CHANGED
@@ -3,6 +3,8 @@ import { createReadStream, createWriteStream, constants } from 'node:fs';
3
3
  import { pipeline } from 'node:stream/promises';
4
4
  import { Transform } from 'node:stream';
5
5
  import path from 'node:path';
6
+ import { hostname } from 'node:os';
7
+ import { setTimeout as sleep } from 'node:timers/promises';
6
8
  import { createHash, randomUUID } from 'node:crypto';
7
9
 
8
10
  export class LibraryError extends Error {
@@ -80,15 +82,41 @@ export async function initialize(root) {
80
82
  }
81
83
  return root;
82
84
  }
83
- export async function locked(root, fn) {
85
+ // A live writer records itself in the lock and others wait for it briefly. A lock
86
+ // with no owner is an interrupted operation and fails closed.
87
+ const LOCK_WAIT_MS = 60_000;
88
+ const OWNERLESS_GRACE_MS = 1_000;
89
+ async function lockOwner(lock) {
90
+ try { return JSON.parse(await fs.readFile(path.join(lock, 'owner'), 'utf8')); }
91
+ catch (e) { if (e.code === 'ENOENT' || e instanceof SyntaxError) return null; throw e; }
92
+ }
93
+ async function acquire(lock, signal) {
94
+ const started = Date.now();
95
+ let ownerless = null;
96
+ for (;;) {
97
+ signal?.throwIfAborted();
98
+ try {
99
+ await fs.mkdir(lock, { mode: 0o700 });
100
+ try { await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: process.pid, host: hostname(), at: new Date().toISOString() }), { mode: 0o600, flag: 'wx' }); }
101
+ catch (e) { await fs.rmdir(lock); throw e; }
102
+ return;
103
+ } catch (e) { if (e.code !== 'EEXIST') throw e; }
104
+ const owner = await lockOwner(lock);
105
+ if (owner?.pid === process.pid && owner?.host === hostname()) fail('BUSY', 'Writer lock is held by this process');
106
+ ownerless = owner ? null : ownerless ?? Date.now();
107
+ if (ownerless !== null && Date.now() - ownerless >= OWNERLESS_GRACE_MS)
108
+ fail('BUSY', 'Writer lock exists without an owner; confirm no command is active before recovering an interrupted operation');
109
+ if (Date.now() - started >= LOCK_WAIT_MS)
110
+ fail('BUSY', `Writer lock held by pid ${owner?.pid} on ${owner?.host} since ${owner?.at}; confirm it is active before recovering an interrupted operation`);
111
+ await sleep(100 + Math.random() * 150, undefined, { signal });
112
+ }
113
+ }
114
+ export async function locked(root, fn, { signal } = {}) {
84
115
  root = await rootDir(root, true);
85
116
  const lock = path.join(root, '.writer-lock');
86
- await fs.mkdir(lock, { mode: 0o700 }).catch(e => {
87
- if (e.code === 'EEXIST') fail('BUSY', 'Writer lock exists; confirm no command is active before recovering an interrupted operation');
88
- throw e;
89
- });
117
+ await acquire(lock, signal);
90
118
  try { return await fn(await initialize(root)); }
91
- finally { await fs.rmdir(lock); }
119
+ finally { await fs.rm(path.join(lock, 'owner'), { force: true }); await fs.rmdir(lock); }
92
120
  }
93
121
  async function opened(file, read) {
94
122
  const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
@@ -27,11 +27,11 @@ while (!stopping) {
27
27
  const enabled = config?.mode === 'two-way' || (config?.backend === 'git' && config.mode === 'pull-only');
28
28
  if (!enabled && (config || mirror?.mode !== 'one-way')) {
29
29
  due.delete(name);
30
- if ((await embeddingStatus()).state === 'ready') await locked(selected, refreshIndex);
30
+ if ((await embeddingStatus()).state === 'ready') await locked(selected, refreshIndex, { signal: controller.signal });
31
31
  continue;
32
32
  }
33
33
  if ((due.get(name) || 0) <= Date.now()) {
34
- try { await syncRun(selected, root); }
34
+ try { await syncRun(selected, root, { signal: controller.signal }); }
35
35
  finally { due.set(name, Date.now() + (config?.intervalSeconds || 60) * 1000); }
36
36
  }
37
37
  interval = Math.min(interval, Math.max(1, ((due.get(name) || 0) - Date.now()) / 1000));
package/src/sync.mjs CHANGED
@@ -142,7 +142,7 @@ export async function syncPolicy(root, { expected, mode, intervalSeconds = 60 })
142
142
  });
143
143
  }
144
144
 
145
- export async function syncRun(root, stateRoot = root) {
145
+ export async function syncRun(root, stateRoot = root, { signal } = {}) {
146
146
  return locked(root, async root => {
147
147
  await prepare(root);
148
148
  const config = await readJSON(location(root));
@@ -172,5 +172,5 @@ export async function syncRun(root, stateRoot = root) {
172
172
  await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
173
173
  if (status.textMirror?.state === 'pending') fail('UNAVAILABLE', 'GitHub text mirror pending: ' + status.textMirror.error.message);
174
174
  return status;
175
- });
175
+ }, { signal });
176
176
  }
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import { tmpdir } from 'node:os';
6
6
  import { Readable } from 'node:stream';
7
7
  import { spawnSync } from 'node:child_process';
8
- import { put, operation, settings, defaults, validateSettings, list, digest, readRange, MAX_READ_BYTES, hash } from '../src/store.mjs';
8
+ import { locked, put, operation, settings, defaults, validateSettings, list, digest, readRange, MAX_READ_BYTES, hash } from '../src/store.mjs';
9
9
  import { qmdEnvironment } from '../src/cli.mjs';
10
10
 
11
11
  const cli = new URL('../bin/ez-library.mjs', import.meta.url).pathname;
@@ -144,6 +144,27 @@ test('writer lock is fail-closed, including stale-looking locks', async t => {
144
144
  assert((await fs.stat(path.join(root, '.writer-lock'))).isDirectory());
145
145
  });
146
146
 
147
+ test('a live writer is waited for instead of failing BUSY', async t => {
148
+ const root = await fixture(t); const lock = path.join(root, '.writer-lock');
149
+ await fs.mkdir(lock);
150
+ await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: process.pid + 1, host: 'other', at: new Date().toISOString() }));
151
+ const release = new Promise(resolve => setTimeout(async () => {
152
+ await fs.rm(path.join(lock, 'owner')); await fs.rmdir(lock); resolve();
153
+ }, 600));
154
+ await save(root, 'after wait');
155
+ await release;
156
+ await assert.rejects(fs.stat(lock), code('ENOENT'));
157
+ });
158
+
159
+ test('an aborted wait gives up without taking the lock', async t => {
160
+ const root = await fixture(t); const lock = path.join(root, '.writer-lock');
161
+ await fs.mkdir(lock);
162
+ await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: process.pid + 1, host: 'other', at: new Date().toISOString() }));
163
+ const controller = new AbortController(); setTimeout(() => controller.abort(), 300);
164
+ await assert.rejects(locked(root, () => assert.fail('must not run'), { signal: controller.signal }), { name: 'AbortError' });
165
+ assert.equal(JSON.parse(await fs.readFile(path.join(lock, 'owner'), 'utf8')).host, 'other');
166
+ });
167
+
147
168
  test('list honors prefix and a bounded result size', async t => {
148
169
  const root = await fixture(t); await save(root, 'a');
149
170
  await put(root, 'notes/second.md', input('b'), { key: 'b', expected: 'new' });