@narumitw/pi-sync-daemon 0.3.0 → 0.5.0

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.
@@ -0,0 +1,55 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import lockfile from "proper-lockfile";
4
+ import { acquireStartupLock } from "./client.js";
5
+ import { revokeRetainedGrants } from "./consent.js";
6
+ import { withStateDirectoryGuardForRoot } from "./engine/state/state-directory.js";
7
+ import { canonicalRootGuard, privateDirectory, processExited, readIdentity, readUpgradeOwner, runtimePaths, upgradeArchivePath, upgradeFile, } from "./identity.js";
8
+ /** Explicit repair never launches or sends requests to a daemon. */
9
+ export async function repairUpgrade(root) {
10
+ const paths = await runtimePaths(root);
11
+ const assertRoot = canonicalRootGuard(paths.root);
12
+ await privateDirectory(paths.directory);
13
+ const releaseStartup = await acquireStartupLock(paths);
14
+ try {
15
+ const pending = await readUpgradeOwner(paths);
16
+ if (!pending)
17
+ return { repaired: false };
18
+ // Exclude direct `serve`. Use a distinct lock key so proper-lockfile can track both locks.
19
+ const releaseOwner = await lockfile.lock(paths.owner, {
20
+ realpath: false,
21
+ lockfilePath: paths.owner,
22
+ stale: 30_000,
23
+ update: 5_000,
24
+ });
25
+ try {
26
+ const identity = await readIdentity(paths);
27
+ if (identity && (identity.instance !== pending.instance || identity.pid !== pending.pid))
28
+ throw new Error("The recorded upgrade owner changed; private state was retained.");
29
+ if (!(await processExited(pending)))
30
+ throw new Error("Cannot verify that the old Pi Sync daemon has exited; private state was retained.");
31
+ assertRoot();
32
+ // The archive also marks a repair in progress before consent or recovery records change.
33
+ const archive = upgradeArchivePath(paths, pending);
34
+ await privateDirectory(archive);
35
+ const revokedGrants = await withStateDirectoryGuardForRoot(paths.root, () => {
36
+ assertRoot();
37
+ return revokeRetainedGrants(paths.root);
38
+ });
39
+ assertRoot();
40
+ // Keep the original bytes private. Move the barrier last so interrupted repair can be retried.
41
+ if (identity)
42
+ await fs.rename(paths.identity, path.join(archive, path.basename(paths.identity)));
43
+ assertRoot();
44
+ const barrier = upgradeFile(paths);
45
+ await fs.rename(barrier, path.join(archive, path.basename(barrier)));
46
+ return { repaired: true, revokedGrants, archive };
47
+ }
48
+ finally {
49
+ await releaseOwner();
50
+ }
51
+ }
52
+ finally {
53
+ await releaseStartup();
54
+ }
55
+ }
@@ -103,9 +103,29 @@ When no registered live PID remains and no valid explicit after-exit grant cover
103
103
 
104
104
  After grace, stop new automatic work and cancel cancellable work. Drain foreground and monitor work, committed writes, admission, queue-release acknowledgements, peer persistence, and owned callbacks before endpoint and owner-lock release. Do not add a closing sync or model request. Preserve journals, backups, request accounting, and existing transfer permissions. Recheck liveness, consent, generation, and ownership after asynchronous reads or drains; the final admission boundary must let an earlier queued attach win and make a later attach observe closing. Cleanup failure is not successful exit.
105
105
 
106
- After quiescence, the authenticated final fence returns `RemoteError.name = "DaemonStoppingError"` to rejected admissions and handshakes on the existing version-1 protocol. `ensureDaemon()` recognizes only this error and waits at most 30 seconds for the recorded PID to exit before singleton startup. The lightweight public `waitForDaemonExit(identity, signal)` helper provides the same cancellable process-exit check for an attach race; it never kills the owner or treats lost contact as exit. Pi Sync retries only an unpublished connection, at most once, and does not replay submitted operations. A rejected first attach preserves this stopping error after local disposal when no callbacks or prior attachment can own grants; a failed cleanup transport remains available as the error cause. Other combined attach and cleanup failures remain aggregate errors and do not authorize a retry. `DaemonConnection.attach(signal)` cancels queued admission without stopping the shared owner; the signal does not own the established connection's lifetime. The next eligible interactive client or explicit command may start after proven owner exit. An incompatible identity, uncertain ownership, or unreachable live owner still fails closed. Print/JSON never launch a service. Manual stop and restart retain explicit behavior. Authorization uncertainty and failed revocation remain paused, not cleared by an implicit restart that could restore an older persisted grant.
107
-
108
- A later command can reconnect after a cancelled or failed unpublished attach. First, Pi Sync confirms the old connection's detach and drain, then releases its local queue grants. It uses a fresh client ID and generation for the next connection. Daemon retirement records stay intact, so late requests cannot revive the old attempt. Failed cleanup blocks a new identity and operation; it does not release uncertain grants. The established connection keeps its identity. A cancelled or submitted operation is never replayed by this recovery.
106
+ After quiescence, the authenticated final fence returns `RemoteError.name = "DaemonStoppingError"` to rejected admissions and handshakes on the existing version-1 protocol. `ensureDaemon()` recognizes this idle-stop error and waits at most 30 seconds for the recorded PID to exit before singleton startup. The lightweight public `waitForDaemonExit(identity, signal)` helper provides the same cancellable process-exit check for an attach race; it never kills the owner or treats lost contact as exit. Pi Sync retries only an unpublished connection, at most once, and does not replay submitted operations. A rejected first attach preserves this stopping error after local disposal when no callbacks or prior attachment can own grants; a failed cleanup transport remains available as the error cause. Other combined attach and cleanup failures remain aggregate errors and do not authorize a retry. `DaemonConnection.attach(signal)` cancels queued admission without stopping the shared owner; the signal does not own the established connection's lifetime. The next eligible interactive client or explicit command may start after proven owner exit. An incompatible identity, uncertain ownership, or unreachable live owner still fails closed. Print/JSON never launch a service. Manual stop and restart retain explicit behavior. Authorization uncertainty and failed revocation remain paused, not cleared by an implicit restart that could restore an older persisted grant.
107
+
108
+ A later command can reconnect after a cancelled or failed unpublished attach. First, Pi Sync confirms the old connection's detach and drain, then releases its local queue grants. It uses a fresh client ID and generation for the next connection. Daemon retirement records stay intact, so late requests cannot revive the old attempt. Failed cleanup blocks a new identity and operation; it does not release uncertain grants. A cancelled or submitted operation is never replayed by this recovery.
109
+
110
+ ### Recovering expired contact
111
+
112
+ A running daemon can expire a Pi session's heartbeat after a computer sleeps. A
113
+ cleanup poll still returns callbacks and job results. Its optional version-1
114
+ `contact` field distinguishes `expired` from `active` and `inactive`. Only a
115
+ heartbeat expired by this daemon instance gets `expired`. A facts update from
116
+ the matching expired client returns `ClientContactExpiredError`. An older
117
+ service can omit `contact`, which does not authorize repair.
118
+
119
+ `DaemonConnection.resumeContact()` sends the same client's current facts to
120
+ the authenticated owner with `resume-contact`. The daemon retains the existing
121
+ participant, protects the live session, and fences publication with the same
122
+ admission gate used by attach. Deliberate pauses, handoffs, retired identities,
123
+ and peers loaded from disk are not eligible. Cleanup polling stays available
124
+ while admission waits. Unknown work outcomes and unconfirmed queue releases
125
+ block repair. Pi Sync supplies non-ready, busy facts during admission, then
126
+ publishes fresh facts after confirmation. The binding and consent checks still
127
+ apply. A failed or uncertain repair does not start a replacement owner, release
128
+ uncertain grants, or resubmit work.
109
129
 
110
130
  ## Repository lifetime smoke
111
131
 
@@ -119,6 +139,30 @@ node node_modules/.cache/pi-extensions-test/packages/pi-sync/test/idle-exit-cli-
119
139
 
120
140
  Do not rebuild while a smoke-owned daemon is running. Linux containers need an init process to reap detached children. This smoke does not verify native Windows behavior, terminal logout, physical power loss, or real-data cutover.
121
141
 
142
+ ## Package upgrades
143
+
144
+ The authenticated `hello` response reports the running package build separately from its protocol
145
+ version. Older releases did not report a build. During active startup, the client holds the existing
146
+ startup lock, sends an authenticated `stop` to an older or unversioned owner, and waits for owner exit
147
+ and identity release. A private exit record survives cancellation and timeout. It keeps the PID
148
+ and, when available, a verified Linux process birth marker. For a marked owner, `ESRCH` confirms
149
+ absence only in the recorded PID namespace. A PID-only record still requires `ESRCH`. Later callers
150
+ use the record even if the old identity file is gone. Concurrent startup can wait for the drain
151
+ under a bounded, cancellable lock wait. The client checks the root again before launching a replacement.
152
+ It does not stop a newer build or start a replacement for an unreachable live owner. A retained unattended grant blocks
153
+ implicit replacement because a legacy owner cannot report a failed revocation. The client reads
154
+ consent under the state migration guard and releases it before sending stop. Passive attachment can
155
+ protect live sessions without starting a replacement or submitting sync operations on the old build.
156
+ An interactive session switch attempts the same protection-only attachment if the upgrade fails.
157
+
158
+ For a blocked pending upgrade, `repair-upgrade` checks exit under the startup and owner locks.
159
+ It revokes retained unattended grants under the state migration guard on all platforms. On
160
+ non-Windows platforms, it also syncs the consent directory before archiving the upgrade barrier.
161
+ Consent storage reserves one byte per retained grant so that revocation fits even for compact JSON
162
+ at the old size limit. Repair reuses the same private archive if interrupted. Normal startup
163
+ cannot clear an incomplete repair. The command does not start the daemon. Clean shutdowns still
164
+ clear the barrier without manual repair.
165
+
122
166
  ## Cross-process apply protocol
123
167
 
124
168
  Acquire target queues in deterministic client-ID and canonical-target order. Each reservation has a job-bound ID and the peer's session generation. The client holds Pi's public queues until the daemon acknowledges completion with a `queue-release` callback. Release uses the reservation ID even if the grant response was lost. A cancelled UI callback does not release an acquired grant. If IPC disappears, hold the grant until explicit release or proof that its daemon process exited. A timeout is not such proof.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-sync-daemon",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "A local synchronization daemon with a versioned client API.",
5
5
  "type": "module",
6
6
  "license": "MIT",