@huaqiu/dsh-plugin-log 0.6.23 → 0.6.25

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,268 @@
1
+ /**
2
+ * Exclusive, OS-backed ownership of ONE DSH instance log directory.
3
+ *
4
+ * The lock is a **bound IPC endpoint held open by the owning DSH process**:
5
+ *
6
+ * Windows : named pipe \\.\pipe\hq-edge-dsh-instance-<sha256(dir)>
7
+ * POSIX : unix socket <dir>/.owner.sock
8
+ *
9
+ * Creating a second server on the same endpoint fails with EADDRINUSE while
10
+ * the owner is alive, and the OS closes the handle — releasing the lock — the
11
+ * instant the owner terminates, including abnormal termination. There is no
12
+ * PID check, no heartbeat and no stale-timestamp heuristic: a DSH process that
13
+ * crashes must not leave a lock that a later process has to guess about.
14
+ *
15
+ * The endpoint is keyed by the INSTANCE DIRECTORY, so two DSH processes under
16
+ * the same HQ Edge process, two DSH processes under different Edge processes,
17
+ * and a DSH process plus the Edge maintenance job never contend for the same
18
+ * lock unless they genuinely target the same directory.
19
+ *
20
+ * `owner.lock` is a diagnostic JSONL file only. Its existence NEVER implies
21
+ * ownership, and it is intentionally left behind after exit: it is the record
22
+ * of which process last owned the directory and when.
23
+ */
24
+ import { createConnection, createServer, type Server } from 'node:net'
25
+ import { createHash } from 'node:crypto'
26
+ import { closeSync, existsSync, mkdirSync, openSync, unlinkSync, writeSync } from 'node:fs'
27
+ import { join, resolve } from 'node:path'
28
+
29
+ import { appendDiagnostic, errorCode } from './fs-utils.js'
30
+ import { OWNER_LOCK_FILENAME, RECOVERY_LOG_FILENAME } from './identity.js'
31
+
32
+ const PIPE_PREFIX = '\\\\.\\pipe\\hq-edge-dsh-instance-'
33
+ const SOCKET_FILENAME = '.owner.sock'
34
+
35
+ export interface DshOwnershipHandle {
36
+ readonly instanceDir: string
37
+ readonly dshInstanceId: string
38
+ readonly released: boolean
39
+ /** Idempotent. Releases the OS handle; never deletes another owner's data. */
40
+ release(): void
41
+ }
42
+
43
+ function normalizedDir(dir: string): string {
44
+ const absolute = resolve(dir)
45
+ return process.platform === 'win32' ? absolute.toLowerCase() : absolute
46
+ }
47
+
48
+ /** Deterministic, filesystem-safe lock key. Not an identity — a lookup key. */
49
+ export function ownershipKey(dir: string): string {
50
+ return createHash('sha256').update(normalizedDir(dir)).digest('hex').slice(0, 32)
51
+ }
52
+
53
+ function endpointFor(dir: string): string {
54
+ return process.platform === 'win32' ? `${PIPE_PREFIX}${ownershipKey(dir)}` : join(resolve(dir), SOCKET_FILENAME)
55
+ }
56
+
57
+ function recordOwnerClaim(dir: string, dshInstanceId: string): void {
58
+ appendDiagnostic(join(dir, OWNER_LOCK_FILENAME), {
59
+ event: 'ownership-claimed',
60
+ pid: process.pid,
61
+ dshInstanceId,
62
+ acquiredAt: new Date().toISOString(),
63
+ })
64
+ }
65
+
66
+ class DshOwnershipHandleImpl implements DshOwnershipHandle {
67
+ private _released = false
68
+
69
+ constructor(
70
+ public readonly instanceDir: string,
71
+ public readonly dshInstanceId: string,
72
+ private readonly server: Server,
73
+ private readonly socketFile: string | null,
74
+ private readonly diagnostics: boolean,
75
+ ) {}
76
+
77
+ get released(): boolean {
78
+ return this._released
79
+ }
80
+
81
+ release(): void {
82
+ if (this._released) return
83
+ this._released = true
84
+ try {
85
+ this.server.close()
86
+ } catch {
87
+ /* already closed */
88
+ }
89
+ if (this.socketFile) {
90
+ try {
91
+ unlinkSync(this.socketFile)
92
+ } catch {
93
+ /* best effort — a stale socket is handled on the next acquisition */
94
+ }
95
+ }
96
+ if (this.diagnostics) {
97
+ appendDiagnostic(join(this.instanceDir, OWNER_LOCK_FILENAME), {
98
+ event: 'ownership-released',
99
+ pid: process.pid,
100
+ dshInstanceId: this.dshInstanceId,
101
+ releasedAt: new Date().toISOString(),
102
+ })
103
+ }
104
+ }
105
+ }
106
+
107
+ function bindServer(endpoint: string): Promise<{ server: Server; ok: boolean; code?: string }> {
108
+ return new Promise((resolvePromise) => {
109
+ const server = createServer()
110
+ let settled = false
111
+ const finish = (ok: boolean, code?: string) => {
112
+ if (settled) return
113
+ settled = true
114
+ resolvePromise({ server, ok, code })
115
+ }
116
+ // A listener MUST exist before listen(): an unhandled 'error' event on a
117
+ // Server would be an uncaught exception, exactly the failure mode logging
118
+ // must never introduce.
119
+ server.once('error', (err: NodeJS.ErrnoException) => finish(false, err.code ?? 'UNKNOWN'))
120
+ server.once('listening', () => finish(true))
121
+ try {
122
+ server.listen(endpoint)
123
+ } catch (err) {
124
+ finish(false, errorCode(err))
125
+ }
126
+ })
127
+ }
128
+
129
+ function delay(ms: number): Promise<void> {
130
+ return new Promise((resolve) => {
131
+ const timer = setTimeout(resolve, ms)
132
+ timer.unref()
133
+ })
134
+ }
135
+
136
+ /**
137
+ * Binds the endpoint, retrying briefly while it reports EADDRINUSE.
138
+ *
139
+ * A process that has JUST released the endpoint can take a few milliseconds to
140
+ * disappear (Windows closes the named-pipe instance asynchronously). Without
141
+ * the retry, a recovery pass that runs immediately after a release mistakes a
142
+ * dying owner for a live one and skips the directory. A genuinely live owner
143
+ * keeps failing every attempt, so this only removes the race — it never steals
144
+ * a held lock.
145
+ */
146
+ async function bindWithRetry(
147
+ endpoint: string,
148
+ ): Promise<{ server: Server; ok: boolean; code?: string }> {
149
+ let bound = await bindServer(endpoint)
150
+ for (let attempt = 0; attempt < 4 && !bound.ok && bound.code === 'EADDRINUSE'; attempt += 1) {
151
+ try {
152
+ bound.server.close()
153
+ } catch {
154
+ /* never listened */
155
+ }
156
+ await delay(15 * (attempt + 1))
157
+ bound = await bindServer(endpoint)
158
+ }
159
+ return bound
160
+ }
161
+
162
+ /** POSIX only: is the socket file a live owner or a stale crash leftover? */
163
+ function socketIsLive(socketFile: string): Promise<boolean> {
164
+ return new Promise((resolvePromise) => {
165
+ const socket = createConnection(socketFile)
166
+ const done = (live: boolean) => {
167
+ socket.destroy()
168
+ resolvePromise(live)
169
+ }
170
+ socket.once('connect', () => done(true))
171
+ socket.once('error', () => done(false))
172
+ socket.setTimeout(250, () => done(false))
173
+ })
174
+ }
175
+
176
+ /**
177
+ * Attempts exclusive ownership. Returns `null` when another live process owns
178
+ * the directory — callers MUST then leave the directory completely alone.
179
+ *
180
+ * Asynchronous because a socket bind resolves on the event loop. The runtime
181
+ * gates opening the active log file on this promise, so no active file is ever
182
+ * written before ownership is established.
183
+ */
184
+ export async function acquireDshOwnership(
185
+ instanceDir: string,
186
+ dshInstanceId: string,
187
+ options: { diagnostics?: boolean } = {},
188
+ ): Promise<DshOwnershipHandle | null> {
189
+ const diagnostics = options.diagnostics !== false
190
+ try {
191
+ mkdirSync(instanceDir, { recursive: true })
192
+ } catch {
193
+ return null
194
+ }
195
+
196
+ const endpoint = endpointFor(instanceDir)
197
+ let bound = await bindWithRetry(endpoint)
198
+
199
+ if (!bound.ok && process.platform !== 'win32' && bound.code === 'EADDRINUSE') {
200
+ if (existsSync(endpoint) && !(await socketIsLive(endpoint))) {
201
+ try {
202
+ unlinkSync(endpoint)
203
+ } catch {
204
+ /* another recovery process won the cleanup race */
205
+ }
206
+ bound = await bindWithRetry(endpoint)
207
+ }
208
+ }
209
+
210
+ if (!bound.ok) {
211
+ try {
212
+ bound.server.close()
213
+ } catch {
214
+ /* ignore */
215
+ }
216
+ return null
217
+ }
218
+
219
+ // Only the CONFIRMED owner may write into the directory. A losing process
220
+ // must never append to another live owner's `owner.lock`.
221
+ if (diagnostics) recordOwnerClaim(instanceDir, dshInstanceId)
222
+
223
+ // Holding a lock must not keep the DSH process alive on its own.
224
+ bound.server.unref()
225
+ return new DshOwnershipHandleImpl(
226
+ instanceDir,
227
+ dshInstanceId,
228
+ bound.server,
229
+ process.platform === 'win32' ? null : endpoint,
230
+ diagnostics,
231
+ )
232
+ }
233
+
234
+ /**
235
+ * Historical recovery / cleanup entry point. Stricter than
236
+ * {@link acquireDshOwnership}: it refuses to create the directory (a deleted
237
+ * directory must stay deleted) and writes no diagnostics into it.
238
+ */
239
+ export async function acquireHistoricalDshOwnership(
240
+ instanceDir: string,
241
+ dshInstanceId: string,
242
+ ): Promise<DshOwnershipHandle | null> {
243
+ if (!existsSync(instanceDir)) return null
244
+ return acquireDshOwnership(instanceDir, dshInstanceId, { diagnostics: false })
245
+ }
246
+
247
+ /** Non-destructive probe: true when nobody currently owns the directory. */
248
+ export async function probeDshOwnership(instanceDir: string): Promise<boolean> {
249
+ if (!existsSync(instanceDir)) return false
250
+ const handle = await acquireDshOwnership(instanceDir, 'ownership-probe', { diagnostics: false })
251
+ if (!handle) return false
252
+ handle.release()
253
+ return true
254
+ }
255
+
256
+ /** Writes a recovery diagnostic without touching a live owner's data. */
257
+ export function recordRecoveryDiagnostic(instanceDir: string, record: Record<string, unknown>): void {
258
+ try {
259
+ const fd = openSync(join(instanceDir, RECOVERY_LOG_FILENAME), 'a', 0o600)
260
+ try {
261
+ writeSync(fd, Buffer.from(`${JSON.stringify({ time: new Date().toISOString(), ...record })}\n`))
262
+ } finally {
263
+ closeSync(fd)
264
+ }
265
+ } catch {
266
+ /* diagnostics must never break recovery */
267
+ }
268
+ }
package/src/paths.ts CHANGED
@@ -1,85 +1,132 @@
1
1
  /**
2
2
  * Inlined from `@hqedge/paths` (hq-edge/packages/paths/src/index.ts) so this
3
- * plugin stays fully self-contained — no runtime dependency on the published
3
+ * package stays fully self-contained — no runtime dependency on the published
4
4
  * package. Keep in sync when `@hqedge/paths` changes its path conventions.
5
5
  *
6
6
  * ────────────────────────────────────────────────────────────────────────────
7
7
  * Shared path resolution for HQ Edge runtimes.
8
8
  *
9
- * The single source of truth for where HQ Edge places per-user directories.
10
- * `getHqEdgeHome()` is the root: every other path getter (`getLogBaseDir`,
11
- * `getLogDir`) is derived from it, so all HQ Edge user directories live under
12
- * one self-contained tree and every consumer resolves the same location.
13
- *
14
9
  * The home is **the same on every platform** — `~/.hq-edge/` — because HQ Edge
15
10
  * is a developer/EDA runtime environment rather than a conventional desktop
16
11
  * app: a single dotfile under `$HOME` keeps logging, diagnostics, DSH
17
12
  * integration, CLI behavior and documentation identical on macOS / Linux /
18
- * Windows, instead of introducing a second filesystem convention
19
- * (`%LOCALAPPDATA%\hq-edge` or `~/.local/share/hq-edge`) per platform.
20
- * `HQ_EDGE_HOME` is the universal escape hatch (tests, bundling, portable
21
- * installs, CI).
13
+ * Windows.
14
+ *
15
+ * ## Log tree layout (docs/tasks/dsh-plugin-log-isolation.md §3)
16
+ *
17
+ * <home>/logs/instances/<edge-instance-id>/
18
+ * server.<date>.log ← owned by the HQ Edge process
19
+ * dsh/
20
+ * <dsh-instance-id>/
21
+ * instance.json ← this package writes it
22
+ * owner.lock ← diagnostic only
23
+ * dsh.<date>.log ← owned by THIS DSH process
24
+ * dsh.<date>.log.gz ← published archive
22
25
  *
23
- * Note: the immutable HQ Edge runtime (`<installRoot>/dsh`,
24
- * `<installRoot>/dsh-plugins`) and `<KiCad installation>/` (application
25
- * install) are deliberately NOT this home — user data, managed runtime and
26
- * installation stay distinct. Mutable per-version DSH state lives UNDER this
27
- * home at `<home>/<version>/dsh-home` (see dshHome.ts). The
28
- * `~/.hq/hq-edge/<version>/` path from an earlier design draft never landed.
26
+ * A DSH process never writes into another DSH process's directory, and never
27
+ * into its parent Edge instance directory: it only appends the
28
+ * `<dsh-instance-id>` level below the `dsh/` root it is handed.
29
+ *
30
+ * `HQ_EDGE_HOME` / `HQ_EDGE_LOG_DIR` / `DSH_LOG_ROOT` are the escape hatches
31
+ * (tests, portable installs, CI). Per repository convention a relative
32
+ * `HQ_EDGE_HOME` is ignored rather than resolved against the CWD.
29
33
  */
30
34
  import { homedir } from 'node:os'
31
- import { join } from 'node:path'
35
+ import { isAbsolute, join } from 'node:path'
32
36
 
33
37
  /**
34
38
  * Application identifier used for OS-native directories.
35
39
  */
36
40
  export const APP_ID = 'hq-edge'
37
41
 
42
+ /** True for a non-empty absolute path — the only accepted override shape. */
43
+ function absoluteOverride(value: string | undefined): string | undefined {
44
+ if (value === undefined) return undefined
45
+ const trimmed = value.trim()
46
+ if (trimmed.length === 0) return undefined
47
+ return isAbsolute(trimmed) ? trimmed : undefined
48
+ }
49
+
38
50
  /**
39
51
  * Resolves the per-user data home directory for HQ Edge — the single root from
40
52
  * which every other HQ Edge path getter is derived.
41
53
  *
42
54
  * macOS / Linux / Windows: ~/.hq-edge/
43
55
  *
44
- * Unconditional across platforms (see the file header for the rationale). The
45
- * path may be overridden explicitly via `override` or the `HQ_EDGE_HOME`
46
- * environment variable (useful for tests / bundling / portable installs).
56
+ * The path may be overridden explicitly via `override` or the `HQ_EDGE_HOME`
57
+ * environment variable (tests / bundling / portable installs).
47
58
  */
48
59
  export function getHqEdgeHome(override?: string): string {
49
- if (override) return override
50
- if (process.env.HQ_EDGE_HOME) return process.env.HQ_EDGE_HOME
60
+ return getHqEdgeHomeFrom(process.env, override)
61
+ }
51
62
 
63
+ /**
64
+ * Environment-parameterized form of {@link getHqEdgeHome}. Identity resolution
65
+ * uses this so the result depends on the environment it was HANDED, never on
66
+ * whatever `process.env` happens to contain at that moment.
67
+ */
68
+ export function getHqEdgeHomeFrom(env: NodeJS.ProcessEnv, override?: string): string {
69
+ const explicit = absoluteOverride(override)
70
+ if (explicit) return explicit
71
+ const fromEnv = absoluteOverride(env.HQ_EDGE_HOME)
72
+ if (fromEnv) return fromEnv
52
73
  return join(homedir(), '.hq-edge')
53
74
  }
54
75
 
55
76
  /**
56
- * Resolves the base log directory for HQ Edge.
57
- *
58
- * Built on top of `getHqEdgeHome()` as `<home>/logs` on every platform, so
59
- * logs live inside the HQ Edge home tree:
60
- *
61
- * macOS / Linux / Windows: ~/.hq-edge/logs/
62
- *
63
- * The path may be overridden explicitly via `override` or the
64
- * `HQ_EDGE_LOG_DIR` environment variable.
77
+ * Resolves the base log directory for HQ Edge: `<home>/logs` on every
78
+ * platform. Overridable via `override` or `HQ_EDGE_LOG_DIR`.
65
79
  */
66
80
  export function getLogBaseDir(override?: string): string {
67
- if (override) return override
68
- if (process.env.HQ_EDGE_LOG_DIR) return process.env.HQ_EDGE_LOG_DIR
69
- return join(getHqEdgeHome(), 'logs')
81
+ return getLogBaseDirFrom(process.env, override)
82
+ }
83
+
84
+ /** Environment-parameterized form of {@link getLogBaseDir}. */
85
+ export function getLogBaseDirFrom(env: NodeJS.ProcessEnv, override?: string): string {
86
+ const explicit = absoluteOverride(override)
87
+ if (explicit) return explicit
88
+ const fromEnv = absoluteOverride(env.HQ_EDGE_LOG_DIR)
89
+ if (fromEnv) return fromEnv
90
+ return join(getHqEdgeHomeFrom(env), 'logs')
70
91
  }
71
92
 
72
93
  /**
73
94
  * Resolves the per-component log directory, e.g. `<base>/dsh-plugins/`.
74
95
  *
75
- * The directory is created on demand by the rotating file stream.
76
- *
77
- * Note: the directory name is the component verbatim — there is no implicit
78
- * version scoping. Callers that need version isolation (e.g. the DSH home,
79
- * which keeps one tree per HQ Edge release) must layer it on top of
80
- * `getHqEdgeHome()` themselves. Cross-version logs (server, plugin diagnostics)
81
- * intentionally share a tree so a single `tail -F` follows them across upgrades.
96
+ * LEGACY. `dsh-plugins/` was the pre-isolation shared plugin log directory and
97
+ * is no longer written to; it is only inspected by maintenance so old files can
98
+ * be reported (never migrated or deleted). New per-process logs MUST go through
99
+ * {@link getDshLogRoot} + the owning process's instance id.
82
100
  */
83
101
  export function getLogDir(component: string, baseDirOverride?: string): string {
84
102
  return join(getLogBaseDir(baseDirOverride), component)
85
103
  }
104
+
105
+ /** `<base>/instances` — one directory per HQ Edge process. */
106
+ export function getInstanceLogRoot(baseDirOverride?: string): string {
107
+ return join(getLogBaseDir(baseDirOverride), 'instances')
108
+ }
109
+
110
+ /**
111
+ * `<base>/instances/<edge-instance-id>/dsh` — the DSH log root owned by one HQ
112
+ * Edge process. Every DSH launch under that process creates its own child
113
+ * directory here.
114
+ *
115
+ * When `edgeInstanceId` is unknown (a standalone `dsh` used in development or a
116
+ * test), the root degrades to `<base>/dsh`, deliberately WITHOUT an
117
+ * `instances/<id>` level: inventing an Edge identity would attribute DSH logs
118
+ * to an HQ Edge process that does not exist.
119
+ */
120
+ export function getDshLogRoot(edgeInstanceId: string | null, baseDirOverride?: string): string {
121
+ return getDshLogRootFrom(process.env, edgeInstanceId, baseDirOverride)
122
+ }
123
+
124
+ /** Environment-parameterized form of {@link getDshLogRoot}. */
125
+ export function getDshLogRootFrom(
126
+ env: NodeJS.ProcessEnv,
127
+ edgeInstanceId: string | null,
128
+ baseDirOverride?: string,
129
+ ): string {
130
+ const base = getLogBaseDirFrom(env, baseDirOverride)
131
+ return edgeInstanceId ? join(base, 'instances', edgeInstanceId, 'dsh') : join(base, 'dsh')
132
+ }