-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResidual.js
More file actions
355 lines (277 loc) · 5.64 KB
/
Copy pathResidual.js
File metadata and controls
355 lines (277 loc) · 5.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/* eslint max-statements: [ 1, 23 ] */
import { once } from 'node:events'
import { spawn } from 'node:child_process'
import Dispatch from './Dispatch.js'
import Endpoint from './Endpoint.js'
import logthru from './_/logthru.js'
import Events from './_/Events.js'
import when from './_/when.js'
import delay from './_/delay.js'
import random from './_/random.js'
import { Timeouted } from './_/timeout.js'
import { when_opened } from './_/when-status.js'
var defaults =
{
name: 'app_example',
exe: process.execPath,
logthru: false,
Server () {},
Client () {},
retries_max: 2,
timeout: 5e3,
}
export default function Residual (options)
{
options = { ...defaults, ...options }
if (process.argv.includes('--residual'))
{
return Server(options)
}
else
{
return Client(options)
}
}
//::
function Server (options)
{
if (options.logthru)
{
logthru(options.name)
}
var wss = Dispatch(options.addr.for_dispatch())
options.Server?.call(null, wss)
var ready = when(wss, '@listening')
.then(() => process.send('@listening'))
.then(() => wss)
function close ()
{
wss?.close()
wss = null
}
return { ready, close }
}
//::
function Client (options)
{
var endp
var events = Events()
var ok = false
var retries = 0
async function setup ()
{
await progress(open_and_ping)
while (! ok)
{
retries++
if (retries > options.retries_max) break
/*
console.debug('retry:', retries, 'max:', options.retries_max) //*/
if (retries > 1)
{
await delay(random(1, 5) * 100./* ms */)
await progress(open_and_ping)
}
await progress(upstart)
await progress(open_and_ping)
}
if (! ok)
{
throw new Error(`unable_to_residual (retries: ${ options.retries_max })`)
}
/* TODO: fallback in single process mode */
}
async function open_and_ping ()
{
await open()
await ping()
ok = true
retries = 0
}
async function open ()
{
if (! endp)
{
var endp_options =
{
should_reconnect: false,
should_cleanup: false,
on_open_success: false,
emit_on_open_success: false,
}
endp = Endpoint(options.addr.for_endpoint(), endp_options, { events })
}
else
{
endp.open()
}
await when_opened(endp)
}
async function ping ()
{
var rs = await when(endp, '@recv')
if (typeof rs !== 'string')
{
throw new Error('not_a_booth')
}
if (! rs.match(/^@@booth:/))
{
throw new Error('not_a_booth')
}
}
async function upstart ()
{
var argv =
[
process.argv[1], /* TODO: test deno compile, provide option */
'--residual',
]
var spawn_options =
{
stdio: [ 'ignore', 'ignore', 'ignore', 'ipc' ],
detached: true,
}
var child = spawn(options.exe, argv, spawn_options)
try
{
var spawned = once(child, 'message')
var [ msg ] = await Timeouted(spawned, options.timeout)
if (msg !== '@listening')
{
throw new Error('not_a_residual')
}
}
catch
{
child.kill()
}
/* child.stdout.pipe(process.stdout) */
/* child.stderr.pipe(process.stderr) */
child.channel?.unref()
child.unref()
events.emit('@upstart', void 0, { endp })
/* return child */
}
async function progress (fn) /* eslint-disable-line complexity */
{
if (ok) return
try
{
await fn()
}
catch (e)
{
ok = false
if (e?.error?.code === 'ECONNREFUSED') return
if (e?.message === 'Timeout') return
console.error('PROGRESS', e)
}
}
function reconnect ()
{
if (! ok) return
if (! endp) return
ok = false
setup().then(
() => events.emit('@@open/success'),
(e) => events.emit('@error', e, { endp }),
)
}
events.on('@close', reconnect)
var Client = options.Client
var ready = setup()
.then(() => Client?.(endp))
.then(() =>
{
/* instantly opened when under Residual Endpoint */
events.emit('@open', void 0, { endp })
events.emit('@@open/success')
})
.then(() => endp)
function close ()
{
endp?.close()
endp = null
}
function fin ()
{
endp = null
}
return { ready, close, fin }
}
/*
// #1
function Server (options)
{
if (options.logthru)
{
logthru(options.name)
}
var wss
async function listen () // eslint-disable-line require-await
{
wss = Dispatch(options.addr.for_dispatch())
options.Server?.call(null, wss)
var ready = when(wss, '@listening')
return ready
}
// var wss = Dispatch(options.addr.for_dispatch())
// options.Server?.call(null, wss)
// var ready = when(wss, '@listening')
var ready = listen()
.then(() => process.send('@listening'))
.then(() => wss)
function close ()
{
wss?.close()
wss = null
}
return { ready, close }
}
// #2
function Server (options)
{
if (options.logthru)
{
logthru(options.name)
}
var wss
var attempts = 1
var attempts_max = 5
async function listen ()
{
try
{
wss = Dispatch(options.addr.for_dispatch())
}
catch (e)
{
if (e.code !== 'EADDRINUSE')
{
throw e
}
attempts++
console.log('attempts', attempts, e.code, String(e))
if (attempts < attempts_max)
{
await delay(100./* ms *-/)
return listen()
}
throw e
}
options.Server?.call(null, wss)
return when(wss, '@listening')
}
// var wss = Dispatch(options.addr.for_dispatch())
// options.Server?.call(null, wss)
var ready = listen()
.then(() => process.send('@listening'))
.then(() => wss)
function close ()
{
wss?.close()
wss = null
}
return { ready, close }
}
//*/