@yaks/process 0.0.0-stage → 0.2.36

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.
Files changed (111) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +249 -2
  3. package/_dist/clock.d.ts +5 -0
  4. package/_dist/clock.d.ts.map +1 -0
  5. package/_dist/command.d.ts +43 -0
  6. package/_dist/command.d.ts.map +1 -0
  7. package/_dist/comp.d.ts +49 -0
  8. package/_dist/comp.d.ts.map +1 -0
  9. package/_dist/env.d.ts +8 -0
  10. package/_dist/env.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +3 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/http.d.ts +11 -0
  14. package/_dist/http.d.ts.map +1 -0
  15. package/_dist/isolate.d.ts +11 -0
  16. package/_dist/isolate.d.ts.map +1 -0
  17. package/_dist/mod.d.ts +49 -0
  18. package/_dist/mod.d.ts.map +1 -0
  19. package/_dist/modules.d.ts +31 -0
  20. package/_dist/modules.d.ts.map +1 -0
  21. package/_dist/platform.d.ts +7 -0
  22. package/_dist/platform.d.ts.map +1 -0
  23. package/_dist/plugin.d.ts +15 -0
  24. package/_dist/plugin.d.ts.map +1 -0
  25. package/_dist/run.d.ts +219 -0
  26. package/_dist/run.d.ts.map +1 -0
  27. package/_dist/self.d.ts +32 -0
  28. package/_dist/self.d.ts.map +1 -0
  29. package/_dist/socket.d.ts +11 -0
  30. package/_dist/socket.d.ts.map +1 -0
  31. package/_dist/store.d.ts +22 -0
  32. package/_dist/store.d.ts.map +1 -0
  33. package/_dist/system.d.ts +64 -0
  34. package/_dist/system.d.ts.map +1 -0
  35. package/_dist/trash.d.ts +6 -0
  36. package/_dist/trash.d.ts.map +1 -0
  37. package/_dist/views.d.ts +4 -0
  38. package/_dist/views.d.ts.map +1 -0
  39. package/_dist/vocab.d.ts +8 -0
  40. package/_dist/vocab.d.ts.map +1 -0
  41. package/_dist/wind.d.ts +35 -0
  42. package/_dist/wind.d.ts.map +1 -0
  43. package/clock.js +11 -0
  44. package/clock.js.map +1 -0
  45. package/clock.ts +11 -0
  46. package/command.js +172 -0
  47. package/command.js.map +1 -0
  48. package/command.ts +215 -0
  49. package/comp.js +54 -0
  50. package/comp.js.map +1 -0
  51. package/comp.ts +123 -0
  52. package/deno.json +1 -0
  53. package/detached.js +60 -0
  54. package/detached.js.map +1 -0
  55. package/detached.ts +92 -0
  56. package/detached_worker.ts +22 -0
  57. package/env.js +13 -0
  58. package/env.js.map +1 -0
  59. package/env.ts +24 -0
  60. package/graph.js +7 -0
  61. package/graph.js.map +1 -0
  62. package/graph.ts +8 -0
  63. package/http.js +158 -0
  64. package/http.js.map +1 -0
  65. package/http.ts +184 -0
  66. package/isolate.js +41 -0
  67. package/isolate.js.map +1 -0
  68. package/isolate.ts +52 -0
  69. package/mod.js +49 -0
  70. package/mod.js.map +1 -0
  71. package/mod.ts +50 -0
  72. package/modules.js +41 -0
  73. package/modules.js.map +1 -0
  74. package/modules.ts +69 -0
  75. package/package.json +81 -4
  76. package/platform.js +9 -0
  77. package/platform.js.map +1 -0
  78. package/platform.ts +9 -0
  79. package/plugin.js +27 -0
  80. package/plugin.js.map +1 -0
  81. package/plugin.ts +28 -0
  82. package/run.js +899 -0
  83. package/run.js.map +1 -0
  84. package/run.ts +1139 -0
  85. package/self.js +93 -0
  86. package/self.js.map +1 -0
  87. package/self.ts +144 -0
  88. package/socket.js +38 -0
  89. package/socket.js.map +1 -0
  90. package/socket.ts +49 -0
  91. package/store.js +30 -0
  92. package/store.js.map +1 -0
  93. package/store.ts +50 -0
  94. package/system.js +161 -0
  95. package/system.js.map +1 -0
  96. package/system.ts +216 -0
  97. package/testing.ts +39 -0
  98. package/tidy.ts +28 -0
  99. package/trash.js +117 -0
  100. package/trash.js.map +1 -0
  101. package/trash.ts +117 -0
  102. package/views.js +28 -0
  103. package/views.js.map +1 -0
  104. package/views.ts +30 -0
  105. package/vocab.js +16 -0
  106. package/vocab.js.map +1 -0
  107. package/vocab.json +154 -0
  108. package/vocab.ts +18 -0
  109. package/wind.js +88 -0
  110. package/wind.js.map +1 -0
  111. package/wind.ts +114 -0
package/detached.ts ADDED
@@ -0,0 +1,92 @@
1
+ // Spawning can sleep in kernel_clone even with asynchronous child streams.
2
+ // One shared thread owns detached launches; callers only send command data.
3
+ import { Worker } from 'node:worker_threads'
4
+ import type { CommandOptions } from './command.ts'
5
+ import { fileURLToPath } from 'node:url'
6
+
7
+ /** A launch with no streams or channel held by its caller. */
8
+ export type DetachedOptions = Pick<
9
+ CommandOptions,
10
+ | 'args'
11
+ | 'cwd'
12
+ | 'env'
13
+ | 'clearEnv'
14
+ | 'uid'
15
+ | 'gid'
16
+ | 'detached'
17
+ | 'windowsRawArguments'
18
+ >
19
+ export type Launch = { id: number; program: string; options: DetachedOptions }
20
+ export type Launched = { id: number; error?: Error }
21
+
22
+ type Thread = Pick<Worker, 'postMessage' | 'ref' | 'unref' | 'terminate'> & {
23
+ on(event: 'message', listener: (message: Launched) => void): unknown
24
+ on(event: 'error', listener: (error: Error) => void): unknown
25
+ on(event: 'exit', listener: (code: number) => void): unknown
26
+ }
27
+
28
+ /** A reusable command door. Its thread holds the caller open only while a
29
+ * launch is outstanding; a failed thread rejects every waiter and the next
30
+ * request gets a fresh one. */
31
+ export let detaching = (
32
+ start: () => Thread = () =>
33
+ new Worker(new URL('./detached_worker.ts', import.meta.url)),
34
+ ): (program: string, options?: DetachedOptions) => Promise<void> => {
35
+ let worker: Thread | undefined
36
+ let serial = 0
37
+ let pending = new Map<number, {
38
+ resolve: () => void
39
+ reject: (error: Error) => void
40
+ }>()
41
+ let open = () => {
42
+ if (worker) return worker
43
+ let w = start()
44
+ worker = w
45
+ let fail = (error: Error) => {
46
+ if (worker !== w) return
47
+ worker = undefined
48
+ if (!pending.size) reportError(error)
49
+ for (let p of pending.values()) p.reject(error)
50
+ pending.clear()
51
+ void w.terminate()
52
+ }
53
+ w.on('error', fail)
54
+ w.on('exit', (code) => fail(new Error(`command thread exited (${code})`)))
55
+ w.on('message', ({ id, error }: Launched) => {
56
+ let p = pending.get(id)
57
+ if (!p) return
58
+ pending.delete(id)
59
+ if (!pending.size) w.unref()
60
+ if (error) p.reject(error)
61
+ else p.resolve()
62
+ })
63
+ return w
64
+ }
65
+ return (program, options = {}) =>
66
+ new Promise<void>((resolve, reject) => {
67
+ let id = ++serial
68
+ try {
69
+ let w = open()
70
+ pending.set(id, { resolve, reject })
71
+ w.ref()
72
+ w.postMessage(
73
+ {
74
+ id,
75
+ program,
76
+ options: options.cwd instanceof URL
77
+ ? { ...options, cwd: fileURLToPath(options.cwd) }
78
+ : options,
79
+ } satisfies Launch,
80
+ )
81
+ } catch (error) {
82
+ pending.delete(id)
83
+ if (!pending.size) worker?.unref()
84
+ reject(error)
85
+ }
86
+ })
87
+ }
88
+
89
+ export let detached: (
90
+ program: string,
91
+ options?: DetachedOptions,
92
+ ) => Promise<void> = detaching()
@@ -0,0 +1,22 @@
1
+ import { parentPort } from 'node:worker_threads'
2
+ import { command } from './command.ts'
3
+ import type { Launch, Launched } from './detached.ts'
4
+
5
+ parentPort!.on('message', async ({ id, program, options }: Launch) => {
6
+ let answer: Launched = { id }
7
+ try {
8
+ let child = command(program, {
9
+ ...options,
10
+ stdin: 'null',
11
+ stdout: 'null',
12
+ stderr: 'null',
13
+ }).spawn()
14
+ // The short-lived launcher exits after detaching the tracked program.
15
+ // Keep its startup failures on the waiting caller's promise.
16
+ child.unref()
17
+ await child.status
18
+ } catch (error) {
19
+ answer.error = error instanceof Error ? error : new Error(String(error))
20
+ }
21
+ parentPort!.postMessage(answer)
22
+ })
package/env.js ADDED
@@ -0,0 +1,13 @@
1
+ // Environment access without loading operating-system or terminal operations.
2
+ import process from 'node:process';
3
+ export let env = {
4
+ get: (name)=>process.env[name],
5
+ set: (name, value)=>{
6
+ process.env[name] = value;
7
+ },
8
+ delete: (name)=>{
9
+ delete process.env[name];
10
+ },
11
+ toObject: ()=>Object.fromEntries(Object.entries(process.env).filter((row)=>row[1] != null))
12
+ };
13
+ //# sourceMappingURL=env.js.map
package/env.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","sources":["./env.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,OAAO,aAAa,eAAc;AAQlC,OAAO,IAAI,MAAW;EACpB,KAAK,CAAC,OAAiB,QAAQ,GAAG,CAAC,KAAK;EACxC,KAAK,CAAC,MAAc;IAClB,QAAQ,GAAG,CAAC,KAAK,GAAG;EACtB;EACA,QAAQ,CAAC;IACP,OAAO,QAAQ,GAAG,CAAC,KAAK;EAC1B;EACA,UAAU,IACR,OAAO,WAAW,CAChB,OAAO,OAAO,CAAC,QAAQ,GAAG,EAAE,MAAM,CAAC,CAAC,MAClC,GAAG,CAAC,EAAE,IAAI;AAGlB,EAAC"}
package/env.ts ADDED
@@ -0,0 +1,24 @@
1
+ // Environment access without loading operating-system or terminal operations.
2
+ import process from 'node:process'
3
+
4
+ export type Env = {
5
+ get: (name: string) => string | undefined
6
+ set: (name: string, value: string) => void
7
+ delete: (name: string) => void
8
+ toObject: () => Record<string, string>
9
+ }
10
+ export let env: Env = {
11
+ get: (name: string) => process.env[name],
12
+ set: (name: string, value: string) => {
13
+ process.env[name] = value
14
+ },
15
+ delete: (name: string) => {
16
+ delete process.env[name]
17
+ },
18
+ toObject: (): Record<string, string> =>
19
+ Object.fromEntries(
20
+ Object.entries(process.env).filter((row): row is [string, string] =>
21
+ row[1] != null
22
+ ),
23
+ ),
24
+ }
package/graph.js ADDED
@@ -0,0 +1,7 @@
1
+ // This package as a graph plugin, exported as `@yaks/process/graph` for a
2
+ // caller assembling a graph's plugin list.
3
+ import { processes } from "./plugin.js";
4
+ /** `process`, `service` and `exit`, as a graph plugin. */ export let plugins = ()=>[
5
+ processes()
6
+ ];
7
+ //# sourceMappingURL=graph.js.map
package/graph.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.js","sources":["./graph.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,2CAA2C;AAG3C,SAAS,SAAS,sBAAqB;AAEvC,wDAAwD,GACxD,OAAO,IAAI,UAAU,IAAgB;IAAC;GAAY,CAAA"}
package/graph.ts ADDED
@@ -0,0 +1,8 @@
1
+ // This package as a graph plugin, exported as `@yaks/process/graph` for a
2
+ // caller assembling a graph's plugin list.
3
+
4
+ import type { Plugin } from 'jsr:@yaks/graph@0.2.36'
5
+ import { processes } from './plugin.js'
6
+
7
+ /** `process`, `service` and `exit`, as a graph plugin. */
8
+ export let plugins = (): Plugin[] => [processes()]
package/http.js ADDED
@@ -0,0 +1,158 @@
1
+ // A private HTTP connection pool: each owner can retire broken connections
2
+ // without changing other callers' pools. undici is loaded by the first request,
3
+ // not by importing this module: it is about 100 CommonJS files, and most
4
+ // processes that import a module that can fetch never do.
5
+ let undici;
6
+ let loaded = ()=>undici ??= import("undici");
7
+ let answer = (body, source)=>{
8
+ let response = new Response(body, {
9
+ status: source.status,
10
+ statusText: source.statusText,
11
+ headers: [
12
+ ...source.headers
13
+ ]
14
+ });
15
+ for (let key of [
16
+ 'url',
17
+ 'redirected',
18
+ 'type'
19
+ ]){
20
+ Object.defineProperty(response, key, {
21
+ value: source[key]
22
+ });
23
+ }
24
+ return response;
25
+ };
26
+ // A body that ends with `signal`: undici's body under Deno reads on past an
27
+ // abort once its headers have arrived, so a stalled stream would never end,
28
+ // and neither would whoever reads it (a model step a Stop withdrew, the host
29
+ // draining behind it). On abort the read in progress fails with the signal's
30
+ // reason and the source is cancelled, which ends its request.
31
+ let bounded = (body, signal)=>{
32
+ if (!body || !signal) return body;
33
+ let reader = body.getReader();
34
+ let release = ()=>{};
35
+ return new ReadableStream({
36
+ start (controller) {
37
+ let stop = ()=>{
38
+ controller.error(signal.reason);
39
+ reader.cancel(signal.reason).catch(()=>{});
40
+ };
41
+ if (signal.aborted) return stop();
42
+ signal.addEventListener('abort', stop, {
43
+ once: true
44
+ });
45
+ release = ()=>signal.removeEventListener('abort', stop);
46
+ },
47
+ async pull (controller) {
48
+ try {
49
+ let part = await reader.read();
50
+ // An abort already ended the stream; what the source said after is
51
+ // nobody's.
52
+ if (signal.aborted) return;
53
+ if (part.done) {
54
+ release();
55
+ controller.close();
56
+ } else controller.enqueue(part.value);
57
+ } catch (error) {
58
+ release();
59
+ if (!signal.aborted) controller.error(error);
60
+ }
61
+ },
62
+ cancel (reason) {
63
+ release();
64
+ return reader.cancel(reason);
65
+ }
66
+ }, {
67
+ highWaterMark: 0
68
+ });
69
+ };
70
+ /** A fetch pool with an explicit lifetime, shared by Node and Deno callers.
71
+ * Without a dispatcher, its own pool opens with its first request. */ export let httpClient = (given)=>{
72
+ let dispatcher = given;
73
+ let send = async (input, init)=>{
74
+ let { Agent, fetch: request } = await loaded();
75
+ dispatcher ??= new Agent();
76
+ let source = input instanceof Request ? input : undefined;
77
+ let options = source ? {
78
+ method: source.method,
79
+ headers: source.headers,
80
+ body: source.body,
81
+ signal: source.signal,
82
+ redirect: source.redirect,
83
+ credentials: source.credentials,
84
+ cache: source.cache,
85
+ integrity: source.integrity,
86
+ keepalive: source.keepalive,
87
+ mode: source.mode,
88
+ referrer: source.referrer,
89
+ referrerPolicy: source.referrerPolicy,
90
+ ...init
91
+ } : init;
92
+ let received = await request(source?.url ?? input, {
93
+ ...options,
94
+ dispatcher,
95
+ duplex: 'half'
96
+ });
97
+ return answer(bounded(received.body, options?.signal), received);
98
+ };
99
+ return {
100
+ fetch: send,
101
+ close: ()=>dispatcher?.close(),
102
+ destroy: ()=>dispatcher?.destroy()
103
+ };
104
+ };
105
+ /** Collect each answer before closing its request's private connection pool. */ export let freshFetch = (create = httpClient)=>async (input, init)=>{
106
+ let client = create();
107
+ let signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);
108
+ try {
109
+ let response = await client.fetch(input, init);
110
+ let body = response.body ? await response.arrayBuffer() : null;
111
+ return answer(body, response);
112
+ } finally{
113
+ // A request the signal cut short may still hold its connection, which a
114
+ // graceful close waits on.
115
+ await (signal?.aborted && client.destroy ? client.destroy() : client.close());
116
+ }
117
+ };
118
+ /** A streamed request gets its own connection until its response ends. */ export let streamingFetch = (create = httpClient)=>async (input, init)=>{
119
+ let client = create();
120
+ let end = ()=>client.destroy ? client.destroy() : client.close();
121
+ try {
122
+ let source = await client.fetch(input, init);
123
+ if (!source.body) {
124
+ await end();
125
+ return source;
126
+ }
127
+ let reader = source.body.getReader();
128
+ let body = new ReadableStream({
129
+ async pull (controller) {
130
+ try {
131
+ let part = await reader.read();
132
+ if (!part.done) {
133
+ controller.enqueue(part.value);
134
+ return;
135
+ }
136
+ await client.close();
137
+ controller.close();
138
+ } catch (e) {
139
+ await end();
140
+ controller.error(e);
141
+ }
142
+ },
143
+ async cancel (reason) {
144
+ await Promise.all([
145
+ reader.cancel(reason),
146
+ end()
147
+ ]);
148
+ }
149
+ }, {
150
+ highWaterMark: 0
151
+ });
152
+ return answer(body, source);
153
+ } catch (e) {
154
+ await end();
155
+ throw e;
156
+ }
157
+ };
158
+ //# sourceMappingURL=http.js.map
package/http.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sources":["./http.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,gFAAgF;AAChF,yEAAyE;AACzE,0DAA0D;AAG1D,IAAI;AACJ,IAAI,SAAS,IAAM,WAAW,MAAM,CAAC;AAiBrC,IAAI,SAAS,CAAC,MAAuB;EACnC,IAAI,WAAW,IAAI,SAAS,MAAM;IAChC,QAAQ,OAAO,MAAM;IACrB,YAAY,OAAO,UAAU;IAC7B,SAAS;SAAI,OAAO,OAAO;KAAC;EAC9B;EACA,KAAK,IAAI,OAAO;IAAC;IAAO;IAAc;GAAO,CAAW;IACtD,OAAO,cAAc,CAAC,UAAU,KAAK;MAAE,OAAO,MAAM,CAAC,IAAI;IAAC;EAC5D;EACA,OAAO;AACT;AAEA,4EAA4E;AAC5E,4EAA4E;AAC5E,6EAA6E;AAC7E,6EAA6E;AAC7E,8DAA8D;AA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UAAU;UACnB,IAAI;YACF,IAAI,OAAO,MAAM,OAAO,IAAI;YAC5B,IAAI,CAAC,KAAK,IAAI,EAAE;cACd,WAAW,OAAO,CAAC,KAAK,KAAK;cAC7B;YACF;YACA,MAAM,OAAO,KAAK;YAClB,WAAW,KAAK;UAClB,EAAE,OAAO,GAAG;YACV,MAAM;YACN,WAAW,KAAK,CAAC;UACnB;QACF;QACA,MAAM,QAAO,MAAM;UACjB,MAAM,QAAQ,GAAG,CAAC;YAAC,OAAO,MAAM,CAAC;YAAS;WAAM;QAClD;MACF,GAAG;QAAE,eAAe;MAAE;MACtB,OAAO,OAAO,MAAM;IACtB,EAAE,OAAO,GAAG;MACV,MAAM;MACN,MAAM;IACR;EACF,EAAC"}
package/http.ts ADDED
@@ -0,0 +1,184 @@
1
+ // A private HTTP connection pool: each owner can retire broken connections
2
+ // without changing other callers' pools. undici is loaded by the first request,
3
+ // not by importing this module: it is about 100 CommonJS files, and most
4
+ // processes that import a module that can fetch never do.
5
+ import type { Dispatcher } from 'undici'
6
+
7
+ let undici: Promise<typeof import('undici')> | undefined
8
+ let loaded = () => undici ??= import('undici')
9
+
10
+ type Client = {
11
+ fetch: typeof fetch
12
+ /** ends the pool once its requests finish */
13
+ close: () => void | Promise<void>
14
+ /** ends the pool and its connections now */
15
+ destroy?: () => void | Promise<void>
16
+ }
17
+ type Answer = {
18
+ status: number
19
+ statusText: string
20
+ headers: Iterable<[string, string]>
21
+ url: string
22
+ redirected: boolean
23
+ type: string
24
+ }
25
+ let answer = (body: BodyInit | null, source: Answer): Response => {
26
+ let response = new Response(body, {
27
+ status: source.status,
28
+ statusText: source.statusText,
29
+ headers: [...source.headers],
30
+ })
31
+ for (let key of ['url', 'redirected', 'type'] as const) {
32
+ Object.defineProperty(response, key, { value: source[key] })
33
+ }
34
+ return response
35
+ }
36
+
37
+ // A body that ends with `signal`: undici's body under Deno reads on past an
38
+ // abort once its headers have arrived, so a stalled stream would never end,
39
+ // and neither would whoever reads it (a model step a Stop withdrew, the host
40
+ // draining behind it). On abort the read in progress fails with the signal's
41
+ // reason and the source is cancelled, which ends its request.
42
+ let bounded = (
43
+ body: ReadableStream<Uint8Array> | null,
44
+ signal?: AbortSignal | null,
45
+ ): ReadableStream<Uint8Array> | null => {
46
+ if (!body || !signal) return body
47
+ let reader = body.getReader()
48
+ let release = () => {}
49
+ return new ReadableStream<Uint8Array>({
50
+ start(controller) {
51
+ let stop = () => {
52
+ controller.error(signal.reason)
53
+ reader.cancel(signal.reason).catch(() => {})
54
+ }
55
+ if (signal.aborted) return stop()
56
+ signal.addEventListener('abort', stop, { once: true })
57
+ release = () => signal.removeEventListener('abort', stop)
58
+ },
59
+ async pull(controller) {
60
+ try {
61
+ let part = await reader.read()
62
+ // An abort already ended the stream; what the source said after is
63
+ // nobody's.
64
+ if (signal.aborted) return
65
+ if (part.done) {
66
+ release()
67
+ controller.close()
68
+ } else controller.enqueue(part.value)
69
+ } catch (error) {
70
+ release()
71
+ if (!signal.aborted) controller.error(error)
72
+ }
73
+ },
74
+ cancel(reason) {
75
+ release()
76
+ return reader.cancel(reason)
77
+ },
78
+ }, { highWaterMark: 0 })
79
+ }
80
+
81
+ /** A fetch pool with an explicit lifetime, shared by Node and Deno callers.
82
+ * Without a dispatcher, its own pool opens with its first request. */
83
+ export let httpClient = (given?: Dispatcher): Client => {
84
+ let dispatcher = given
85
+ let send: typeof fetch = async (input, init) => {
86
+ let { Agent, fetch: request } = await loaded()
87
+ dispatcher ??= new Agent()
88
+ let source = input instanceof Request ? input : undefined
89
+ let options = source
90
+ ? {
91
+ method: source.method,
92
+ headers: source.headers,
93
+ body: source.body,
94
+ signal: source.signal,
95
+ redirect: source.redirect,
96
+ credentials: source.credentials,
97
+ cache: source.cache,
98
+ integrity: source.integrity,
99
+ keepalive: source.keepalive,
100
+ mode: source.mode,
101
+ referrer: source.referrer,
102
+ referrerPolicy: source.referrerPolicy,
103
+ ...init,
104
+ }
105
+ : init
106
+ let received = await request(
107
+ source?.url ?? input as string | URL,
108
+ {
109
+ ...options,
110
+ dispatcher,
111
+ duplex: 'half',
112
+ } as Parameters<typeof request>[1],
113
+ )
114
+ return answer(
115
+ bounded(
116
+ received.body as ReadableStream<Uint8Array> | null,
117
+ options?.signal,
118
+ ),
119
+ received,
120
+ )
121
+ }
122
+ return {
123
+ fetch: send,
124
+ close: () => dispatcher?.close(),
125
+ destroy: () => dispatcher?.destroy(),
126
+ }
127
+ }
128
+
129
+ /** Collect each answer before closing its request's private connection pool. */
130
+ export let freshFetch =
131
+ (create: () => Client = httpClient): typeof fetch => async (input, init) => {
132
+ let client = create()
133
+ let signal = init?.signal ??
134
+ (input instanceof Request ? input.signal : undefined)
135
+ try {
136
+ let response = await client.fetch(input, init)
137
+ let body = response.body ? await response.arrayBuffer() : null
138
+ return answer(body, response)
139
+ } finally {
140
+ // A request the signal cut short may still hold its connection, which a
141
+ // graceful close waits on.
142
+ await (signal?.aborted && client.destroy
143
+ ? client.destroy()
144
+ : client.close())
145
+ }
146
+ }
147
+
148
+ /** A streamed request gets its own connection until its response ends. */
149
+ export let streamingFetch =
150
+ (create: () => Client = httpClient): typeof fetch => async (input, init) => {
151
+ let client = create()
152
+ let end = () => client.destroy ? client.destroy() : client.close()
153
+ try {
154
+ let source = await client.fetch(input, init)
155
+ if (!source.body) {
156
+ await end()
157
+ return source
158
+ }
159
+ let reader = source.body.getReader()
160
+ let body = new ReadableStream<Uint8Array>({
161
+ async pull(controller) {
162
+ try {
163
+ let part = await reader.read()
164
+ if (!part.done) {
165
+ controller.enqueue(part.value)
166
+ return
167
+ }
168
+ await client.close()
169
+ controller.close()
170
+ } catch (e) {
171
+ await end()
172
+ controller.error(e)
173
+ }
174
+ },
175
+ async cancel(reason) {
176
+ await Promise.all([reader.cancel(reason), end()])
177
+ },
178
+ }, { highWaterMark: 0 })
179
+ return answer(body, source)
180
+ } catch (e) {
181
+ await end()
182
+ throw e
183
+ }
184
+ }
package/isolate.js ADDED
@@ -0,0 +1,41 @@
1
+ // A Linux managed run belongs to its own user scope, never its launcher's
2
+ // service cgroup. Both local supervisors and filesystem receipts use this door.
3
+ /** The user manager's address, available while user@<uid> is active. */ export let bus = (uid)=>({
4
+ XDG_RUNTIME_DIR: `/run/user/${uid}`,
5
+ DBUS_SESSION_BUS_ADDRESS: `unix:path=/run/user/${uid}/bus`
6
+ });
7
+ /** The systemd user slice that holds managed runs. */ export let applicationSlice = 'app.slice';
8
+ /** Lift the following command out of the launcher's systemd unit. Failure to
9
+ * reach that manager must fail the launch, never fall back inside its unit.
10
+ * `properties` are the scope's own, such as `MemoryMax=6G`: a command that
11
+ * grows past its cap is the one the kernel ends. */ export let scope = (unit, properties = [])=>[
12
+ 'systemd-run',
13
+ '--user',
14
+ '--scope',
15
+ '--collect',
16
+ '--quiet',
17
+ `--unit=${unit}`,
18
+ ...properties.map((p)=>`--property=${p}`)
19
+ ];
20
+ /** A managed run owns its descendants until its main process exits. Unlike a
21
+ * scope, this service then ends even descendants that made their own session.
22
+ * Environment references are expanded by systemd into single argv elements;
23
+ * env clears the user manager's extras without putting values in the unit. */ export let service = (unit, cwd, names)=>[
24
+ 'systemd-run',
25
+ '--user',
26
+ '--collect',
27
+ '--quiet',
28
+ '--service-type=exec',
29
+ '--property=ExitType=main',
30
+ '--property=KillMode=control-group',
31
+ '--property=TimeoutStopSec=2s',
32
+ `--slice=${applicationSlice}`,
33
+ `--unit=${unit}`,
34
+ `--working-directory=${cwd}`,
35
+ ...names.map((name)=>`--setenv=${name}`),
36
+ 'env',
37
+ '-i',
38
+ '--',
39
+ ...names.map((name)=>`${name}=\${${name}}`)
40
+ ];
41
+ //# sourceMappingURL=isolate.js.map
package/isolate.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"isolate.js","sources":["./isolate.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,gFAAgF;AAEhF,sEAAsE,GACtE,OAAO,IAAI,MAAM,CAAC,MAAwC,CAAC;IACzD,iBAAiB,CAAC,UAAU,EAAE,KAAK;IACnC,0BAA0B,CAAC,oBAAoB,EAAE,IAAI,IAAI,CAAC;EAC5D,CAAC,EAAC;AAEF,oDAAoD,GACpD,OAAO,IAAI,mBAAmB,YAAW;AAEzC;;;kDAGkD,GAClD,OAAO,IAAI,QAAQ,CAAC,MAAc,aAAuB,EAAE,GAAe;IACxE;IACA;IACA;IACA;IACA;IACA,CAAC,OAAO,EAAE,MAAM;OACb,WAAW,GAAG,CAAC,CAAC,IAAM,CAAC,WAAW,EAAE,GAAG;GAC3C,CAAA;AAED;;;4EAG4E,GAC5E,OAAO,IAAI,UAAU,CACnB,MACA,KACA,QACa;IACb;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,CAAC,QAAQ,EAAE,kBAAkB;IAC7B,CAAC,OAAO,EAAE,MAAM;IAChB,CAAC,oBAAoB,EAAE,KAAK;OACzB,MAAM,GAAG,CAAC,CAAC,OAAS,CAAC,SAAS,EAAE,MAAM;IACzC;IACA;IACA;OACG,MAAM,GAAG,CAAC,CAAC,OAAS,GAAG,KAAK,IAAI,EAAE,KAAK,CAAC,CAAC;GAC7C,CAAA"}
package/isolate.ts ADDED
@@ -0,0 +1,52 @@
1
+ // A Linux managed run belongs to its own user scope, never its launcher's
2
+ // service cgroup. Both local supervisors and filesystem receipts use this door.
3
+
4
+ /** The user manager's address, available while user@<uid> is active. */
5
+ export let bus = (uid: number): Record<string, string> => ({
6
+ XDG_RUNTIME_DIR: `/run/user/${uid}`,
7
+ DBUS_SESSION_BUS_ADDRESS: `unix:path=/run/user/${uid}/bus`,
8
+ })
9
+
10
+ /** The systemd user slice that holds managed runs. */
11
+ export let applicationSlice = 'app.slice'
12
+
13
+ /** Lift the following command out of the launcher's systemd unit. Failure to
14
+ * reach that manager must fail the launch, never fall back inside its unit.
15
+ * `properties` are the scope's own, such as `MemoryMax=6G`: a command that
16
+ * grows past its cap is the one the kernel ends. */
17
+ export let scope = (unit: string, properties: string[] = []): string[] => [
18
+ 'systemd-run',
19
+ '--user',
20
+ '--scope',
21
+ '--collect',
22
+ '--quiet',
23
+ `--unit=${unit}`,
24
+ ...properties.map((p) => `--property=${p}`),
25
+ ]
26
+
27
+ /** A managed run owns its descendants until its main process exits. Unlike a
28
+ * scope, this service then ends even descendants that made their own session.
29
+ * Environment references are expanded by systemd into single argv elements;
30
+ * env clears the user manager's extras without putting values in the unit. */
31
+ export let service = (
32
+ unit: string,
33
+ cwd: string,
34
+ names: string[],
35
+ ): string[] => [
36
+ 'systemd-run',
37
+ '--user',
38
+ '--collect',
39
+ '--quiet',
40
+ '--service-type=exec',
41
+ '--property=ExitType=main',
42
+ '--property=KillMode=control-group',
43
+ '--property=TimeoutStopSec=2s',
44
+ `--slice=${applicationSlice}`,
45
+ `--unit=${unit}`,
46
+ `--working-directory=${cwd}`,
47
+ ...names.map((name) => `--setenv=${name}`),
48
+ 'env',
49
+ '-i',
50
+ '--',
51
+ ...names.map((name) => `${name}=\${${name}}`),
52
+ ]
package/mod.js ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @yaks/process — a running program as an entity, so whatever needs one can
3
+ * point at it instead of keeping a pid of its own.
4
+ *
5
+ * - `service{command, cwd, restart, attempts}` — a program that should run,
6
+ * stored on the same entity its process lands on. The supervisor acts on
7
+ * this component, and a `stop` component beside it means the program is no
8
+ * longer wanted.
9
+ * - `process{pid, command, cwd}` — a program running on this machine;
10
+ * `command` and `cwd` are present exactly when we launched it.
11
+ * - `exit{code}` — it is over, and how. Absent means running.
12
+ * - output stays in the run's stdout and stderr files, never the graph:
13
+ * {@link tail} reads their last lines, {@link clean} removes them, and
14
+ * {@link sweep} removes every run's that ended long enough ago.
15
+ *
16
+ * The program doing the launching is one too: {@link started} and
17
+ * {@link ended} return the components a process writes about itself on the way
18
+ * in and the way out (./self.ts). That is the entity the server signs its
19
+ * writes with, and the one a start-up effect handler fires on.
20
+ *
21
+ * ```ts
22
+ * import { launch, store, supervise, tail, watch } from '@yaks/process'
23
+ *
24
+ * // let processes = store(graph)
25
+ * // let run = await launch(processes, { command: 'sh', args: ['-c', 'echo hi'] })
26
+ * // await run.done // 0
27
+ * // await tail(run.eid, 40) // ['hi']
28
+ * // await watch(processes) // at start-up: pick the unfinished ones back up
29
+ * // let pass = supervise(processes) // then drive it from your own timer
30
+ * ```
31
+ *
32
+ * Four entry points over one loop: {@link launch} starts a process detached
33
+ * (a wrapper in a session of its own, beyond the host's service manager, a
34
+ * pidfile, a stdout file and a stderr file), {@link adopt} tracks one nobody
35
+ * here started, {@link watch} adopts every row with no `exit` again at
36
+ * start-up and records an exit code for the ones already gone, and
37
+ * {@link supervise} makes the machine match the `service` rows — start, start
38
+ * again with a bounded backoff, stop. The server can restart without taking
39
+ * any of those processes with it, which is the only reason the launcher is
40
+ * shaped the way it is, and exactly one supervisor sits above it (see
41
+ * ./run.ts).
42
+ *
43
+ * @module
44
+ */ export * from "./comp.js";
45
+ export * from "./self.js";
46
+ export * from "./store.js";
47
+ export * from "./plugin.js";
48
+ export * from "./run.js";
49
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GAED,0BAAyB;AACzB,0BAAyB;AACzB,2BAA0B;AAC1B,4BAA2B;AAC3B,yBAAwB"}