@laraveladmin/dsh-stay-awake 0.0.0-stage → 0.1.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,305 @@
1
+ /**
2
+ * Assertion state machine.
3
+ *
4
+ * idle ──wanted──▶ holding ──!wanted──▶ releasing ──timer & !wanted──▶ idle
5
+ * ▲ │ │
6
+ * │ │ unexpected exit │ wanted returns / assertion dies
7
+ * └──!wanted── failed ◀──backoff&wanted── holding
8
+ *
9
+ * Invariants:
10
+ * - at most one assertion process, except while a scope change replaces it;
11
+ * - `holding` always owns a live handle;
12
+ * - every timer is cancelled before the state that armed it changes.
13
+ */
14
+
15
+ const RETRY_MIN_MS = 1_000
16
+ const RETRY_MAX_MS = 60_000
17
+
18
+ export function createController({
19
+ config,
20
+ power,
21
+ log,
22
+ now = Date.now,
23
+ setTimer = setTimeout,
24
+ clearTimer = clearTimeout,
25
+ supported = true,
26
+ }) {
27
+ let state = 'idle'
28
+ let handle = null
29
+ let releaseTimer = null
30
+ let maxHoldTimer = null
31
+ let retryTimer = null
32
+ let retryDelay = RETRY_MIN_MS
33
+ let heldSince = null
34
+ let manualUntil = 0
35
+ let lastError = null
36
+ let lastErrorCode = null
37
+ let disposed = false
38
+ let sources = { agents: 0, maintenance: 0, jobs: 0 }
39
+
40
+ function wanted() {
41
+ if (disposed) return false
42
+ if (!config.enabled) return false
43
+ if (now() < manualUntil) return true
44
+ return sources.agents + sources.maintenance + sources.jobs > 0
45
+ }
46
+
47
+ function clearRelease() {
48
+ if (releaseTimer !== null) {
49
+ clearTimer(releaseTimer)
50
+ releaseTimer = null
51
+ }
52
+ }
53
+
54
+ function clearMaxHold() {
55
+ if (maxHoldTimer !== null) {
56
+ clearTimer(maxHoldTimer)
57
+ maxHoldTimer = null
58
+ }
59
+ }
60
+
61
+ function clearRetry() {
62
+ if (retryTimer !== null) {
63
+ clearTimer(retryTimer)
64
+ retryTimer = null
65
+ }
66
+ }
67
+
68
+ function cancelTimers() {
69
+ clearRelease()
70
+ clearMaxHold()
71
+ clearRetry()
72
+ }
73
+
74
+ function acquire() {
75
+ clearRetry()
76
+ const next = supported ? power.start(config.scope) : null
77
+ if (next === null) {
78
+ state = 'failed'
79
+ lastErrorCode = supported ? 'backend-failed' : 'unsupported'
80
+ lastError = supported ? 'backend failed to start' : 'no power backend for this platform'
81
+ log.error(`stay-awake: ${lastError}`)
82
+ scheduleRetry()
83
+ return
84
+ }
85
+
86
+ handle = next
87
+ state = 'holding'
88
+ heldSince = now()
89
+ lastError = null
90
+ lastErrorCode = null
91
+ retryDelay = RETRY_MIN_MS
92
+ log.info(`holding (${config.scope}) via ${next.launch.kind}`)
93
+ watch(next)
94
+ armMaxHold()
95
+ }
96
+
97
+ /** Replace the assertion in place (scope change): start the new one, then stop the old. */
98
+ function rebuild() {
99
+ const previous = handle
100
+ handle = null
101
+ if (previous !== null) {
102
+ previous.expected = true
103
+ Promise.resolve(power.stop(previous)).catch(() => {})
104
+ }
105
+ acquire()
106
+ }
107
+
108
+ function watch(assertion) {
109
+ assertion.exited.then(() => {
110
+ if (handle !== assertion || assertion.expected) return
111
+ handle = null
112
+ if (state === 'releasing') {
113
+ clearRelease()
114
+ state = 'idle'
115
+ log.warn('stay-awake: assertion exited while releasing; nothing left to do')
116
+ return
117
+ }
118
+ if (state !== 'holding') return
119
+ clearMaxHold()
120
+ state = 'failed'
121
+ lastErrorCode = 'exited'
122
+ lastError = 'assertion exited unexpectedly'
123
+ log.error(`stay-awake: ${lastError} (${describeExit(assertion.exit)})`)
124
+ scheduleRetry()
125
+ })
126
+ }
127
+
128
+ function armMaxHold() {
129
+ if (!config.maxHoldHours) return
130
+ clearMaxHold()
131
+ maxHoldTimer = setTimer(() => {
132
+ maxHoldTimer = null
133
+ if (state !== 'holding' || handle === null) return
134
+ log.info('stay-awake: max hold reached; rebuilding the assertion')
135
+ const previous = handle
136
+ handle = null
137
+ previous.expected = true
138
+ Promise.resolve(power.stop(previous)).catch(() => {})
139
+ if (wanted()) acquire()
140
+ else enterReleasing()
141
+ }, config.maxHoldHours * 3_600_000)
142
+ }
143
+
144
+ function scheduleRetry() {
145
+ clearRetry()
146
+ const delay = retryDelay
147
+ retryDelay = Math.min(retryDelay * 2, RETRY_MAX_MS)
148
+ retryTimer = setTimer(() => {
149
+ retryTimer = null
150
+ if (wanted()) acquire()
151
+ else state = 'idle'
152
+ }, delay)
153
+ }
154
+
155
+ function enterReleasing() {
156
+ if (config.releaseDelayMs <= 0) {
157
+ releaseNow()
158
+ return
159
+ }
160
+ state = 'releasing'
161
+ clearRelease()
162
+ releaseTimer = setTimer(() => {
163
+ releaseTimer = null
164
+ if (state === 'releasing' && !wanted()) releaseNow()
165
+ }, config.releaseDelayMs)
166
+ }
167
+
168
+ function releaseNow() {
169
+ cancelTimers()
170
+ const previous = handle
171
+ handle = null
172
+ state = 'idle'
173
+ heldSince = null
174
+ retryDelay = RETRY_MIN_MS
175
+ if (previous !== null) {
176
+ previous.expected = true
177
+ Promise.resolve(power.stop(previous)).catch((error) => {
178
+ log.warn(`stay-awake: releasing the assertion failed: ${describeExit(error)}`)
179
+ })
180
+ }
181
+ log.info('released')
182
+ }
183
+
184
+ function reconcile() {
185
+ if (disposed) return
186
+ if (wanted()) {
187
+ clearRelease()
188
+ if (state === 'holding') return
189
+ if (state === 'releasing') {
190
+ // The assertion was never torn down, so returning to holding is free.
191
+ state = 'holding'
192
+ return
193
+ }
194
+ acquire()
195
+ return
196
+ }
197
+
198
+ if (state === 'holding') {
199
+ enterReleasing()
200
+ return
201
+ }
202
+ if (state === 'releasing') return
203
+ if (state === 'failed') {
204
+ clearRetry()
205
+ state = 'idle'
206
+ }
207
+ }
208
+
209
+ return {
210
+ /** @param {{agents:number, maintenance:number, jobs:number}} next */
211
+ update(next) {
212
+ sources = next
213
+ reconcile()
214
+ },
215
+
216
+ /** Force one working state even without activity (UI "hold for N minutes"). */
217
+ hold(minutes = 30) {
218
+ if (!config.enabled) return this.status()
219
+ const bounded = Math.max(1, Math.min(24 * 60, Number.isFinite(minutes) ? minutes : 30))
220
+ manualUntil = now() + bounded * 60_000
221
+ reconcile()
222
+ return this.status()
223
+ },
224
+
225
+ /**
226
+ * Recompute the wanted state. Cheap and idempotent; used by the status
227
+ * route so an expired manual hold releases on the next poll instead of
228
+ * waiting for the 60s reconcile interval.
229
+ */
230
+ refresh() {
231
+ reconcile()
232
+ return this.status()
233
+ },
234
+
235
+ /** Drop a manual hold without touching the configured switch. */
236
+ cancelHold() {
237
+ manualUntil = 0
238
+ reconcile()
239
+ return this.status()
240
+ },
241
+
242
+ /**
243
+ * Apply a change that must take effect immediately.
244
+ * Disabling bypasses the release debounce; changing the scope rebuilds the
245
+ * assertion (new one first, old one after).
246
+ */
247
+ configure(patch = {}) {
248
+ const previousScope = config.scope
249
+ if (typeof patch.enabled === 'boolean') config.enabled = patch.enabled
250
+ if (patch.scope === 'system' || patch.scope === 'display') config.scope = patch.scope
251
+
252
+ if (!wanted()) {
253
+ if (handle !== null) {
254
+ clearRelease()
255
+ releaseNow()
256
+ } else {
257
+ cancelTimers()
258
+ state = 'idle'
259
+ }
260
+ return this.status()
261
+ }
262
+
263
+ if (config.scope !== previousScope && handle !== null) {
264
+ rebuild()
265
+ return this.status()
266
+ }
267
+
268
+ reconcile()
269
+ return this.status()
270
+ },
271
+
272
+ status() {
273
+ return {
274
+ enabled: config.enabled,
275
+ state,
276
+ holding: handle !== null,
277
+ scope: config.scope,
278
+ sources,
279
+ since: heldSince,
280
+ manualUntil: manualUntil > now() ? manualUntil : null,
281
+ lastError,
282
+ lastErrorCode,
283
+ }
284
+ },
285
+
286
+ dispose() {
287
+ disposed = true
288
+ cancelTimers()
289
+ const previous = handle
290
+ handle = null
291
+ state = 'idle'
292
+ if (previous !== null) {
293
+ previous.expected = true
294
+ Promise.resolve(power.stop(previous)).catch(() => {})
295
+ }
296
+ },
297
+ }
298
+ }
299
+
300
+ function describeExit(exit) {
301
+ if (exit === null || exit === undefined) return 'unknown'
302
+ if (exit.error !== undefined) return exit.error
303
+ if (exit.signal !== null) return `signal ${exit.signal}`
304
+ return `code ${exit.code}`
305
+ }
package/lib/log.js ADDED
@@ -0,0 +1,21 @@
1
+ /** Bounded in-memory log. Never written to disk, never contains session data. */
2
+ export function createLog(limit = 200) {
3
+ const entries = []
4
+ let lastError = null
5
+
6
+ function add(level, message) {
7
+ const entry = { time: Date.now(), level, message: String(message) }
8
+ entries.push(entry)
9
+ if (entries.length > limit) entries.shift()
10
+ if (level === 'error') lastError = entry.message
11
+ return entry
12
+ }
13
+
14
+ return {
15
+ info: (message) => add('info', message),
16
+ warn: (message) => add('warn', message),
17
+ error: (message) => add('error', message),
18
+ entries: () => entries.slice(),
19
+ lastError: () => lastError,
20
+ }
21
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Platform backends: the exact commands that hold a system power assertion.
3
+ *
4
+ * Every builder is pure so the generated command line can be unit tested
5
+ * without spawning anything. Three invariants matter more than the flags:
6
+ *
7
+ * 1. The assertion must die with the DSH host process (crash safety).
8
+ * 2. `scope: 'system'` must never touch the display.
9
+ * 3. `scope: 'display'` may keep the screen on, nothing more.
10
+ */
11
+
12
+ const ES_CONTINUOUS = 0x80000000
13
+ const ES_SYSTEM_REQUIRED = 0x00000001
14
+ const ES_DISPLAY_REQUIRED = 0x00000002
15
+
16
+ function windowsScript(scope) {
17
+ const flags = scope === 'display'
18
+ ? (ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED) >>> 0
19
+ : (ES_CONTINUOUS | ES_SYSTEM_REQUIRED) >>> 0
20
+ return [
21
+ '$ErrorActionPreference = "Stop"',
22
+ '$signature = \'[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint esFlags);\'',
23
+ '$power = Add-Type -MemberDefinition $signature -Name StayAwake -Namespace DshStayAwake -PassThru',
24
+ `[void]$power::SetThreadExecutionState(${flags})`,
25
+ // stdin EOF means the host process is gone: release and exit.
26
+ 'try { while ($null -ne [Console]::In.ReadLine()) { } }',
27
+ `finally { [void]$power::SetThreadExecutionState(${ES_CONTINUOUS}) }`,
28
+ ].join('\n')
29
+ }
30
+
31
+ /**
32
+ * @param {object} options
33
+ * @param {string} options.platform `process.platform`
34
+ * @param {'system'|'display'} options.scope
35
+ * @param {number} options.hostPid pid whose death must release the assertion
36
+ * @param {string} options.caffeinatePath macOS binary override
37
+ * @returns {{ kind: string, command: string, args: string[], stdin: boolean, displayScope: boolean } | null}
38
+ */
39
+ export function buildLaunch({ platform, scope, hostPid, caffeinatePath = '/usr/bin/caffeinate' }) {
40
+ if (!Number.isInteger(hostPid) || hostPid <= 0) return null
41
+ const displayScope = scope === 'display'
42
+
43
+ if (platform === 'darwin') {
44
+ const args = []
45
+ if (displayScope) args.push('-d')
46
+ // -i: block idle system sleep. -w: exit when the watched pid exits.
47
+ // Deliberately no -u: declaring the user active can wake the display and
48
+ // is the opposite of letting the screen stay off overnight.
49
+ args.push('-i', '-w', String(hostPid))
50
+ return { kind: 'caffeinate', command: caffeinatePath, args, stdin: false, displayScope }
51
+ }
52
+
53
+ if (platform === 'win32') {
54
+ return {
55
+ kind: 'setthreadexecutionstate',
56
+ command: 'powershell.exe',
57
+ args: [
58
+ '-NoProfile',
59
+ '-NonInteractive',
60
+ '-ExecutionPolicy',
61
+ 'Bypass',
62
+ '-Command',
63
+ windowsScript(scope),
64
+ ],
65
+ stdin: true,
66
+ displayScope,
67
+ }
68
+ }
69
+
70
+ if (platform === 'linux') {
71
+ const what = displayScope ? 'idle:sleep' : 'sleep'
72
+ return {
73
+ kind: 'systemd-inhibit',
74
+ command: 'systemd-inhibit',
75
+ args: [
76
+ `--what=${what}`,
77
+ '--who=dsh-stay-awake',
78
+ '--why=DSH unattended work is still running',
79
+ '--mode=block',
80
+ '/bin/sh',
81
+ '-c',
82
+ `while kill -0 ${hostPid} 2>/dev/null; do sleep 2; done`,
83
+ ],
84
+ stdin: false,
85
+ displayScope,
86
+ }
87
+ }
88
+
89
+ return null
90
+ }
91
+
92
+ export function backendName(platform) {
93
+ if (platform === 'darwin') return 'caffeinate'
94
+ if (platform === 'win32') return 'setthreadexecutionstate'
95
+ if (platform === 'linux') return 'systemd-inhibit'
96
+ return null
97
+ }
98
+
99
+ /** Human-verifiable status sources used by docs and the diagnostics payload. */
100
+ export function verifyCommand(platform) {
101
+ if (platform === 'darwin') return 'pmset -g assertions'
102
+ if (platform === 'win32') return 'powercfg /requests'
103
+ if (platform === 'linux') return 'systemd-inhibit --list'
104
+ return null
105
+ }
package/lib/power.js ADDED
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Power assertion process lifecycle.
3
+ *
4
+ * Every exit is classified by origin, never by exit code: an exit is either
5
+ * something this module caused (release/dispose/replacement) or an unexpected
6
+ * death that must enter the retry ladder. There is no `-t` timeout in the
7
+ * command lines, so a clean exit is never a normal outcome.
8
+ */
9
+
10
+ import { spawn as nodeSpawn } from 'node:child_process'
11
+
12
+ import { buildLaunch } from './platform.js'
13
+
14
+ const TERM_GRACE_MS = 2_000
15
+ const STDIN_GRACE_MS = 5_000
16
+ const KILL_GRACE_MS = 1_000
17
+
18
+ function wait(ms) {
19
+ return new Promise((resolve) => setTimeout(resolve, ms))
20
+ }
21
+
22
+ /**
23
+ * @param {object} options
24
+ * @param {string} options.platform
25
+ * @param {object} options.config normalized config
26
+ * @param {ReturnType<typeof createLogLike>} options.log
27
+ */
28
+ export function createPower({ platform, config, log, spawn = nodeSpawn, delay = wait, hostPid = process.pid }) {
29
+ /**
30
+ * @param {'system'|'display'} scope
31
+ * @returns {{ child: any, launch: object, expected: boolean, exited: Promise<object>, exit: object | null } | null}
32
+ */
33
+ function start(scope) {
34
+ const launch = buildLaunch({ platform, scope, hostPid, caffeinatePath: config.caffeinatePath })
35
+ if (launch === null) return null
36
+
37
+ let child
38
+ try {
39
+ child = spawn(launch.command, launch.args, {
40
+ stdio: launch.stdin ? ['pipe', 'ignore', 'ignore'] : ['ignore', 'ignore', 'ignore'],
41
+ windowsHide: true,
42
+ detached: platform !== 'win32',
43
+ })
44
+ } catch (error) {
45
+ log.error(`spawn ${launch.kind} failed: ${describe(error)}`)
46
+ return null
47
+ }
48
+
49
+ const handle = { child, launch, expected: false, exit: null, exited: null }
50
+ handle.exited = new Promise((resolve) => {
51
+ let settled = false
52
+ const settle = (value) => {
53
+ if (settled) return
54
+ settled = true
55
+ handle.exit = value
56
+ resolve(value)
57
+ }
58
+ child.once('exit', (code, signal) => settle({ code, signal }))
59
+ child.once('error', (error) => settle({ code: null, signal: null, error: describe(error) }))
60
+ })
61
+
62
+ if (launch.stdin) {
63
+ // EPIPE is expected when the host dies before the holder reads stdin.
64
+ child.stdin.on('error', () => {})
65
+ }
66
+
67
+ return handle
68
+ }
69
+
70
+ /** @param {ReturnType<typeof start>} handle */
71
+ async function stop(handle) {
72
+ if (handle === null || handle === undefined) return
73
+ handle.expected = true
74
+ const { child, launch } = handle
75
+ if (child === undefined || child === null) return
76
+
77
+ signal(child, 'SIGTERM', platform)
78
+
79
+ if (launch.stdin) {
80
+ try {
81
+ child.stdin.end()
82
+ } catch {
83
+ // The pipe is already gone; the exit wait below still applies.
84
+ }
85
+ }
86
+
87
+ const grace = launch.stdin ? STDIN_GRACE_MS : TERM_GRACE_MS
88
+ const settled = await Promise.race([handle.exited, delay(grace).then(() => 'timeout')])
89
+ if (settled !== 'timeout') return
90
+
91
+ signal(child, 'SIGKILL', platform)
92
+ await Promise.race([handle.exited, delay(KILL_GRACE_MS)])
93
+ }
94
+
95
+ return { start, stop }
96
+ }
97
+
98
+ function signal(child, name, platform) {
99
+ if (child.exitCode !== null || child.signalCode !== null) return
100
+ try {
101
+ if (platform !== 'win32' && typeof child.pid === 'number') {
102
+ // Kill the whole group: systemd-inhibit owns a watchdog child.
103
+ process.kill(-child.pid, name)
104
+ return
105
+ }
106
+ } catch {
107
+ // Fall through to the direct kill; the group may already be gone.
108
+ }
109
+ try {
110
+ child.kill(name)
111
+ } catch {
112
+ // Nothing left to signal.
113
+ }
114
+ }
115
+
116
+ function describe(error) {
117
+ if (error instanceof Error) return error.message
118
+ return String(error)
119
+ }
120
+
121
+ /** @typedef {ReturnType<typeof import('./log.js').createLog>} createLogLike */
package/lib/server.js ADDED
@@ -0,0 +1,91 @@
1
+ /** Same-origin fetch route consumed by the composer indicator and its popover. */
2
+
3
+ const MAX_BODY_BYTES = 4096
4
+ const SCOPES = new Set(['system', 'display'])
5
+
6
+ export function createStatusHandler({ controller, activity, config, platform, version, backend, verify, onChange }) {
7
+ return async function handle(request) {
8
+ try {
9
+ if (request.method === 'GET') {
10
+ if (typeof controller.refresh === 'function') controller.refresh()
11
+ return json(payload({ controller, activity, config, platform, version, backend, verify }))
12
+ }
13
+ if (request.method !== 'POST') {
14
+ return new Response(null, { status: 405, headers: { allow: 'GET, POST' } })
15
+ }
16
+
17
+ const declared = Number(request.headers.get('content-length') ?? 0)
18
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
19
+ return json({ error: 'body-too-large' }, 413)
20
+ }
21
+
22
+ let body
23
+ try {
24
+ body = await request.json()
25
+ } catch {
26
+ return json({ error: 'invalid-json' }, 400)
27
+ }
28
+ if (body === null || typeof body !== 'object') return json({ error: 'invalid-body' }, 400)
29
+
30
+ switch (body.action) {
31
+ case 'hold':
32
+ controller.hold(typeof body.minutes === 'number' ? body.minutes : 30)
33
+ break
34
+ case 'cancel-hold':
35
+ controller.cancelHold()
36
+ break
37
+ case 'set-enabled':
38
+ if (typeof body.enabled !== 'boolean') return json({ error: 'invalid-body' }, 400)
39
+ controller.configure({ enabled: body.enabled })
40
+ notify(onChange)
41
+ break
42
+ case 'set-scope':
43
+ if (!SCOPES.has(body.scope)) return json({ error: 'invalid-body' }, 400)
44
+ controller.configure({ scope: body.scope })
45
+ notify(onChange)
46
+ break
47
+ default:
48
+ return json({ error: 'invalid-action' }, 400)
49
+ }
50
+
51
+ return json(payload({ controller, activity, config, platform, version, backend, verify }))
52
+ } catch {
53
+ return json({ error: 'internal' }, 500)
54
+ }
55
+ }
56
+ }
57
+
58
+ function notify(onChange) {
59
+ if (typeof onChange !== 'function') return
60
+ try {
61
+ onChange()
62
+ } catch {
63
+ // Persisting a preference must never fail the request.
64
+ }
65
+ }
66
+
67
+ function payload({ controller, activity, config, platform, version, backend, verify }) {
68
+ return {
69
+ ok: true,
70
+ protocol: 2,
71
+ version,
72
+ platform,
73
+ backend,
74
+ verify,
75
+ scope: config.scope,
76
+ releaseDelayMs: config.releaseDelayMs,
77
+ maxHoldHours: config.maxHoldHours,
78
+ counts: activity.counts(config),
79
+ ...controller.status(),
80
+ }
81
+ }
82
+
83
+ function json(value, status = 200) {
84
+ return new Response(JSON.stringify(value), {
85
+ status,
86
+ headers: {
87
+ 'cache-control': 'no-store',
88
+ 'content-type': 'application/json; charset=utf-8',
89
+ },
90
+ })
91
+ }