@jc_stack/ez-library 0.1.0-beta.19 → 0.1.0-beta.21
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 +11 -0
- package/ez-plugin.json +1 -1
- package/package.json +1 -1
- package/src/git-mirror.mjs +11 -8
- package/src/git-sync.mjs +13 -7
- package/src/native.mjs +17 -2
- package/src/store.mjs +31 -4
- package/src/sync.mjs +7 -3
- package/test/git-sync.test.mjs +37 -1
- package/test/library.test.mjs +41 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.0-beta.21
|
|
4
|
+
|
|
5
|
+
- Git sync can no longer hang forever holding the writer lock. The SSH command adds `ServerAliveInterval=15` and `ServerAliveCountMax=4`, and every remote-touching Git call (fetch, push, ls-remote, in sync, text mirror and adoption) is bounded at 5 minutes: on expiry the child is stopped (SIGTERM, then SIGKILL after 5 seconds) and the cycle fails `UNAVAILABLE`, so the lock is released and the next interval retries. Before this, a connection that stalled after connect left `sync-status` at `syncing` and every writer `BUSY` until the service was restarted (#53).
|
|
6
|
+
- `sync/status.json` records the current `step` while a cycle runs (`fetch`, `push`, `verify`, then `mirror-read`, `mirror-fetch`, `mirror-push` and `index`); a failed Git transfer or index keeps its step, so `sync-status` shows where it stopped. A text-mirror failure is reported in `textMirror.error`, naming the failed operation.
|
|
7
|
+
- Requires Ez core 0.1.0-beta.50 or newer (unchanged).
|
|
8
|
+
|
|
9
|
+
## 0.1.0-beta.20
|
|
10
|
+
|
|
11
|
+
- Reclaim a writer lock left by a dead process on the same host. The lock owner now records a per-process id; a same-host lock whose pid no longer exists, or that names this process's pid without its id (a restarted container reusing pid and hostname), is removed. Reclaimers take turns under an exclusive mutex and remove the lock only if it still names the same dead owner, so concurrent callers never take over a live lock. Before this, a restarted resident worker read the dead writer's lock as its own and failed `BUSY` on every cycle until the lock was removed by hand. Locks from other hosts, locks without an owner and an unreadable owner pid still fail closed; a reclaim mutex left by a crash makes writers wait and fail `BUSY` naming it. Same hostname is taken to mean the same pid namespace (Docker's default).
|
|
12
|
+
- Requires Ez core 0.1.0-beta.50 or newer (unchanged).
|
|
13
|
+
|
|
3
14
|
## 0.1.0-beta.19
|
|
4
15
|
|
|
5
16
|
- 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.
|
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.
|
|
4
|
+
"version": "0.1.0-beta.21",
|
|
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
package/src/git-mirror.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import * as fs from 'node:fs/promises';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { atomic, fail, hash, jsonBytes, locked, safePath } from './store.mjs';
|
|
4
4
|
import { inventory } from './indexer.mjs';
|
|
5
|
-
import { git, repositoryURL, tree } from './git-sync.mjs';
|
|
5
|
+
import { git, network, repositoryURL, tree } from './git-sync.mjs';
|
|
6
6
|
import { native, succeeded } from './native.mjs';
|
|
7
7
|
|
|
8
8
|
const file = root => path.join(root, 'sync/text-mirror.json');
|
|
@@ -88,13 +88,13 @@ export async function mirrorAdopt(root, repository, branch = 'main', extensions
|
|
|
88
88
|
if (origin.code !== 0) succeeded(await mirrorGit(root, config, ['remote', 'add', 'origin', repositoryURL(repository)]), 'Set mirror remote');
|
|
89
89
|
// Existing history requires an exact reviewed remote revision and a safe
|
|
90
90
|
// projection. Adoption never writes source files or pushes a remote change.
|
|
91
|
-
const existing = succeeded(await mirrorGit(root, config, ['ls-remote', 'origin', 'refs/heads/' + branch]), 'Check mirror destination');
|
|
91
|
+
const existing = succeeded(await mirrorGit(root, config, ['ls-remote', 'origin', 'refs/heads/' + branch], network()), 'Check mirror destination');
|
|
92
92
|
const remoteHead = existing.trim().split(/\s+/)[0];
|
|
93
93
|
if (expectedRemote !== undefined && !/^[a-f0-9]{40}$/.test(expectedRemote)) fail('INVALID', 'Use the full expected remote commit SHA');
|
|
94
94
|
if (remoteHead && !expectedRemote) fail('CONFLICT', 'Existing mirror history requires --expected-remote with the reviewed commit SHA');
|
|
95
95
|
if (expectedRemote && remoteHead !== expectedRemote) fail('CONFLICT', 'Mirror remote no longer matches the expected commit');
|
|
96
96
|
if (remoteHead) {
|
|
97
|
-
succeeded(await mirrorGit(root, config, ['fetch', '--no-tags', 'origin', 'refs/heads/' + branch]), 'Fetch existing mirror');
|
|
97
|
+
succeeded(await mirrorGit(root, config, ['fetch', '--no-tags', 'origin', 'refs/heads/' + branch], network()), 'Fetch existing mirror');
|
|
98
98
|
if (succeeded(await mirrorGit(root, config, ['rev-parse', 'FETCH_HEAD']), 'Read fetched mirror').trim() !== expectedRemote) fail('CONFLICT', 'Mirror changed during adoption');
|
|
99
99
|
const entries = await tree(root, { ...config, textMirror: true }, 'FETCH_HEAD');
|
|
100
100
|
canonicalHistory(entries);
|
|
@@ -123,20 +123,22 @@ export async function mirrorPolicy(root, expected, mode) {
|
|
|
123
123
|
});
|
|
124
124
|
}
|
|
125
125
|
// Caller holds the Library writer lock, after a successful folder transfer.
|
|
126
|
-
export async function mirrorTransfer(root) {
|
|
126
|
+
export async function mirrorTransfer(root, step = async () => {}) {
|
|
127
127
|
const { config } = await mirrorStatus(root);
|
|
128
128
|
if (!config || config.mode === 'paused') return { state: config ? 'paused' : 'disabled' };
|
|
129
129
|
const selected = textProjection(await inventory(path.join(root, 'files')), config);
|
|
130
130
|
const run = (args, options) => mirrorGit(root, config, args, options);
|
|
131
131
|
if (succeeded(await run(['remote', 'get-url', 'origin']), 'Check mirror remote').trim() !== repositoryURL(config.repository)) fail('CONFLICT', 'Mirror remote changed');
|
|
132
|
-
|
|
132
|
+
await step('mirror-read');
|
|
133
|
+
const remote = succeeded(await run(['ls-remote', 'origin', 'refs/heads/' + config.branch], network()), 'Read mirror head').trim().split(/\s+/)[0];
|
|
133
134
|
const local = await run(['rev-parse', '--verify', 'HEAD']);
|
|
134
135
|
if (local.code === 0) canonicalHistory(await tree(root, { ...config, textMirror: true }, 'HEAD'));
|
|
135
136
|
if (remote) {
|
|
136
137
|
if (config.lastCommit && remote !== config.lastCommit && remote !== local.stdout.trim()) fail('CONFLICT', 'Mirror branch was changed externally');
|
|
137
138
|
if (local.code !== 0) fail('CONFLICT', 'Mirror remote changed before first commit');
|
|
138
139
|
if (remote !== local.stdout.trim()) {
|
|
139
|
-
|
|
140
|
+
await step('mirror-fetch');
|
|
141
|
+
succeeded(await run(['fetch', '--no-tags', 'origin', 'refs/heads/' + config.branch], network()), 'Fetch mirror head');
|
|
140
142
|
if ((await run(['merge-base', '--is-ancestor', 'FETCH_HEAD', 'HEAD'])).code !== 0) fail('CONFLICT', 'GitHub mirror was edited externally; preserve and reconcile it before resuming');
|
|
141
143
|
}
|
|
142
144
|
} else if (config.lastCommit) fail('CONFLICT', 'Mirror branch disappeared; no automatic recreation');
|
|
@@ -163,8 +165,9 @@ export async function mirrorTransfer(root) {
|
|
|
163
165
|
const commit = succeeded(await run(['rev-parse', 'HEAD']), 'Read mirror commit').trim();
|
|
164
166
|
// The remote head read above already proves an unchanged projection.
|
|
165
167
|
if (remote !== commit) {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
+
await step('mirror-push');
|
|
169
|
+
succeeded(await run(['push', 'origin', 'HEAD:refs/heads/' + config.branch], network()), 'Push text mirror');
|
|
170
|
+
const verified = succeeded(await run(['ls-remote', 'origin', 'refs/heads/' + config.branch], network()), 'Verify text mirror').trim().split(/\s+/)[0];
|
|
168
171
|
if (verified !== commit) fail('UNCERTAIN', 'Mirror advanced during verification');
|
|
169
172
|
}
|
|
170
173
|
if (config.lastCommit !== commit) await atomic(file(root), jsonBytes({ ...config, lastCommit: commit }));
|
package/src/git-sync.mjs
CHANGED
|
@@ -32,6 +32,10 @@ export async function gitKey(root, repository) {
|
|
|
32
32
|
});
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
// Remote-touching Git calls are bounded so a stalled transport ends the cycle
|
|
36
|
+
// (UNAVAILABLE) and releases the writer lock instead of blocking every writer.
|
|
37
|
+
export const network = () => ({ timeout: Number(process.env.EZ_LIBRARY_GIT_TIMEOUT_MS) || 5 * 60 * 1000 });
|
|
38
|
+
|
|
35
39
|
export function git(root, config, args, options = {}) {
|
|
36
40
|
const dir = privateDir(root, config.repository);
|
|
37
41
|
const workTree = path.join(root, config.textMirror ? 'sync/text-mirror/files' : 'files');
|
|
@@ -41,7 +45,7 @@ export function git(root, config, args, options = {}) {
|
|
|
41
45
|
'-c', 'user.name=Ez Library', '-c', 'user.email=library@localhost', ...args], {
|
|
42
46
|
...options, env: { GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_TERMINAL_PROMPT: '0',
|
|
43
47
|
GIT_ALLOW_PROTOCOL: path.isAbsolute(config.repository) ? 'file' : 'ssh',
|
|
44
|
-
GIT_SSH_COMMAND: ['/usr/bin/ssh', '-F', '/dev/null', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'IdentitiesOnly=yes',
|
|
48
|
+
GIT_SSH_COMMAND: ['/usr/bin/ssh', '-F', '/dev/null', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=4', '-o', 'IdentitiesOnly=yes',
|
|
45
49
|
'-o', 'StrictHostKeyChecking=yes', '-o', 'UserKnownHostsFile=' + path.join(dir, 'known_hosts'), '-i', path.join(dir, 'key')].map(quote).join(' ') } });
|
|
46
50
|
}
|
|
47
51
|
|
|
@@ -106,7 +110,7 @@ export async function gitAdopt(root, repository, branch = 'main', stateRoot = ro
|
|
|
106
110
|
if (reuseCheckout) {
|
|
107
111
|
config.checkoutOrigin = await existingCheckout(root, config);
|
|
108
112
|
await tree(root, config, 'HEAD');
|
|
109
|
-
succeeded(await git(root, config, ['fetch', '--no-tags', remote, 'refs/heads/' + branch]), 'Verify selected remote');
|
|
113
|
+
succeeded(await git(root, config, ['fetch', '--no-tags', remote, 'refs/heads/' + branch], network()), 'Verify selected remote');
|
|
110
114
|
await tree(root, config, 'FETCH_HEAD');
|
|
111
115
|
// No checkout, reset, commit or push during adoption. Native history and
|
|
112
116
|
// eligible unstaged edits remain owned by the existing checkout.
|
|
@@ -129,7 +133,7 @@ export async function gitAdopt(root, repository, branch = 'main', stateRoot = ro
|
|
|
129
133
|
succeeded(await git(root, config, ['remote', 'add', 'origin', remote]), 'Set Git remote');
|
|
130
134
|
// A failed setup leaves the prepared binding paused, never silently rebound.
|
|
131
135
|
await atomic(binding, jsonBytes(config));
|
|
132
|
-
succeeded(await git(root, config, ['fetch', '--no-tags', 'origin', 'refs/heads/' + branch]), 'Fetch existing branch');
|
|
136
|
+
succeeded(await git(root, config, ['fetch', '--no-tags', 'origin', 'refs/heads/' + branch], network()), 'Fetch existing branch');
|
|
133
137
|
const entries = await tree(root, config, 'FETCH_HEAD');
|
|
134
138
|
const existing = new Map(local.map(f => [f.path, f]));
|
|
135
139
|
for (const entry of entries) {
|
|
@@ -148,7 +152,7 @@ export async function gitAdopt(root, repository, branch = 'main', stateRoot = ro
|
|
|
148
152
|
});
|
|
149
153
|
}
|
|
150
154
|
|
|
151
|
-
export async function gitTransfer(root, config) {
|
|
155
|
+
export async function gitTransfer(root, config, step = async () => {}) {
|
|
152
156
|
if (!['two-way', 'pull-only'].includes(config.mode)) fail('INVALID', 'Use two-way or pull-only Git sync');
|
|
153
157
|
const pullOnly = config.mode === 'pull-only';
|
|
154
158
|
await checkPolicy(root, config.repository, config.branch);
|
|
@@ -172,7 +176,8 @@ export async function gitTransfer(root, config) {
|
|
|
172
176
|
}
|
|
173
177
|
const transport = config.existingCheckout ? repositoryURL(config.repository) : 'origin';
|
|
174
178
|
const trackingRef = 'refs/remotes/origin/' + config.branch;
|
|
175
|
-
|
|
179
|
+
await step('fetch');
|
|
180
|
+
succeeded(await git(root, config, ['fetch', '--no-tags', transport, 'refs/heads/' + config.branch], network()), 'Fetch remote changes');
|
|
176
181
|
await tree(root, config, 'FETCH_HEAD');
|
|
177
182
|
// Native fetch may itself update origin's tracking ref, including when its
|
|
178
183
|
// URL was supplied directly. Compare-and-swap against that post-fetch value.
|
|
@@ -190,8 +195,9 @@ export async function gitTransfer(root, config) {
|
|
|
190
195
|
succeeded(merge, 'Merge remote changes');
|
|
191
196
|
}
|
|
192
197
|
const commit = succeeded(await git(root, config, ['rev-parse', 'HEAD']), 'Read synchronized commit').trim();
|
|
193
|
-
if (!pullOnly) succeeded(await git(root, config, ['push', transport, 'HEAD:refs/heads/' + config.branch]), 'Push Library changes');
|
|
194
|
-
|
|
198
|
+
if (!pullOnly) { await step('push'); succeeded(await git(root, config, ['push', transport, 'HEAD:refs/heads/' + config.branch], network()), 'Push Library changes'); }
|
|
199
|
+
await step('verify');
|
|
200
|
+
const remote = succeeded(await git(root, config, ['ls-remote', '--exit-code', transport, 'refs/heads/' + config.branch], network()), 'Verify remote commit').trim().split(/\s+/)[0];
|
|
195
201
|
if (remote !== commit) fail('UNCERTAIN', 'Remote advanced during verification; fetch/reconcile on the next cycle');
|
|
196
202
|
if (config.existingCheckout) {
|
|
197
203
|
// Push can also record the verified tracking value itself. Keep the guard
|
package/src/native.mjs
CHANGED
|
@@ -10,7 +10,7 @@ export function environment(root) {
|
|
|
10
10
|
...(process.env.EZ_LIBRARY_EMBED_SOCKET ? { EZ_LIBRARY_EMBED_SOCKET: process.env.EZ_LIBRARY_EMBED_SOCKET } : {}), LANG: 'C.UTF-8',
|
|
11
11
|
RCLONE_CONFIG: path.join(root, 'sync/rclone.conf') };
|
|
12
12
|
}
|
|
13
|
-
export function native(root, executable, args, { inherit = false, env = {}, input } = {}) {
|
|
13
|
+
export function native(root, executable, args, { inherit = false, env = {}, input, timeout } = {}) {
|
|
14
14
|
return new Promise((resolve, reject) => {
|
|
15
15
|
const child = spawn(executable, args, { cwd: root, env: { ...environment(root), ...env }, stdio: inherit ? 'inherit' : [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'] });
|
|
16
16
|
if (!inherit && input !== undefined) { child.stdin.on('error', () => {}); child.stdin.end(input); }
|
|
@@ -24,10 +24,25 @@ export function native(root, executable, args, { inherit = false, env = {}, inpu
|
|
|
24
24
|
const terminate = () => child.kill('SIGTERM');
|
|
25
25
|
const interrupt = () => child.kill('SIGINT');
|
|
26
26
|
process.once('SIGTERM', terminate); process.once('SIGINT', interrupt);
|
|
27
|
-
|
|
27
|
+
// A bounded call that stalls is killed (SIGKILL after a grace period) and
|
|
28
|
+
// fails UNAVAILABLE as soon as the child exits, even if an orphaned
|
|
29
|
+
// grandchild still holds its pipes open.
|
|
30
|
+
let timedOut = false, timer, killer;
|
|
31
|
+
if (timeout) timer = setTimeout(() => {
|
|
32
|
+
timedOut = true; child.kill('SIGTERM');
|
|
33
|
+
killer = setTimeout(() => child.kill('SIGKILL'), 5000);
|
|
34
|
+
}, timeout);
|
|
35
|
+
const cleanup = () => { clearTimeout(timer); clearTimeout(killer); process.removeListener('SIGTERM', terminate); process.removeListener('SIGINT', interrupt); };
|
|
28
36
|
child.once('error', e => { cleanup(); reject(e); });
|
|
37
|
+
child.once('exit', () => {
|
|
38
|
+
// Exited in time: the bound is met even if a grandchild still holds the pipes until close.
|
|
39
|
+
if (!timedOut) { clearTimeout(timer); return; }
|
|
40
|
+
cleanup();
|
|
41
|
+
try { fail('UNAVAILABLE', `${path.basename(executable)} timed out after ${Math.round(timeout / 1000)}s and was stopped`); } catch (e) { reject(e); }
|
|
42
|
+
});
|
|
29
43
|
child.once('close', code => {
|
|
30
44
|
cleanup();
|
|
45
|
+
if (timedOut) return;
|
|
31
46
|
if (bytes > 32 * 1024 * 1024) reject(Error('Native output exceeded 32 MiB'));
|
|
32
47
|
else resolve({ code: code ?? 130, stdout: out, stderr: err });
|
|
33
48
|
});
|
package/src/store.mjs
CHANGED
|
@@ -83,13 +83,37 @@ export async function initialize(root) {
|
|
|
83
83
|
return root;
|
|
84
84
|
}
|
|
85
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.
|
|
86
|
+
// with no owner is an interrupted operation and fails closed. A lock owned on this
|
|
87
|
+
// host by a process that no longer exists is reclaimed: a restarted container keeps
|
|
88
|
+
// its hostname and often its pid, so pid + host alone would match the dead writer.
|
|
89
|
+
// Same hostname is taken to mean the same pid namespace (Docker's default).
|
|
87
90
|
const LOCK_WAIT_MS = 60_000;
|
|
88
91
|
const OWNERLESS_GRACE_MS = 1_000;
|
|
92
|
+
const PROCESS_ID = randomUUID();
|
|
89
93
|
async function lockOwner(lock) {
|
|
90
94
|
try { return JSON.parse(await fs.readFile(path.join(lock, 'owner'), 'utf8')); }
|
|
91
95
|
catch (e) { if (e.code === 'ENOENT' || e instanceof SyntaxError) return null; throw e; }
|
|
92
96
|
}
|
|
97
|
+
function alive(pid) {
|
|
98
|
+
if (!Number.isInteger(pid) || pid <= 0) return true; // unreadable owner: fail closed
|
|
99
|
+
if (pid === process.pid) return false; // our pid, but not our PROCESS_ID: a previous process
|
|
100
|
+
try { process.kill(pid, 0); return true; } catch (e) { return e.code !== 'ESRCH'; }
|
|
101
|
+
}
|
|
102
|
+
// Reclaimers take turns under an exclusive mutex and remove the lock only if it still
|
|
103
|
+
// names the same dead owner. A dead owner's lock cannot change while it exists, and
|
|
104
|
+
// nothing else removes it, so the check holds until removal. Returns whether it
|
|
105
|
+
// removed the lock; otherwise the caller waits as for a live holder, so a mutex left
|
|
106
|
+
// by a crash ends in BUSY naming it.
|
|
107
|
+
async function reclaim(lock, dead) {
|
|
108
|
+
const mutex = `${lock}.reclaim`;
|
|
109
|
+
try { await fs.mkdir(mutex, { mode: 0o700 }); } catch (e) { if (e.code === 'EEXIST') return false; throw e; }
|
|
110
|
+
try {
|
|
111
|
+
const owner = await lockOwner(lock);
|
|
112
|
+
if (!owner || !['pid', 'host', 'id', 'at'].every(k => owner[k] === dead[k])) return false;
|
|
113
|
+
await fs.rm(path.join(lock, 'owner'), { force: true }); await fs.rmdir(lock);
|
|
114
|
+
return true;
|
|
115
|
+
} finally { await fs.rmdir(mutex); }
|
|
116
|
+
}
|
|
93
117
|
async function acquire(lock, signal) {
|
|
94
118
|
const started = Date.now();
|
|
95
119
|
let ownerless = null;
|
|
@@ -97,17 +121,20 @@ async function acquire(lock, signal) {
|
|
|
97
121
|
signal?.throwIfAborted();
|
|
98
122
|
try {
|
|
99
123
|
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' }); }
|
|
124
|
+
try { await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: process.pid, host: hostname(), id: PROCESS_ID, at: new Date().toISOString() }), { mode: 0o600, flag: 'wx' }); }
|
|
101
125
|
catch (e) { await fs.rmdir(lock); throw e; }
|
|
102
126
|
return;
|
|
103
127
|
} catch (e) { if (e.code !== 'EEXIST') throw e; }
|
|
104
128
|
const owner = await lockOwner(lock);
|
|
105
|
-
if (owner?.
|
|
129
|
+
if (owner?.host === hostname()) {
|
|
130
|
+
if (owner.id === PROCESS_ID) fail('BUSY', 'Writer lock is held by this process');
|
|
131
|
+
if (!alive(owner.pid) && await reclaim(lock, owner)) continue;
|
|
132
|
+
}
|
|
106
133
|
ownerless = owner ? null : ownerless ?? Date.now();
|
|
107
134
|
if (ownerless !== null && Date.now() - ownerless >= OWNERLESS_GRACE_MS)
|
|
108
135
|
fail('BUSY', 'Writer lock exists without an owner; confirm no command is active before recovering an interrupted operation');
|
|
109
136
|
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`);
|
|
137
|
+
fail('BUSY', `Writer lock held by pid ${owner?.pid} on ${owner?.host} since ${owner?.at}; confirm it is active before recovering an interrupted operation${await fs.stat(`${lock}.reclaim`).then(() => ` (an interrupted reclaim also left ${lock}.reclaim)`, () => '')}`);
|
|
111
138
|
await sleep(100 + Math.random() * 150, undefined, { signal });
|
|
112
139
|
}
|
|
113
140
|
}
|
package/src/sync.mjs
CHANGED
|
@@ -151,17 +151,20 @@ export async function syncRun(root, stateRoot = root, { signal } = {}) {
|
|
|
151
151
|
if (!config && mirror?.mode !== 'one-way') return { state: mirror ? 'paused' : 'unconfigured' };
|
|
152
152
|
let status = { state: 'syncing', startedAt: new Date().toISOString() };
|
|
153
153
|
await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
|
|
154
|
+
// Record where a slow cycle is; the step stays on a failed status.
|
|
155
|
+
const step = async name => { status.step = name; await atomic(path.join(root, 'sync/status.json'), jsonBytes(status)); };
|
|
154
156
|
try {
|
|
155
|
-
if (config?.backend === 'git') status.git = await gitTransfer(root, config);
|
|
157
|
+
if (config?.backend === 'git') status.git = await gitTransfer(root, config, step);
|
|
156
158
|
else if (config) {
|
|
157
159
|
if (config.mode !== 'two-way') fail('INVALID', 'Folder sync requires two-way mode');
|
|
158
160
|
if (await remoteIdentity(root, config.remote, stateRoot) !== config.identity) fail('CONFLICT', 'Mapped folder disappeared or changed identity; no automatic recreation');
|
|
159
161
|
succeeded(await rclone(root, bisyncArgs(root, config)), 'Native bisync');
|
|
160
162
|
}
|
|
161
|
-
status = { ...status, state: 'indexing', syncedAt: new Date().toISOString() };
|
|
163
|
+
status = { ...status, state: 'indexing', step: 'index', syncedAt: new Date().toISOString() };
|
|
162
164
|
await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
|
|
163
|
-
try { status.textMirror = await mirrorTransfer(root); }
|
|
165
|
+
try { status.textMirror = await mirrorTransfer(root, step); }
|
|
164
166
|
catch (error) { status.textMirror = { state: 'pending', error: { code: error.code || 'UNAVAILABLE', message: error.message } }; }
|
|
167
|
+
await step('index');
|
|
165
168
|
const index = await refreshIndex(root);
|
|
166
169
|
status = { ...status, state: index.conflicts?.length ? 'synced-with-conflicts' : index.pending.length ? 'indexed-with-pending-extraction' : 'synced-and-indexed', indexedAt: index.indexedAt, embedded: index.embedded };
|
|
167
170
|
} catch (error) {
|
|
@@ -169,6 +172,7 @@ export async function syncRun(root, stateRoot = root, { signal } = {}) {
|
|
|
169
172
|
await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
|
|
170
173
|
throw error;
|
|
171
174
|
}
|
|
175
|
+
delete status.step;
|
|
172
176
|
await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
|
|
173
177
|
if (status.textMirror?.state === 'pending') fail('UNAVAILABLE', 'GitHub text mirror pending: ' + status.textMirror.error.message);
|
|
174
178
|
return status;
|
package/test/git-sync.test.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import { execFileSync } from 'node:child_process';
|
|
|
7
7
|
import { Readable } from 'node:stream';
|
|
8
8
|
import { gitAdopt, gitTransfer, git, repositoryURL } from '../src/git-sync.mjs';
|
|
9
9
|
import { locked, put, digest, organize, jsonBytes } from '../src/store.mjs';
|
|
10
|
-
import { syncPolicy, syncStatus } from '../src/sync.mjs';
|
|
10
|
+
import { syncPolicy, syncRun, syncStatus } from '../src/sync.mjs';
|
|
11
11
|
|
|
12
12
|
async function setup(t) {
|
|
13
13
|
const base = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), 'library-git-')));
|
|
@@ -302,3 +302,39 @@ test('existing checkout rejects staged work, branch changes and origin changes w
|
|
|
302
302
|
await assert.rejects(cycle(root, config), { code: 'CONFLICT' });
|
|
303
303
|
assert.equal(await fs.readFile(path.join(checkout, 'note0.md'), 'utf8'), 'User staged edit');
|
|
304
304
|
});
|
|
305
|
+
|
|
306
|
+
test('a stalled Git transport ends the cycle UNAVAILABLE, releases the writer lock and the next sync succeeds', async t => {
|
|
307
|
+
const { base, root, remote, outside } = await setup(t);
|
|
308
|
+
const { config } = await gitAdopt(root, remote);
|
|
309
|
+
// A transport that connects, then never answers.
|
|
310
|
+
const stall = path.join(base, 'stall.sh');
|
|
311
|
+
await fs.writeFile(stall, '#!/bin/sh\nexec sleep 120\n', { mode: 0o755 });
|
|
312
|
+
await git(root, config, ['config', 'remote.origin.uploadpack', stall]);
|
|
313
|
+
await put(root, 'stalled.md', Readable.from(['# Stalled\nMarigold ledger.']), { expected: 'new', key: 'stalled' });
|
|
314
|
+
const previous = process.env.EZ_LIBRARY_GIT_TIMEOUT_MS;
|
|
315
|
+
process.env.EZ_LIBRARY_GIT_TIMEOUT_MS = '1500';
|
|
316
|
+
t.after(() => { if (previous === undefined) delete process.env.EZ_LIBRARY_GIT_TIMEOUT_MS; else process.env.EZ_LIBRARY_GIT_TIMEOUT_MS = previous; });
|
|
317
|
+
const started = Date.now();
|
|
318
|
+
await assert.rejects(syncRun(root), { code: 'UNAVAILABLE', message: /timed out/ });
|
|
319
|
+
assert(Date.now() - started < 30000, 'the stalled fetch was stopped, not waited for');
|
|
320
|
+
const failed = (await syncStatus(root)).status;
|
|
321
|
+
assert.equal(failed.state, 'sync-error');
|
|
322
|
+
assert.equal(failed.step, 'fetch');
|
|
323
|
+
assert.equal(failed.error.code, 'UNAVAILABLE');
|
|
324
|
+
// The writer lock is free: another writer is not BUSY.
|
|
325
|
+
await put(root, 'after.md', Readable.from(['# After\nHeron.']), { expected: 'new', key: 'after' });
|
|
326
|
+
await git(root, config, ['config', '--unset', 'remote.origin.uploadpack']);
|
|
327
|
+
// The next cycle takes the same writer lock and transfers both files.
|
|
328
|
+
const result = await cycle(root, config);
|
|
329
|
+
assert.equal(result.remoteVerified, true);
|
|
330
|
+
assert.match(outside(['--git-dir', remote, 'show', 'main:stalled.md']), /Marigold/);
|
|
331
|
+
assert.match(outside(['--git-dir', remote, 'show', 'main:after.md']), /Heron/);
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
test('a bounded call that exits in time settles even while a grandchild still holds its pipes', async t => {
|
|
335
|
+
const { native } = await import('../src/native.mjs');
|
|
336
|
+
const root = await fs.mkdtemp(path.join(tmpdir(), 'ez-library-native-'));
|
|
337
|
+
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
|
338
|
+
const result = await native(root, '/bin/sh', ['-c', 'sleep 2 & exit 0'], { timeout: 500 });
|
|
339
|
+
assert.equal(result.code, 0);
|
|
340
|
+
});
|
package/test/library.test.mjs
CHANGED
|
@@ -156,6 +156,47 @@ test('a live writer is waited for instead of failing BUSY', async t => {
|
|
|
156
156
|
await assert.rejects(fs.stat(lock), code('ENOENT'));
|
|
157
157
|
});
|
|
158
158
|
|
|
159
|
+
test('a lock left by a dead process on this host is reclaimed, including a restart that reuses our pid', async t => {
|
|
160
|
+
const { hostname } = await import('node:os');
|
|
161
|
+
for (const pid of [process.pid, 2 ** 22 + 7]) {
|
|
162
|
+
const root = await fixture(t); const lock = path.join(root, '.writer-lock');
|
|
163
|
+
await fs.mkdir(lock);
|
|
164
|
+
await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid, host: hostname(), at: '2026-11-24T08:10:12.895Z' }));
|
|
165
|
+
assert.equal(await locked(root, () => 'ran'), 'ran');
|
|
166
|
+
await assert.rejects(fs.stat(lock), code('ENOENT'));
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test('concurrent processes reclaim one dead lock without overlapping writers', async t => {
|
|
171
|
+
const { hostname } = await import('node:os');
|
|
172
|
+
const { spawn } = await import('node:child_process');
|
|
173
|
+
const store = new URL('../src/store.mjs', import.meta.url).href;
|
|
174
|
+
const child = `const { locked } = await import(${JSON.stringify(store)}); const fs = await import('node:fs/promises');
|
|
175
|
+
await locked(process.argv[1], async () => { const f = process.argv[1] + '/in'; await fs.writeFile(f, '', { flag: 'wx' });
|
|
176
|
+
await new Promise(r => setTimeout(r, 30)); await fs.rm(f); });`;
|
|
177
|
+
for (let round = 0; round < 5; round++) {
|
|
178
|
+
const root = await fixture(t); const lock = path.join(root, '.writer-lock');
|
|
179
|
+
await fs.mkdir(lock);
|
|
180
|
+
await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: 2 ** 22 + 7, host: hostname(), at: '2026-11-24T08:10:12.895Z' }));
|
|
181
|
+
const codes = await Promise.all(Array.from({ length: 4 }, () => new Promise(resolve =>
|
|
182
|
+
spawn(process.execPath, ['--input-type=module', '-e', child, root], { stdio: 'inherit' }).on('exit', resolve))));
|
|
183
|
+
assert.deepEqual(codes, [0, 0, 0, 0]);
|
|
184
|
+
await assert.rejects(fs.stat(lock), code('ENOENT'));
|
|
185
|
+
await assert.rejects(fs.stat(`${lock}.reclaim`), code('ENOENT'));
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test('a reclaim mutex left by a crash makes writers wait, not spin', async t => {
|
|
190
|
+
const { hostname } = await import('node:os');
|
|
191
|
+
const root = await fixture(t); const lock = path.join(root, '.writer-lock');
|
|
192
|
+
await fs.mkdir(lock); await fs.mkdir(`${lock}.reclaim`);
|
|
193
|
+
await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: 2 ** 22 + 7, host: hostname(), at: '2026-11-24T08:10:12.895Z' }));
|
|
194
|
+
const cpu = process.cpuUsage();
|
|
195
|
+
await assert.rejects(locked(root, () => assert.fail('must not run'), { signal: AbortSignal.timeout(1000) }), { name: 'AbortError' });
|
|
196
|
+
const used = process.cpuUsage(cpu); assert((used.user + used.system) / 1000 < 400, 'waiting must sleep between attempts');
|
|
197
|
+
assert((await fs.stat(lock)).isDirectory());
|
|
198
|
+
});
|
|
199
|
+
|
|
159
200
|
test('an aborted wait gives up without taking the lock', async t => {
|
|
160
201
|
const root = await fixture(t); const lock = path.join(root, '.writer-lock');
|
|
161
202
|
await fs.mkdir(lock);
|