@cldmv/lib-process 0.0.1-placeholder → 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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,7 +1,155 @@
1
1
  # @cldmv/lib-process
2
2
 
3
- This version is a placeholder that reserves the package name so the repository's release workflow can publish it with npm trusted publishing.
4
-
5
3
  Process safety for Node: liveness checks a crash can't leave stale, locks that release when their holder dies, and kills that only ever reach your own processes.
6
4
 
7
- Source and real releases: https://github.com/CLDMV/lib-process
5
+ [![npm version]][npm_version_url] [![npm downloads]][npm_downloads_url] [![Last commit]][last_commit_url] [![coverage]][coverage_url]
6
+
7
+ ---
8
+
9
+ ## ✨ What's New
10
+
11
+ ### Latest: v0.1.0 (November 2026)
12
+
13
+ - **First release** — `alive.hold()` / `alive.check()` give a liveness check through a Unix socket that a crash can't leave stale, `lock()` is an exclusive lock that a dead holder's successor takes over at once, and `safeKill()` only signals the caller's own descendants (or reported processes that started after a given time) ([#2](https://github.com/CLDMV/lib-process/pull/2)). `lock()` and `safeKill()` are Linux only for now.
14
+ - [View full v0.1.0 Changelog](https://github.com/CLDMV/lib-process/blob/master/docs/changelog/v0/v0.1.0.md)
15
+
16
+ ---
17
+
18
+ Pid files lie. A pid in a file can belong to an unrelated process by the time you read it, and inside a PID namespace a live process outside it looks dead. `process.kill(pid)` trusts whatever pid it gets, so a computed 0 or -1 signals a whole process group or every process you own.
19
+
20
+ This package replaces those patterns with three small tools:
21
+
22
+ - **`alive`**: a holder listens on a Unix socket in a folder. Anyone can connect to find out whether it is still running. The kernel closes the socket the moment the holder exits, however it exits.
23
+ - **`lock`**: an exclusive lock built on `alive`. A dead holder's lock is taken over straight away, and two contenders never both win.
24
+ - **`safeKill`**: signals only the caller's own descendants (or processes it was told about that started after a given time), and never pid 0, pid 1, a group, itself or its ancestors.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ npm install @cldmv/lib-process
30
+ ```
31
+
32
+ ESM and CommonJS both work (`require()` needs Node.js ^20.19.0 or >=22.13.0).
33
+
34
+ ## `alive`
35
+
36
+ ```js
37
+ import { alive } from "@cldmv/lib-process";
38
+
39
+ // In the process that owns the folder:
40
+ const holder = await alive.hold("/tmp/my-run");
41
+ // ... work ...
42
+ await holder.close();
43
+
44
+ // Anywhere else:
45
+ const state = await alive.check("/tmp/my-run"); // "alive" | "dead" | "unknown"
46
+ ```
47
+
48
+ | `check()` says | Meaning |
49
+ | -------------- | -------------------------------------------------------------------------------------------------------- |
50
+ | `"alive"` | The holder's socket accepted a connection. It is running (a stopped, SIGSTOPped process counts too). |
51
+ | `"dead"` | The socket file is there but nothing listens on it. The holder crashed or was killed. |
52
+ | `"unknown"` | There is no socket: never held, closed cleanly, or not started yet. Decide yourself, e.g. by folder age. |
53
+
54
+ - The socket is `alive.sock` inside the folder (`alive.SOCKET_NAME`). Unix socket paths are short: 107 bytes on Linux, 103 on macOS (`alive.MAX_SOCKET_PATH_BYTES`). A longer path throws `ERR_LIB_PROCESS_PATH_TOO_LONG`, so keep folders near the root of `/tmp` or `$XDG_RUNTIME_DIR`.
55
+ - `hold()` creates the folder, replaces a dead socket, and throws `ERR_LIB_PROCESS_HELD` when a live process already holds it. It leaves a non-socket file at the socket path alone (`ERR_LIB_PROCESS_NOT_SOCKET`).
56
+ - The socket doesn't keep your process running, and child processes don't inherit it.
57
+ - Connecting works across PID namespaces, because the socket is a file. Processes only need to see the same folder.
58
+ - On Windows there are no Unix sockets in folders: `hold()` returns a handle with `unsupported: true` that holds nothing, and `check()` always says `"unknown"`.
59
+
60
+ ## `lock`
61
+
62
+ ```js
63
+ import { lock } from "@cldmv/lib-process";
64
+
65
+ const held = await lock("/tmp/my-app.lock", { wait: 5000 });
66
+ try {
67
+ // ... only one process at a time gets here ...
68
+ } finally {
69
+ await held.release();
70
+ }
71
+ ```
72
+
73
+ - The lock is a folder that this function creates and removes. Its socket must fit the limit above.
74
+ - `wait` (ms, default 0) is how long to keep trying while a live holder has it; `Infinity` waits indefinitely. When it runs out, it throws `ERR_LIB_PROCESS_HELD`. `retryInterval` (default 50 ms) is the pause between tries.
75
+ - A holder that crashed or was SIGKILLed leaves a dead socket. The next `lock()` takes it over at once, with no stale timeout to wait out.
76
+ - Taking over a dead lock runs under a short mutex: a listening socket in Linux's abstract namespace, which the kernel frees when its process dies. So two contenders never both win, and a crash can't leave the mutex stuck. Contenders must share a network namespace (abstract sockets are per network namespace). Separate PID or user namespaces are fine.
77
+ - Linux only for now. Elsewhere it throws `ERR_LIB_PROCESS_UNSUPPORTED_PLATFORM`.
78
+
79
+ ## `safeKill`
80
+
81
+ ```js
82
+ import { safeKill } from "@cldmv/lib-process";
83
+
84
+ const { killed, skipped } = await safeKill([worker.pid], { signal: "SIGTERM" });
85
+ // skipped: [{ pid, reason }] for everything it refused
86
+ ```
87
+
88
+ It never signals:
89
+
90
+ | Reason | What |
91
+ | ---------------- | ---------------------------------------------------------------------- |
92
+ | `invalid` | Anything that isn't a positive integer: 0, -1, negative (group) ids. |
93
+ | `init` | pid 1. |
94
+ | `self` | The calling process. |
95
+ | `ancestor` | Any of the caller's ancestors. |
96
+ | `thread` | A thread id (it would signal the whole process the thread belongs to). |
97
+ | `gone` | A pid that no longer exists, or was reused before the signal. |
98
+ | `not-descendant` | Any other process, unless `reported` is given. |
99
+ | `started-before` | With `reported`: a non-descendant that started before `since`. |
100
+ | `denied` | The kernel refused (EPERM). |
101
+
102
+ What it does signal: the caller's descendants. With `reported: { since }` it also signals other processes that started at or after `since` (a `Date` or epoch ms). That covers a grandchild that was reparented when its parent exited and whose pid a child reported. Because its start time is after `since`, it can't be an older process that happens to reuse the pid.
103
+
104
+ ```js
105
+ const started = Date.now();
106
+ // ... spawn work; a child reports a grandchild's pid ...
107
+ await safeKill([reportedPid], { reported: { since: started } });
108
+ ```
109
+
110
+ Right before each signal it reads the process's start time again, so a pid that was reused in between isn't signalled. Linux only: it reads `/proc`. It refuses to run (`ERR_LIB_PROCESS_PROC_MISMATCH`) when `/proc` belongs to another PID namespace, as after `unshare -p` without `--mount-proc`.
111
+
112
+ ## Errors
113
+
114
+ Every error is a `LibProcessError` with a `code` from `CODES`:
115
+
116
+ | Code | When |
117
+ | -------------------------------------- | ---------------------------------------------------------- |
118
+ | `ERR_LIB_PROCESS_HELD` | A live process holds the folder or lock. |
119
+ | `ERR_LIB_PROCESS_PATH_TOO_LONG` | The socket path is over the platform limit. |
120
+ | `ERR_LIB_PROCESS_NOT_SOCKET` | Something other than a socket sits at the socket path. |
121
+ | `ERR_LIB_PROCESS_UNKNOWN_STATE` | The socket exists but can't be connected to (permissions). |
122
+ | `ERR_LIB_PROCESS_MUTEX_TIMEOUT` | The takeover mutex stayed busy for 10 s. |
123
+ | `ERR_LIB_PROCESS_UNSUPPORTED_PLATFORM` | `lock()` or `safeKill()` off Linux. |
124
+ | `ERR_LIB_PROCESS_PROC_MISMATCH` | `/proc` can't be trusted for this process's pids. |
125
+ | `ERR_LIB_PROCESS_INVALID_ARGUMENT` | A bad argument. |
126
+
127
+ ## Development
128
+
129
+ ```bash
130
+ npm test # unit tests, then the CJS and dist checks
131
+ npm run coverage # the same with coverage (100% required)
132
+ ```
133
+
134
+ Tests that fork processes or send real signals only run inside a PID namespace, so a wrong kill can only reach the test run's own processes. They're skipped unless `LIB_PROCESS_TEST_NAMESPACE=1` is set and pid 1 isn't a host init. Run them in a throwaway container, for example:
135
+
136
+ ```bash
137
+ LIB_PROCESS_TEST_NAMESPACE=1 npm test
138
+ ```
139
+
140
+ The rest of the suite (the kill decisions with a made-up process table, and `safeKill` with `/proc` and `process.kill` replaced) runs anywhere and covers every line.
141
+
142
+ In a checkout, the `lib-process-dev` export condition loads `src/` instead of `dist/`.
143
+
144
+ ## License
145
+
146
+ Apache-2.0. See [LICENSE](LICENSE).
147
+
148
+ [npm version]: https://img.shields.io/npm/v/%40cldmv%2Flib-process.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
149
+ [npm_version_url]: https://www.npmjs.com/package/@cldmv/lib-process
150
+ [npm downloads]: https://img.shields.io/npm/dm/%40cldmv%2Flib-process.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
151
+ [npm_downloads_url]: https://www.npmjs.com/package/@cldmv/lib-process
152
+ [last commit]: https://img.shields.io/github/last-commit/CLDMV/lib-process?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
153
+ [last_commit_url]: https://github.com/CLDMV/lib-process/commits
154
+ [coverage]: https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2FCLDMV%2Flib-process%2Fbadges%2Fcoverage.json&style=for-the-badge&logo=vitest&logoColor=white
155
+ [coverage_url]: https://github.com/CLDMV/lib-process/blob/badges/coverage.json
package/dist/index.cjs ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ *
3
+ * @Project: @cldmv/lib-process
4
+ * @Filename: /src/index.cjs
5
+ * @Date: 2026-11-21T10:42:30-08:00 (1795286550)
6
+ * @Author: Nate Corcoran <CLDMV>
7
+ * @Email: <Shinrai@users.noreply.github.com>
8
+ * -----
9
+ * @Last modified by: Nate Corcoran <CLDMV> (Shinrai@users.noreply.github.com)
10
+ * @Last modified time: 2026-11-21T11:06:10-08:00 (1795287970)
11
+ * -----
12
+ * @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
13
+ *
14
+ */
15
+
16
+ "use strict";
17
+
18
+ // CommonJS entry for @cldmv/lib-process. It loads the sibling ESM module through Node's
19
+ // synchronous require(esm), so there is one implementation and no second bundle. tsup copies
20
+ // this file verbatim into dist/ next to the built .mjs.
21
+ if (!process.features?.require_module) {
22
+ const error = new Error(
23
+ `@cldmv/lib-process: require() needs Node.js ^20.19.0 or >=22.13.0 (this is ${process.version}). On older Node.js, load the package with import() instead.`
24
+ );
25
+ error.code = "ERR_REQUIRE_ESM";
26
+ throw error;
27
+ }
28
+
29
+ module.exports = require("./index.mjs");
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ var G=Object.defineProperty;var n=(t,e)=>G(t,"name",{value:e,configurable:!0});import{randomBytes as z}from"node:crypto";import{link as W,lstat as A,mkdir as b,realpath as q,rmdir as J,unlink as T}from"node:fs/promises";import Q from"node:net";import O from"node:path";var c=Object.freeze({HELD:"ERR_LIB_PROCESS_HELD",PATH_TOO_LONG:"ERR_LIB_PROCESS_PATH_TOO_LONG",NOT_SOCKET:"ERR_LIB_PROCESS_NOT_SOCKET",UNKNOWN_STATE:"ERR_LIB_PROCESS_UNKNOWN_STATE",MUTEX_TIMEOUT:"ERR_LIB_PROCESS_MUTEX_TIMEOUT",UNSUPPORTED_PLATFORM:"ERR_LIB_PROCESS_UNSUPPORTED_PLATFORM",PROC_MISMATCH:"ERR_LIB_PROCESS_PROC_MISMATCH",INVALID_ARGUMENT:"ERR_LIB_PROCESS_INVALID_ARGUMENT"}),i=class extends Error{static{n(this,"LibProcessError")}constructor(e,r,o){super(r,o),this.name="LibProcessError",this.code=e}};function w(t,e){if(!e.includes(process.platform))throw new i(c.UNSUPPORTED_PLATFORM,`@cldmv/lib-process: ${t}() isn't supported on ${process.platform} (supported: ${e.join(", ")}).`)}n(w,"assertPlatform");import F from"node:net";function E(t){return new Promise((e,r)=>{let o=F.createServer(s=>s.destroy());o.once("error",r),o.listen(t,()=>{o.off("error",r),o.on("error",()=>{}),o.unref(),e(o)})})}n(E,"listen");import{createHash as B}from"node:crypto";import{setTimeout as V}from"node:timers/promises";var X="\0@cldmv/lib-process:",j=process.platform==="linux";async function N(t,e,{timeout:r=1e4}={}){if(!j)return e();let o=X+B("sha256").update(t).digest("hex"),s=await Y(o,Date.now()+r);try{return await e()}finally{s.close()}}n(N,"withMutex");async function Y(t,e){for(;;)try{return await E(t)}catch(r){if(r.code!=="EADDRINUSE")throw r;if(Date.now()>=e)throw new i(c.MUTEX_TIMEOUT,"@cldmv/lib-process: timed out waiting for another process to finish replacing a socket.",{cause:r});await V(2+Math.random()*8)}}n(Y,"acquire");var P="alive.sock",_=process.platform==="darwin"?103:107,D=2e3,Z=Object.freeze({ECONNREFUSED:"dead",EAGAIN:"alive",ENOENT:"unknown"});function C(t){let e=O.join(t,P),r=Buffer.byteLength(e);if(r>_)throw new i(c.PATH_TOO_LONG,`@cldmv/lib-process: socket path ${e} is ${r} bytes, over the ${_}-byte limit for Unix sockets. Use a shorter folder path.`);return e}n(C,"socketPathFor");function x(t,e){return new Promise(r=>{let o=Q.connect(t),s=n(p=>{clearTimeout(a),o.destroy(),r(p)},"done"),a=setTimeout(()=>s("alive"),e);o.once("connect",()=>s("alive")),o.once("error",p=>s(Z[String(p.code)]??"unknown"))})}n(x,"probe");async function R(t){try{return await A(t)}catch(e){let r=e.code;if(r==="ENOENT"||r==="ENOTDIR")return null;throw e}}n(R,"statSocket");async function tt(t){for(let e=1;;e++)try{return await b(t,{recursive:!0}),await q(t)}catch(r){if(r.code!=="ENOENT"||e>=100)throw r}}n(tt,"realFolder");async function et(t,e){let r=O.join(t,`.t${z(4).toString("hex")}`),o=await E(r);try{await W(r,e)}catch(s){throw o.close(),await T(r).catch(y),s.code==="EEXIST"?new i(c.HELD,`@cldmv/lib-process: ${t} was taken by another holder.`,{cause:s}):s}return await T(r),o}n(et,"bindInPlace");async function L(t,{timeout:e=D}={}){if(process.platform==="win32")return"unknown";let r=C(O.resolve(t)),o;try{o=await R(r)}catch{return"unknown"}return o?.isSocket()?x(r,e):"unknown"}n(L,"check");var h=class{static{n(this,"Holder")}#t;#e;#o;#s;#r=null;constructor({dir:e,socketPath:r,server:o,identity:s,key:a,removeDir:p=!1}){this.dir=e,this.socketPath=r,this.#t=o,this.#e=s,this.#o=a,this.#s=p}get unsupported(){return this.socketPath===null}get closed(){return this.#r!==null}close(){return this.#r??=this.#n(),this.#r}async#n(){let e=this.#t,r=this.socketPath;if(!e||!r)return;this.#t=null;let o=n(()=>new Promise(s=>e.close(()=>s(void 0))),"stop");try{await N(this.#o,async()=>{let s=await R(r).catch(()=>null);s&&this.#e&&s.dev===this.#e.dev&&s.ino===this.#e.ino&&await T(r).catch(y),await o(),this.#s&&await J(this.dir).catch(rt)})}catch(s){throw e.listening&&await o(),s}}};function y(t){if(t.code!=="ENOENT")throw t}n(y,"ignoreGone");function rt(t){if(t.code!=="ENOENT"&&t.code!=="ENOTEMPTY")throw t}n(rt,"ignoreGoneOrNotEmpty");async function U(t){return k(t,{removeDir:!1})}n(U,"hold");async function k(t,{removeDir:e}){let r=O.resolve(t);if(process.platform==="win32")return await b(r,{recursive:!0}),new h({dir:r,socketPath:null,server:null,identity:null,key:r});let o=await tt(r),s=C(o);return N(o,async()=>{await b(o,{recursive:!0});let a=await R(s);if(a){if(!a.isSocket())throw new i(c.NOT_SOCKET,`@cldmv/lib-process: ${s} exists and isn't a socket, so it was left alone.`);let u=await x(s,D);if(u==="alive")throw new i(c.HELD,`@cldmv/lib-process: ${o} is held by a live process.`);if(u==="unknown")throw new i(c.UNKNOWN_STATE,`@cldmv/lib-process: can't tell whether ${s} still has a holder.`);await T(s).catch(y)}let p=await et(o,s),{dev:d,ino:l}=await A(s);return new h({dir:o,socketPath:s,server:p,identity:{dev:d,ino:l},key:o,removeDir:e})})}n(k,"holdFolder");import{setTimeout as ot}from"node:timers/promises";var st=50,S=class{static{n(this,"Lock")}#t;constructor(e){this.#t=e,this.path=e.dir}get released(){return this.#t.closed}release(){return this.#t.close()}};async function nt(t,{wait:e=0,retryInterval:r=st}={}){if(w("lock",["linux"]),typeof t!="string"||t==="")throw new i(c.INVALID_ARGUMENT,"@cldmv/lib-process: lock() needs a folder path.");if(!(e>=0))throw new i(c.INVALID_ARGUMENT,"@cldmv/lib-process: lock() `wait` must be 0 or more.");if(!(r>0))throw new i(c.INVALID_ARGUMENT,"@cldmv/lib-process: lock() `retryInterval` must be more than 0.");let o=Date.now()+e;for(;;)try{return new S(await k(t,{removeDir:!0}))}catch(s){let a=o-Date.now();if(s.code!==c.HELD||a<=0)throw s;await ot(Math.min(r,a))}}n(nt,"lock");import pt from"node:os";import{readFile as M,readlink as it}from"node:fs/promises";var ct=100;async function g(){let t;try{t=await it("/proc/self")}catch(e){throw new i(c.PROC_MISMATCH,"@cldmv/lib-process: /proc isn't readable, so pids can't be checked.",{cause:e})}if(t!==String(process.pid))throw new i(c.PROC_MISMATCH,`@cldmv/lib-process: /proc shows this process as ${t} but its pid is ${process.pid}. /proc belongs to another PID namespace (remount it, e.g. unshare --mount-proc), so no pid from it can be trusted.`)}n(g,"assertProcMatches");async function H(){let t=Number.parseFloat((await M("/proc/uptime","utf8")).split(" ")[0]);return Date.now()-t*1e3}n(H,"bootTimeMs");function at(t){let e=t.slice(t.lastIndexOf(")")+2).split(" ");return{ppid:Number(e[1]),startTicks:Number(e[19])}}n(at,"parseStat");function lt(t){let e=/^Tgid:\s*(\d+)$/m.exec(t);return e?Number(e[1]):Number.NaN}n(lt,"parseTgid");async function K(t,e){let r,o;try{[r,o]=await Promise.all([M(`/proc/${t}/stat`,"utf8"),M(`/proc/${t}/status`,"utf8")])}catch(p){let d=p.code;if(d==="ENOENT"||d==="ESRCH")return null;throw p}let{ppid:s,startTicks:a}=at(r);return{pid:t,tgid:lt(o),ppid:s,startTicks:a,startMs:e+a*1e3/ct}}n(K,"readProcess");var $=4096;async function ft(t,e){let r=new Set,o=await e(t);for(let s=0;o&&o.ppid>0&&s<$;s++)r.add(o.ppid),o=await e(o.ppid);return r}n(ft,"ancestorsOf");async function ut(t,e,r){let o=t.ppid;for(let s=0;o>0&&s<$;s++){if(o===e)return!0;if(o===1)return!1;let a=await r(o);if(!a)return!1;o=a.ppid}return!1}n(ut,"isDescendant");async function dt(t,{self:e,read:r,since:o}){let s=await ft(e,r),a=[],p=[],d=new Set;for(let l of t){if(d.has(l))continue;d.add(l);let u=n(m=>p.push({pid:l,reason:m}),"skip");if(typeof l!="number"||!Number.isSafeInteger(l)||l<=0){u("invalid");continue}if(l===1){u("init");continue}if(l===e){u("self");continue}if(s.has(l)){u("ancestor");continue}let f=await r(l);if(!f){u("gone");continue}if(f.tgid!==l){u("thread");continue}if(await ut(f,e,r)){a.push(f);continue}o===void 0?u("not-descendant"):f.startMs>=o?a.push(f):u("started-before")}return{allowed:a,skipped:p}}n(dt,"planKill");function ht(t){if(typeof t=="string"&&Object.hasOwn(pt.constants.signals,t)||typeof t=="number"&&Number.isInteger(t)&&t>=0)return t;throw new i(c.INVALID_ARGUMENT,`@cldmv/lib-process: safeKill() got an unknown signal ${String(t)}.`)}n(ht,"validateSignal");function mt(t){if(t===void 0)return;let e=t?.since,r=e instanceof Date?e.getTime():e;if(typeof r!="number"||!Number.isFinite(r))throw new i(c.INVALID_ARGUMENT,"@cldmv/lib-process: safeKill() `reported.since` must be a Date or epoch milliseconds.");return r}n(mt,"validateSince");async function wt(t,{signal:e="SIGTERM",reported:r}={}){if(w("safeKill",["linux"]),t===null||typeof t!="object"||typeof t[Symbol.iterator]!="function")throw new i(c.INVALID_ARGUMENT,"@cldmv/lib-process: safeKill() needs an array (or other iterable) of pids.");let o=ht(e),s=mt(r);await g();let a=await H(),p=n(f=>K(f,a),"read"),{allowed:d,skipped:l}=await dt([...t],{self:process.pid,read:p,since:s}),u=[];for(let f of d){let m=await p(f.pid);if(!m||m.startTicks!==f.startTicks){l.push({pid:f.pid,reason:"gone"});continue}try{process.kill(f.pid,o),u.push(f.pid)}catch(v){let I=v.code;if(I==="ESRCH")l.push({pid:f.pid,reason:"gone"});else if(I==="EPERM")l.push({pid:f.pid,reason:"denied"});else throw v}}return{killed:u,skipped:l}}n(wt,"safeKill");var Zt=Object.freeze({hold:U,check:L,SOCKET_NAME:P,MAX_SOCKET_PATH_BYTES:_});export{c as CODES,h as Holder,i as LibProcessError,S as Lock,Zt as alive,nt as lock,wt as safeKill};
2
+ //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,12 +1,113 @@
1
1
  {
2
2
  "name": "@cldmv/lib-process",
3
- "version": "0.0.1-placeholder",
4
- "description": "Placeholder for @cldmv/lib-process. Releases are published from https://github.com/CLDMV/lib-process by CI.",
3
+ "version": "0.1.0",
4
+ "description": "Process safety for Node: liveness checks a crash can't leave stale, locks that release when their holder dies, and kills that only ever reach your own processes.",
5
+ "type": "module",
5
6
  "license": "Apache-2.0",
7
+ "author": {
8
+ "name": "Shinrai",
9
+ "company": "CLDMV",
10
+ "email": "git+npm@cldmv.net",
11
+ "url": "https://cldmv.net"
12
+ },
13
+ "contributors": [
14
+ {
15
+ "name": "CLDMV",
16
+ "url": "https://github.com/CLDMV"
17
+ }
18
+ ],
19
+ "funding": {
20
+ "type": "github",
21
+ "url": "https://github.com/sponsors/shinrai"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "sideEffects": false,
27
+ "main": "./dist/index.cjs",
28
+ "module": "./dist/index.mjs",
29
+ "types": "./types/src/index.d.mts",
30
+ "exports": {
31
+ ".": {
32
+ "lib-process-dev": {
33
+ "types": "./types/src/index.d.mts",
34
+ "import": "./src/index.mjs",
35
+ "require": "./src/index.cjs"
36
+ },
37
+ "types": "./types/src/index.d.mts",
38
+ "import": "./dist/index.mjs",
39
+ "require": "./dist/index.cjs"
40
+ }
41
+ },
42
+ "files": [
43
+ "dist/",
44
+ "!dist/**/*.map",
45
+ "types/"
46
+ ],
47
+ "scripts": {
48
+ "build": "tsup",
49
+ "build:ci": "npm run lint && npm run format:check && npm run types:check && npm run types:build && npm run build",
50
+ "prepack": "npm run build",
51
+ "types:build": "tsc -p .configs/tsconfig.json --noCheck",
52
+ "types:check": "tsc -p .configs/tsconfig.json --noEmit",
53
+ "test": "node tests/run-vitest.mjs && npm run test:cjs && npm run test:dist",
54
+ "test:cjs": "npm run build && node --conditions=lib-process-dev --test tests/cjs/entry.test.cjs",
55
+ "test:dist": "npm run build && node tests/run-vitest.mjs --mode=dist",
56
+ "test:watch": "vitest --config .configs/vitest.config.mjs",
57
+ "coverage": "node tests/run-vitest.mjs --coverage-quiet",
58
+ "ci:coverage": "npm run coverage && npm run test:cjs && npm run test:dist",
59
+ "lint": "eslint --config .configs/eslint.config.mjs .",
60
+ "lint:fix": "eslint --config .configs/eslint.config.mjs . --fix",
61
+ "format": "prettier --config .configs/.prettierrc --write .",
62
+ "format:check": "prettier --config .configs/.prettierrc --check .",
63
+ "fix:headers": "fix-headers --config .configs/fix-headers.json"
64
+ },
65
+ "keywords": [
66
+ "process",
67
+ "pid",
68
+ "liveness",
69
+ "lock",
70
+ "lockfile",
71
+ "kill",
72
+ "unix-socket"
73
+ ],
74
+ "devEngines": {
75
+ "runtime": {
76
+ "name": "node",
77
+ "version": ">=22.22.0",
78
+ "onFail": "error"
79
+ }
80
+ },
6
81
  "repository": {
7
82
  "type": "git",
8
83
  "url": "git+https://github.com/CLDMV/lib-process.git"
9
84
  },
85
+ "bugs": {
86
+ "url": "https://github.com/CLDMV/lib-process/issues"
87
+ },
10
88
  "homepage": "https://github.com/CLDMV/lib-process#readme",
11
- "scaffoldedBy": "gh-broker"
89
+ "devDependencies": {
90
+ "@cldmv/configs": "^1.4.0",
91
+ "@cldmv/eslint-plugin-jsonv": "^1.1.2",
92
+ "@cldmv/fix-headers": "^2.2.7",
93
+ "@cldmv/jsonv": "^1.2.2",
94
+ "@cldmv/prettier-plugin-jsonv": "^1.2.2",
95
+ "@cldmv/vitest-runner": "^1.6.1",
96
+ "@eslint/css": "^2.0.1",
97
+ "@eslint/js": "^10.0.1",
98
+ "@eslint/json": "^2.1.1",
99
+ "@eslint/markdown": "^9.0.0",
100
+ "@types/node": "^26.6.6",
101
+ "@vitest/coverage-v8": "^5.1.1",
102
+ "eslint": "^10.15.0",
103
+ "globals": "^17.14.0",
104
+ "prettier": "^3.10.1",
105
+ "tsup": "^9.0.0",
106
+ "typescript": "^6.0.3",
107
+ "vitest": "^5.1.1"
108
+ },
109
+ "overrides": {
110
+ "katex": ">=0.19.1 <1.0.0",
111
+ "minimatch": "^11.0.3"
112
+ }
12
113
  }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Checks whether a process holds `dir`.
3
+ *
4
+ * @param {string} dir - The folder to check.
5
+ * @param {{ timeout?: number }} [options] - `timeout`: ms to wait for the connect (default 2000).
6
+ * @returns {Promise<AliveState>} `"alive"` when the holder's socket answers, `"dead"` when the
7
+ * socket is still there but nothing listens on it, `"unknown"` when there is no socket (or it
8
+ * can't be read). On Windows it is always `"unknown"`.
9
+ * @throws {LibProcessError} `ERR_LIB_PROCESS_PATH_TOO_LONG` when the socket path is over the limit.
10
+ * @example
11
+ * const state = await alive.check("/tmp/my-run");
12
+ * if (state === "dead") await rm("/tmp/my-run", { recursive: true });
13
+ */
14
+ export function check(dir: string, { timeout }?: {
15
+ timeout?: number;
16
+ }): Promise<AliveState>;
17
+ /**
18
+ * Starts holding `dir`: listens on `alive.sock` inside it until the handle is closed or the
19
+ * process exits. Creates the folder when it doesn't exist. A socket left behind by a holder
20
+ * that died is replaced. The socket doesn't keep the process running, and child processes
21
+ * don't inherit it, so it dies with this process alone.
22
+ *
23
+ * On Linux, replacing a dead socket runs under a short cross-process mutex, so two processes
24
+ * can never both end up holding the folder. On macOS that mutex doesn't exist: two `hold()`
25
+ * calls racing on the same dead folder could both succeed, so use `lock()` (Linux) when that
26
+ * matters. On Windows nothing is held and the handle's `unsupported` is true; `check()` then
27
+ * says `"unknown"` for the folder.
28
+ *
29
+ * @param {string} dir - The folder to hold.
30
+ * @returns {Promise<Holder>} The handle. Call `close()` to stop holding.
31
+ * @throws {LibProcessError} `ERR_LIB_PROCESS_HELD` when a live process already holds the folder,
32
+ * `ERR_LIB_PROCESS_NOT_SOCKET` when something else sits at the socket path,
33
+ * `ERR_LIB_PROCESS_UNKNOWN_STATE` when the socket's state can't be read,
34
+ * `ERR_LIB_PROCESS_PATH_TOO_LONG` when the socket path is over the limit.
35
+ * @example
36
+ * const holder = await alive.hold("/tmp/my-run");
37
+ * // ... work ...
38
+ * await holder.close();
39
+ */
40
+ export function hold(dir: string): Promise<Holder>;
41
+ /**
42
+ * `hold()` with the options `lock()` needs.
43
+ * @param {string} dir - The folder to hold.
44
+ * @param {{ removeDir: boolean }} options - `removeDir`: remove the folder on close when empty.
45
+ * @returns {Promise<Holder>} The handle.
46
+ */
47
+ export function holdFolder(dir: string, { removeDir }: {
48
+ removeDir: boolean;
49
+ }): Promise<Holder>;
50
+ /** File name of the socket inside a held folder. */
51
+ export const SOCKET_NAME: "alive.sock";
52
+ /** Longest socket path this platform accepts, in bytes (the kernel's limit minus its NUL). */
53
+ export const MAX_SOCKET_PATH_BYTES: 103 | 107;
54
+ /**
55
+ * The handle `hold()` returns. Closing it stops holding the folder.
56
+ */
57
+ export class Holder {
58
+ /**
59
+ * @param {object} init - Internal.
60
+ * @param {string} init.dir - The held folder's real path.
61
+ * @param {string | null} init.socketPath - The socket's path, or null where sockets aren't supported.
62
+ * @param {net.Server | null} init.server - The listening server.
63
+ * @param {{ dev: number, ino: number } | null} init.identity - The socket file's device and inode.
64
+ * @param {string} init.key - The mutex key for the folder.
65
+ * @param {boolean} [init.removeDir] - Remove the folder on close when it's empty.
66
+ */
67
+ constructor({ dir, socketPath, server, identity, key, removeDir }: {
68
+ dir: string;
69
+ socketPath: string | null;
70
+ server: net.Server | null;
71
+ identity: {
72
+ dev: number;
73
+ ino: number;
74
+ } | null;
75
+ key: string;
76
+ removeDir?: boolean | undefined;
77
+ });
78
+ /** The held folder (its real path). */
79
+ dir: string;
80
+ /** Path of the socket, or null on Windows, where holding is a no-op. */
81
+ socketPath: string | null;
82
+ /** True when this platform has no Unix sockets and the handle holds nothing (Windows). */
83
+ get unsupported(): boolean;
84
+ /** True once `close()` has been called. */
85
+ get closed(): boolean;
86
+ /**
87
+ * Stops holding: closes the socket and removes its file. The file is only removed when it
88
+ * is still this holder's own (same inode), so a later holder's socket is never touched.
89
+ * Calling it again returns the first call's promise.
90
+ * @returns {Promise<void>}
91
+ */
92
+ close(): Promise<void>;
93
+ #private;
94
+ }
95
+ export type AliveState = "alive" | "dead" | "unknown";
96
+ import net from "node:net";
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Throws {@link CODES.UNSUPPORTED_PLATFORM} unless the process runs on one of `platforms`.
3
+ * @param {string} name - The public function's name, for the message.
4
+ * @param {readonly string[]} platforms - The platforms the function supports.
5
+ * @returns {void}
6
+ */
7
+ export function assertPlatform(name: string, platforms: readonly string[]): void;
8
+ /**
9
+ *
10
+ * @Project: @cldmv/lib-process
11
+ * @Filename: /src/errors.mjs
12
+ * @Date: 2026-11-21T10:39:57-08:00 (1795286397)
13
+ * @Author: Nate Corcoran <CLDMV>
14
+ * @Email: <Shinrai@users.noreply.github.com>
15
+ * -----
16
+ * @Last modified by: Nate Corcoran <CLDMV> (Shinrai@users.noreply.github.com)
17
+ * @Last modified time: 2026-11-21T11:06:10-08:00 (1795287970)
18
+ * -----
19
+ * @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
20
+ *
21
+ */
22
+ /**
23
+ * @fileoverview The error class every lib-process failure uses, and its codes.
24
+ * @module @cldmv/lib-process/errors
25
+ */
26
+ /**
27
+ * Error codes thrown by lib-process. Each one is set on `error.code`.
28
+ * @readonly
29
+ */
30
+ export const CODES: Readonly<{
31
+ /** `alive.hold()` or `lock()` found a live holder already in the folder. */
32
+ HELD: "ERR_LIB_PROCESS_HELD";
33
+ /** The folder's socket path is longer than the platform allows for a Unix socket. */
34
+ PATH_TOO_LONG: "ERR_LIB_PROCESS_PATH_TOO_LONG";
35
+ /** Something other than a socket sits at the socket path, so it is left alone. */
36
+ NOT_SOCKET: "ERR_LIB_PROCESS_NOT_SOCKET";
37
+ /** The socket exists but its state can't be read (for example, no permission). */
38
+ UNKNOWN_STATE: "ERR_LIB_PROCESS_UNKNOWN_STATE";
39
+ /** The short internal mutex that serializes takeovers wasn't free in time. */
40
+ MUTEX_TIMEOUT: "ERR_LIB_PROCESS_MUTEX_TIMEOUT";
41
+ /** The function isn't available on this platform. */
42
+ UNSUPPORTED_PLATFORM: "ERR_LIB_PROCESS_UNSUPPORTED_PLATFORM";
43
+ /** `/proc` belongs to a different PID namespace than this process, so its pids can't be trusted. */
44
+ PROC_MISMATCH: "ERR_LIB_PROCESS_PROC_MISMATCH";
45
+ /** An argument has the wrong type or value. */
46
+ INVALID_ARGUMENT: "ERR_LIB_PROCESS_INVALID_ARGUMENT";
47
+ }>;
48
+ /**
49
+ * An error raised by lib-process. `code` is one of {@link CODES}.
50
+ */
51
+ export class LibProcessError extends Error {
52
+ /**
53
+ * @param {string} code - One of {@link CODES}.
54
+ * @param {string} message - What went wrong, in a sentence.
55
+ * @param {{ cause?: unknown }} [options] - The underlying error, when there is one.
56
+ */
57
+ constructor(code: string, message: string, options?: {
58
+ cause?: unknown;
59
+ });
60
+ /** @type {string} */
61
+ code: string;
62
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Liveness through a Unix socket in a folder: `hold()` it, `check()` it from anywhere.
3
+ */
4
+ export const alive: Readonly<{
5
+ hold: typeof hold;
6
+ check: typeof check;
7
+ SOCKET_NAME: "alive.sock";
8
+ MAX_SOCKET_PATH_BYTES: 103 | 107;
9
+ }>;
10
+ export { Holder };
11
+ export { safeKill } from "./kill.mjs";
12
+ import { hold } from "./alive.mjs";
13
+ import { check } from "./alive.mjs";
14
+ import { Holder } from "./alive.mjs";
15
+ export { lock, Lock } from "./lock.mjs";
16
+ export { CODES, LibProcessError } from "./errors.mjs";
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Decides, without signalling anything, which pids may be signalled.
3
+ * @param {unknown[]} pids - The candidates.
4
+ * @param {PlanOptions} options - Who the caller is and how to read processes.
5
+ * @returns {Promise<{ allowed: import("./proc.mjs").ProcessInfo[], skipped: KillResult["skipped"] }>} The decision.
6
+ */
7
+ export function planKill(pids: unknown[], { self, read, since }: PlanOptions): Promise<{
8
+ allowed: import("./proc.mjs").ProcessInfo[];
9
+ skipped: KillResult["skipped"];
10
+ }>;
11
+ /**
12
+ * Sends `signal` to each pid in `pids` that is provably safe to signal, and skips the rest.
13
+ * Linux only: it reads `/proc`, and refuses to run when `/proc` belongs to another PID
14
+ * namespace (an `unshare -p` without `--mount-proc`).
15
+ *
16
+ * @param {Iterable<number>} pids - The processes to signal.
17
+ * @param {object} [options]
18
+ * @param {string | number} [options.signal="SIGTERM"] - Signal name or number.
19
+ * @param {{ since: Date | number }} [options.reported] - Also allow pids that aren't the
20
+ * caller's descendants when they started at or after `since`. Without it only descendants
21
+ * are signalled.
22
+ * @returns {Promise<KillResult>} Which pids got the signal and which were skipped, with reasons.
23
+ * @throws {LibProcessError} `ERR_LIB_PROCESS_UNSUPPORTED_PLATFORM` off Linux,
24
+ * `ERR_LIB_PROCESS_PROC_MISMATCH` when `/proc` can't be trusted,
25
+ * `ERR_LIB_PROCESS_INVALID_ARGUMENT` for a bad signal or `reported.since`.
26
+ * @example
27
+ * const started = Date.now();
28
+ * // ... spawn workers; one of them reports a grandchild's pid ...
29
+ * const { killed, skipped } = await safeKill([worker.pid, reportedPid], { reported: { since: started } });
30
+ */
31
+ export function safeKill(pids: Iterable<number>, { signal, reported }?: {
32
+ signal?: string | number | undefined;
33
+ reported?: {
34
+ since: Date | number;
35
+ } | undefined;
36
+ }): Promise<KillResult>;
37
+ /**
38
+ * Why a pid was skipped.
39
+ */
40
+ export type SkipReason = "invalid" | "init" | "self" | "ancestor" | "thread" | "gone" | "not-descendant" | "started-before" | "denied";
41
+ export type KillResult = {
42
+ /**
43
+ * - Pids that were sent the signal.
44
+ */
45
+ killed: number[];
46
+ /**
47
+ * - Pids that weren't, and why.
48
+ */
49
+ skipped: {
50
+ pid: unknown;
51
+ reason: SkipReason;
52
+ }[];
53
+ };
54
+ export type PlanOptions = {
55
+ /**
56
+ * - The caller's pid.
57
+ */
58
+ self: number;
59
+ /**
60
+ * - Reads a process's facts.
61
+ */
62
+ read: (pid: number) => Promise<import("./proc.mjs").ProcessInfo | null>;
63
+ /**
64
+ * - Epoch ms; with it, non-descendants that started at or after it are allowed.
65
+ */
66
+ since?: number | undefined;
67
+ };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Listens on `name` and resolves once bound. Every connection is closed straight away: a
3
+ * successful connect is the whole message. The server doesn't keep the event loop alive,
4
+ * and an error after it is bound is ignored (the socket is then simply gone).
5
+ * @param {string} name - A socket path, or on Linux an abstract name starting with NUL.
6
+ * @returns {Promise<net.Server>} The listening server.
7
+ */
8
+ export function listen(name: string): Promise<net.Server>;
9
+ import net from "node:net";
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Takes an exclusive lock on `lockPath`, a folder this function creates and owns.
3
+ *
4
+ * @param {string} lockPath - The lock folder, for example `/run/user/1000/my-app.lock`. Keep it
5
+ * short: the socket inside must fit the Unix socket path limit.
6
+ * @param {object} [options]
7
+ * @param {number} [options.wait=0] - How long to keep trying while another live process holds
8
+ * the lock, in ms. 0 fails at once; `Infinity` waits for as long as it takes.
9
+ * @param {number} [options.retryInterval=50] - Pause between attempts while waiting, in ms.
10
+ * @returns {Promise<Lock>} The held lock.
11
+ * @throws {LibProcessError} `ERR_LIB_PROCESS_HELD` when a live process still holds it after
12
+ * `wait`, `ERR_LIB_PROCESS_UNSUPPORTED_PLATFORM` off Linux, plus the errors `alive.hold()` throws.
13
+ * @example
14
+ * const held = await lock("/tmp/my-app.lock", { wait: 5000 });
15
+ * try {
16
+ * // ... exclusive work ...
17
+ * } finally {
18
+ * await held.release();
19
+ * }
20
+ */
21
+ export function lock(lockPath: string, { wait, retryInterval }?: {
22
+ wait?: number | undefined;
23
+ retryInterval?: number | undefined;
24
+ }): Promise<Lock>;
25
+ /**
26
+ * A held lock. Call `release()` when done.
27
+ */
28
+ export class Lock {
29
+ /**
30
+ * @param {import("./alive.mjs").Holder} holder - Internal.
31
+ */
32
+ constructor(holder: import("./alive.mjs").Holder);
33
+ /** The lock folder's real path. */
34
+ path: string;
35
+ /** True once `release()` has been called. */
36
+ get released(): boolean;
37
+ /**
38
+ * Releases the lock and removes the lock folder (unless something else was put in it).
39
+ * Calling it again returns the first call's promise.
40
+ * @returns {Promise<void>}
41
+ */
42
+ release(): Promise<void>;
43
+ #private;
44
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Runs `fn` while holding the mutex for `key`.
3
+ * @template T
4
+ * @param {string} key - What the mutex guards, normally a folder's real path.
5
+ * @param {() => Promise<T>} fn - The critical section. Keep it short.
6
+ * @param {{ timeout?: number }} [options] - How long to wait for the mutex, in ms (default 10000).
7
+ * @returns {Promise<T>} Whatever `fn` returns.
8
+ */
9
+ export function withMutex<T>(key: string, fn: () => Promise<T>, { timeout }?: {
10
+ timeout?: number;
11
+ }): Promise<T>;
12
+ /** Whether this platform has an abstract socket namespace. */
13
+ export const HAS_MUTEX: boolean;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * @typedef {object} ProcessInfo
3
+ * @property {number} pid - The pid that was read.
4
+ * @property {number} tgid - Its thread group id: the process it belongs to. Differs from
5
+ * `pid` when `pid` is a thread.
6
+ * @property {number} ppid - Its parent's pid (0 for a namespace's pid 1).
7
+ * @property {number} startTicks - When it started, in clock ticks since boot. Unique enough
8
+ * with `pid` to tell a reused pid from the original.
9
+ * @property {number} startMs - When it started, as epoch milliseconds (about 10 ms precision).
10
+ */
11
+ /**
12
+ * Throws unless `/proc` shows this process under its own pid. When the process runs in a PID
13
+ * namespace whose `/proc` wasn't remounted, `/proc` lists another namespace's pids, and
14
+ * every pid read from it would point at a different process.
15
+ * @returns {Promise<void>}
16
+ */
17
+ export function assertProcMatches(): Promise<void>;
18
+ /**
19
+ * Works out when the system booted, as epoch milliseconds, from `/proc/uptime`.
20
+ * @returns {Promise<number>} Boot time in epoch ms.
21
+ */
22
+ export function bootTimeMs(): Promise<number>;
23
+ /**
24
+ * Parses the text of `/proc/<pid>/stat`.
25
+ * The second field is the command name in parentheses and may itself contain spaces and
26
+ * parentheses, so the fields after it are found from the last `)`.
27
+ * @param {string} text - The file's contents.
28
+ * @returns {{ ppid: number, startTicks: number }} The parent pid and start time.
29
+ */
30
+ export function parseStat(text: string): {
31
+ ppid: number;
32
+ startTicks: number;
33
+ };
34
+ /**
35
+ * Reads the `Tgid:` line of `/proc/<pid>/status`.
36
+ * @param {string} text - The file's contents.
37
+ * @returns {number} The thread group id, or NaN when the line is missing.
38
+ */
39
+ export function parseTgid(text: string): number;
40
+ /**
41
+ * Reads one process's facts. Returns null when it no longer exists.
42
+ * @param {number} pid - The pid to read.
43
+ * @param {number} bootMs - Boot time from {@link bootTimeMs}.
44
+ * @returns {Promise<ProcessInfo | null>} Its facts, or null when it is gone.
45
+ */
46
+ export function readProcess(pid: number, bootMs: number): Promise<ProcessInfo | null>;
47
+ /**
48
+ * Clock ticks per second in `/proc/<pid>/stat` (the kernel's USER_HZ). It is 100 on every
49
+ * architecture Node supports; `sysconf(_SC_CLK_TCK)` isn't reachable from Node without a
50
+ * child process, and a kill path shouldn't depend on spawning one.
51
+ */
52
+ export const CLOCK_TICKS_PER_SECOND: 100;
53
+ export type ProcessInfo = {
54
+ /**
55
+ * - The pid that was read.
56
+ */
57
+ pid: number;
58
+ /**
59
+ * - Its thread group id: the process it belongs to. Differs from
60
+ * `pid` when `pid` is a thread.
61
+ */
62
+ tgid: number;
63
+ /**
64
+ * - Its parent's pid (0 for a namespace's pid 1).
65
+ */
66
+ ppid: number;
67
+ /**
68
+ * - When it started, in clock ticks since boot. Unique enough
69
+ * with `pid` to tell a reused pid from the original.
70
+ */
71
+ startTicks: number;
72
+ /**
73
+ * - When it started, as epoch milliseconds (about 10 ms precision).
74
+ */
75
+ startMs: number;
76
+ };