@lango-project/lango-server 0.1.0 → 0.1.1
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/README.md +283 -4
- package/dist/builder.mjs +16 -1
- package/dist/builder.mjs.map +1 -1
- package/dist/cli/endpoint.mjs +6 -0
- package/dist/cli/endpoint.mjs.map +1 -1
- package/dist/cli/longpoll_broker.mjs +214 -0
- package/dist/cli/longpoll_broker.mjs.map +1 -0
- package/dist/cli/longpoll_options.mjs +102 -0
- package/dist/cli/longpoll_options.mjs.map +1 -0
- package/dist/cli/longpoll_session.mjs +135 -0
- package/dist/cli/longpoll_session.mjs.map +1 -0
- package/dist/cli/middleware.mjs +25 -0
- package/dist/cli/middleware.mjs.map +1 -0
- package/dist/cli/options.mjs +14 -2
- package/dist/cli/options.mjs.map +1 -1
- package/dist/cli/routes.mjs +66 -2
- package/dist/cli/routes.mjs.map +1 -1
- package/dist/cli/server.mjs +243 -23
- package/dist/cli/server.mjs.map +1 -1
- package/dist/cli/static_files.mjs +125 -0
- package/dist/cli/static_files.mjs.map +1 -0
- package/dist/endpoint.mjs +6 -0
- package/dist/endpoint.mjs.map +1 -1
- package/dist/group.mjs +17 -1
- package/dist/group.mjs.map +1 -1
- package/dist/longpoll_broker.mjs +214 -0
- package/dist/longpoll_broker.mjs.map +1 -0
- package/dist/longpoll_options.mjs +102 -0
- package/dist/longpoll_options.mjs.map +1 -0
- package/dist/longpoll_session.mjs +135 -0
- package/dist/longpoll_session.mjs.map +1 -0
- package/dist/middleware.mjs +25 -0
- package/dist/middleware.mjs.map +1 -0
- package/dist/options.mjs +14 -2
- package/dist/options.mjs.map +1 -1
- package/dist/routes.mjs +66 -2
- package/dist/routes.mjs.map +1 -1
- package/dist/runtime.mjs +118 -44
- package/dist/runtime.mjs.map +1 -1
- package/dist/server.mjs +243 -23
- package/dist/server.mjs.map +1 -1
- package/dist/server_context.mjs +78 -0
- package/dist/server_context.mjs.map +1 -0
- package/dist/static_files.mjs +125 -0
- package/dist/static_files.mjs.map +1 -0
- package/package.json +9 -4
- package/src/builder.lango +11 -0
- package/src/endpoint.lango +7 -0
- package/src/group.lango +14 -0
- package/src/longpoll.lua +61 -0
- package/src/longpoll_broker.lango +161 -0
- package/src/longpoll_options.lango +79 -0
- package/src/longpoll_session.lango +90 -0
- package/src/middleware.lango +10 -0
- package/src/options.lango +16 -0
- package/src/routes.lango +65 -1
- package/src/runtime.lango +62 -0
- package/src/server.lango +182 -17
- package/src/server_context.lango +58 -0
- package/src/static_files.lango +90 -0
package/dist/server.mjs
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import { LongpollBroker } from "./longpoll_broker.mjs";
|
|
2
|
+
import { LongpollSession } from "./longpoll_session.mjs";
|
|
1
3
|
import { prepareDatabase } from "./database.mjs";
|
|
2
4
|
import { deployment } from "./options.mjs";
|
|
3
5
|
import { Routes } from "./routes.mjs";
|
|
4
6
|
import { BodyReader } from "./body_reader.mjs";
|
|
7
|
+
import { StaticFiles } from "./static_files.mjs";
|
|
5
8
|
import * as http from "node:http";
|
|
6
9
|
import * as path from "node:path";
|
|
7
10
|
import * as modules from "node:module";
|
|
@@ -21,6 +24,7 @@ import {
|
|
|
21
24
|
isObject as __isObject,
|
|
22
25
|
isArray as __isArray,
|
|
23
26
|
includes as __includes,
|
|
27
|
+
entries as __entries,
|
|
24
28
|
range as __range,
|
|
25
29
|
add as __add,
|
|
26
30
|
requireBoolean as __requireBoolean,
|
|
@@ -35,7 +39,10 @@ import {
|
|
|
35
39
|
|
|
36
40
|
export class Server {
|
|
37
41
|
#definition;
|
|
42
|
+
#broker;
|
|
43
|
+
#polls;
|
|
38
44
|
#state;
|
|
45
|
+
#connections;
|
|
39
46
|
#server;
|
|
40
47
|
#pool;
|
|
41
48
|
#starting;
|
|
@@ -46,6 +53,7 @@ export class Server {
|
|
|
46
53
|
#ready;
|
|
47
54
|
#readyIds;
|
|
48
55
|
#destroying;
|
|
56
|
+
#static;
|
|
49
57
|
#lango;
|
|
50
58
|
#shutdownDeadline;
|
|
51
59
|
constructor(path, definition = null) {
|
|
@@ -56,13 +64,16 @@ export class Server {
|
|
|
56
64
|
let directory = path;
|
|
57
65
|
let routes = new Routes(directory);
|
|
58
66
|
__normalize(routes.xml(pathJoin(directory, "routes.xml")));
|
|
59
|
-
definition = { settings: deployment(directory), routes: __normalize(routes.definitions()), events: __normalize(routes.events()) };
|
|
67
|
+
definition = { settings: deployment(directory), routes: __normalize(routes.definitions()), events: __normalize(routes.events()), middlewares: __normalize(routes.middlewares()) };
|
|
60
68
|
}
|
|
61
69
|
if (__requireBoolean(definition === null)) {
|
|
62
70
|
throw "Use Server(directory) or Builder.build()";
|
|
63
71
|
}
|
|
64
72
|
this.#definition = __fromJson(__toJson(definition));
|
|
73
|
+
this.#broker = new LongpollBroker(__normalize(this.#definition.settings), __normalize(this.#definition.routes));
|
|
74
|
+
this.#polls = __normalize(__hostGlobal(["Object"]).create(null));
|
|
65
75
|
this.#state = "new";
|
|
76
|
+
this.#connections = [];
|
|
66
77
|
this.#server = null;
|
|
67
78
|
this.#pool = null;
|
|
68
79
|
this.#starting = null;
|
|
@@ -73,6 +84,28 @@ export class Server {
|
|
|
73
84
|
this.#ready = __normalize(__hostGlobal(["Promise"]).withResolvers());
|
|
74
85
|
this.#readyIds = [];
|
|
75
86
|
this.#destroying = false;
|
|
87
|
+
this.#static = null;
|
|
88
|
+
}
|
|
89
|
+
publish(path, key, data) {
|
|
90
|
+
__requireArity(arguments.length, [0, 1, 2], "publish");
|
|
91
|
+
path = __boundary(path);
|
|
92
|
+
key = __boundary(key);
|
|
93
|
+
data = __boundary(data);
|
|
94
|
+
if (__requireBoolean(__normalize(this.#state) !== "running")) {
|
|
95
|
+
return __normalize(__hostGlobal(["Promise"]).reject("Server is not running"));
|
|
96
|
+
}
|
|
97
|
+
return __normalize(this.#broker.publish(path, key, data));
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
cursor(path, key) {
|
|
101
|
+
__requireArity(arguments.length, [0, 1], "cursor");
|
|
102
|
+
path = __boundary(path);
|
|
103
|
+
key = __boundary(key);
|
|
104
|
+
if (__requireBoolean(__normalize(this.#state) !== "running")) {
|
|
105
|
+
return __normalize(__hostGlobal(["Promise"]).reject("Server is not running"));
|
|
106
|
+
}
|
|
107
|
+
return __normalize(this.#broker.cursor(path, key));
|
|
108
|
+
return null;
|
|
76
109
|
}
|
|
77
110
|
start() {
|
|
78
111
|
if (__requireBoolean(__normalize(this.#state) !== "new")) {
|
|
@@ -85,7 +118,19 @@ export class Server {
|
|
|
85
118
|
}
|
|
86
119
|
#launch() {
|
|
87
120
|
let settings = __normalize(this.#definition.settings);
|
|
88
|
-
|
|
121
|
+
if (__requireBoolean(__normalize(settings.static) !== null)) {
|
|
122
|
+
try {
|
|
123
|
+
this.#static = new StaticFiles(__normalize(settings.static));
|
|
124
|
+
} catch (error) {
|
|
125
|
+
this.#state = "closed";
|
|
126
|
+
return __normalize(__hostGlobal(["Promise"]).reject(error));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return __normalize(this.#broker.open()).then(__withArity((ignored) => {
|
|
130
|
+
ignored = __boundary(ignored);
|
|
131
|
+
return prepareDatabase(__normalize(settings.database));
|
|
132
|
+
return null;
|
|
133
|
+
}, [0], "closure")).then(__withArity((ignored) => {
|
|
89
134
|
ignored = __boundary(ignored);
|
|
90
135
|
let resolver = __normalize(modules.createRequire(__normalize(path.join(__normalize(settings.root), "package.json"))));
|
|
91
136
|
let entry = __normalize(resolver.resolve("@lango-project/lango-server"));
|
|
@@ -121,6 +166,11 @@ export class Server {
|
|
|
121
166
|
return null;
|
|
122
167
|
}, [0, 1], "closure"));
|
|
123
168
|
this.#server = server;
|
|
169
|
+
__normalize(server.on("connection", __withArity((socket) => {
|
|
170
|
+
socket = __boundary(socket);
|
|
171
|
+
this.#connected(socket);
|
|
172
|
+
return null;
|
|
173
|
+
}, [0], "closure")));
|
|
124
174
|
server.headersTimeout = __normalize(settings.bodyTimeoutMs);
|
|
125
175
|
server.requestTimeout = __normalize(settings.bodyTimeoutMs);
|
|
126
176
|
let listening = new (__hostGlobal(["Promise"]))(__withArity((resolve, reject) => {
|
|
@@ -144,6 +194,7 @@ export class Server {
|
|
|
144
194
|
return null;
|
|
145
195
|
}, [0], "closure")).catch(__withArity((error) => {
|
|
146
196
|
error = __boundary(error);
|
|
197
|
+
__normalize(this.#broker.close());
|
|
147
198
|
this.#state = "closed";
|
|
148
199
|
return this.#destroyPool().then(__withArity((ignored) => {
|
|
149
200
|
ignored = __boundary(ignored);
|
|
@@ -157,6 +208,10 @@ export class Server {
|
|
|
157
208
|
#messageReceived(message) {
|
|
158
209
|
__requireArity(arguments.length, [0], "messageReceived");
|
|
159
210
|
message = __boundary(message);
|
|
211
|
+
if (__requireBoolean(__normalize(message.kind) === "longpoll")) {
|
|
212
|
+
this.#brokerMessage(message);
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
160
215
|
if (__requireBoolean(__normalize(message.kind) === "ready")) {
|
|
161
216
|
if (__requireBoolean(!__requireBoolean(__normalize(this.#readyIds.includes(__normalize(message.threadId)))))) {
|
|
162
217
|
__add(this.#readyIds, __normalize(message.threadId));
|
|
@@ -199,10 +254,54 @@ export class Server {
|
|
|
199
254
|
return null;
|
|
200
255
|
return null;
|
|
201
256
|
}
|
|
257
|
+
#connected(socket) {
|
|
258
|
+
__requireArity(arguments.length, [0], "connected");
|
|
259
|
+
socket = __boundary(socket);
|
|
260
|
+
let record = { socket: socket, active: 0 };
|
|
261
|
+
__add(this.#connections, record);
|
|
262
|
+
__normalize(socket.once("close", () => {
|
|
263
|
+
let index = __normalize(this.#connections.indexOf(record));
|
|
264
|
+
if (__requireBoolean(index >= 0)) {
|
|
265
|
+
__normalize(this.#connections.splice(index, 1));
|
|
266
|
+
}
|
|
267
|
+
return null;
|
|
268
|
+
}));
|
|
269
|
+
return null;
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
#trackResponse(req, res) {
|
|
273
|
+
__requireArity(arguments.length, [0, 1], "trackResponse");
|
|
274
|
+
req = __boundary(req);
|
|
275
|
+
res = __boundary(res);
|
|
276
|
+
for (const record of __normalize(this.#connections)) {
|
|
277
|
+
if (__requireBoolean(__normalize(record.socket) === __normalize(req.socket))) {
|
|
278
|
+
record.active = __numericAdd(__normalize(record.active), 1);
|
|
279
|
+
let state = { done: false };
|
|
280
|
+
let complete = () => {
|
|
281
|
+
if (__requireBoolean(__normalize(state.done))) {
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
state.done = true;
|
|
285
|
+
record.active = __finite(__normalize(record.active) - 1);
|
|
286
|
+
if (__requireBoolean(__requireBoolean(__normalize(this.#state) === "closing") && __requireBoolean(__normalize(record.active) === 0))) {
|
|
287
|
+
__normalize(record.socket.end());
|
|
288
|
+
}
|
|
289
|
+
return null;
|
|
290
|
+
return null;
|
|
291
|
+
};
|
|
292
|
+
__normalize(res.once("finish", complete));
|
|
293
|
+
__normalize(res.once("close", complete));
|
|
294
|
+
return null;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return null;
|
|
298
|
+
return null;
|
|
299
|
+
}
|
|
202
300
|
#receive(req, res) {
|
|
203
301
|
__requireArity(arguments.length, [0, 1], "receive");
|
|
204
302
|
req = __boundary(req);
|
|
205
303
|
res = __boundary(res);
|
|
304
|
+
this.#trackResponse(req, res);
|
|
206
305
|
__normalize(req.on("error", __withArity((error) => {
|
|
207
306
|
error = __boundary(error);
|
|
208
307
|
return null;
|
|
@@ -211,8 +310,21 @@ export class Server {
|
|
|
211
310
|
if (__requireBoolean(__normalize(this.#state) !== "running")) {
|
|
212
311
|
return rejectHttp(req, res, 503, "Unavailable");
|
|
213
312
|
}
|
|
313
|
+
if (__requireBoolean(__requireBoolean(__normalize(this.#static) !== null) && __requireBoolean(__requireBoolean(__normalize(req.method) === "GET") || __requireBoolean(__normalize(req.method) === "HEAD")))) {
|
|
314
|
+
let failed = __withArity((status, code) => {
|
|
315
|
+
status = __boundary(status);
|
|
316
|
+
code = __boundary(code);
|
|
317
|
+
this.#send(res, failure(status, code));
|
|
318
|
+
return null;
|
|
319
|
+
}, [0, 1], "closure");
|
|
320
|
+
return __normalize(this.#static.receive(req, res, failed));
|
|
321
|
+
}
|
|
214
322
|
if (__requireBoolean(__normalize(req.method) !== "POST")) {
|
|
215
|
-
|
|
323
|
+
let allowed = "POST";
|
|
324
|
+
if (__requireBoolean(__normalize(this.#static) !== null)) {
|
|
325
|
+
allowed = "GET, HEAD, POST";
|
|
326
|
+
}
|
|
327
|
+
__normalize(res.setHeader("Allow", allowed));
|
|
216
328
|
return rejectHttp(req, res, 405, "MethodNotAllowed");
|
|
217
329
|
}
|
|
218
330
|
if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(req.url.includes("?"))) || __requireBoolean(__normalize(req.url.includes("#")))) || __requireBoolean(__normalize(req.url.includes("\\"))))) {
|
|
@@ -252,39 +364,125 @@ export class Server {
|
|
|
252
364
|
req = __boundary(req);
|
|
253
365
|
res = __boundary(res);
|
|
254
366
|
body = __boundary(body);
|
|
367
|
+
let pending = null;
|
|
368
|
+
let route = __normalize(this.#broker.route(__normalize(req.url)));
|
|
369
|
+
if (__requireBoolean(route === null)) {
|
|
370
|
+
pending = this.#dispatch(req, res, body);
|
|
371
|
+
} else {
|
|
372
|
+
pending = this.#longpoll(req, res, body, route);
|
|
373
|
+
}
|
|
374
|
+
return pending.then(__withArity((result) => {
|
|
375
|
+
result = __boundary(result);
|
|
376
|
+
this.#send(res, result);
|
|
377
|
+
return null;
|
|
378
|
+
return null;
|
|
379
|
+
}, [0], "closure")).catch(__withArity((error) => {
|
|
380
|
+
error = __boundary(error);
|
|
381
|
+
this.#send(res, failure(500, "InternalServerError"));
|
|
382
|
+
return null;
|
|
383
|
+
return null;
|
|
384
|
+
}, [0], "closure"));
|
|
385
|
+
return null;
|
|
386
|
+
}
|
|
387
|
+
#longpoll(req, res, body, route) {
|
|
388
|
+
__requireArity(arguments.length, [0, 1, 2, 3], "longpoll");
|
|
389
|
+
req = __boundary(req);
|
|
390
|
+
res = __boundary(res);
|
|
391
|
+
body = __boundary(body);
|
|
392
|
+
route = __boundary(route);
|
|
393
|
+
if (__requireBoolean(__normalize(__normalize(__hostGlobal(["Object"]).keys(__normalize(this.#polls))).length) >= __normalize(this.#definition.settings.redis.maxPendingPolls))) {
|
|
394
|
+
return __normalize(__hostGlobal(["Promise"]).resolve(failure(503, "PollLimit")));
|
|
395
|
+
}
|
|
396
|
+
let authorize = __withArity((token, result) => {
|
|
397
|
+
token = __boundary(token);
|
|
398
|
+
result = __boundary(result);
|
|
399
|
+
return this.#dispatch(req, res, body, true, token, result);
|
|
400
|
+
return null;
|
|
401
|
+
}, [0, 1], "closure");
|
|
402
|
+
let session = new LongpollSession(__normalize(this.#broker), route, authorize, body);
|
|
403
|
+
let id = __normalize(crypto.randomUUID());
|
|
404
|
+
this.#polls[id] = session;
|
|
405
|
+
let disconnected = () => {
|
|
406
|
+
__normalize(session.cancel());
|
|
407
|
+
return null;
|
|
408
|
+
};
|
|
409
|
+
__normalize(res.once("close", disconnected));
|
|
410
|
+
return __normalize(session.run()).finally(() => {
|
|
411
|
+
__normalize(res.removeListener("close", disconnected));
|
|
412
|
+
__normalize(__hostGlobal(["Reflect"]).deleteProperty(__normalize(this.#polls), id));
|
|
413
|
+
return null;
|
|
414
|
+
});
|
|
415
|
+
return null;
|
|
416
|
+
}
|
|
417
|
+
#brokerMessage(message) {
|
|
418
|
+
__requireArity(arguments.length, [0], "brokerMessage");
|
|
419
|
+
message = __boundary(message);
|
|
420
|
+
let port = __normalize(message.port);
|
|
421
|
+
let pending = null;
|
|
422
|
+
try {
|
|
423
|
+
if (__normalize(message.operation) === "publish") {
|
|
424
|
+
pending = this.publish(__normalize(message.path), __normalize(message.key), __normalize(message.data));
|
|
425
|
+
} else if (__normalize(message.operation) === "cursor") {
|
|
426
|
+
pending = this.cursor(__normalize(message.path), __normalize(message.key));
|
|
427
|
+
} else {
|
|
428
|
+
pending = __normalize(__hostGlobal(["Promise"]).reject("Unknown longpoll operation"));
|
|
429
|
+
}
|
|
430
|
+
} catch (error) {
|
|
431
|
+
pending = __normalize(__hostGlobal(["Promise"]).reject(error));
|
|
432
|
+
}
|
|
433
|
+
return pending.then(__withArity((value) => {
|
|
434
|
+
value = __boundary(value);
|
|
435
|
+
brokerReply(port, { ok: true, value: value });
|
|
436
|
+
return null;
|
|
437
|
+
}, [0], "closure")).catch(__withArity((error) => {
|
|
438
|
+
error = __boundary(error);
|
|
439
|
+
brokerReply(port, { ok: false });
|
|
440
|
+
return null;
|
|
441
|
+
}, [0], "closure")).finally(() => {
|
|
442
|
+
__normalize(port.close());
|
|
443
|
+
return null;
|
|
444
|
+
});
|
|
445
|
+
return null;
|
|
446
|
+
}
|
|
447
|
+
#dispatch(req, res, body, authorize = false, token = null, pollResult = null) {
|
|
448
|
+
__requireArity(arguments.length, [0, 1, 2], "dispatch");
|
|
449
|
+
req = __boundary(req);
|
|
450
|
+
res = __boundary(res);
|
|
451
|
+
body = __boundary(body);
|
|
452
|
+
authorize = __boundary(authorize);
|
|
453
|
+
token = __boundary(token);
|
|
454
|
+
pollResult = __boundary(pollResult);
|
|
255
455
|
let settings = __normalize(this.#definition.settings);
|
|
256
456
|
if (__requireBoolean(__requireBoolean(__normalize(this.#state) !== "running") || __requireBoolean(__requireBoolean(__normalize(this.#active) >= __normalize(settings.workers)) && __requireBoolean(__normalize(this.#waiting.length) >= __normalize(settings.maxQueue))))) {
|
|
257
|
-
return
|
|
457
|
+
return __normalize(__hostGlobal(["Promise"]).resolve(failure(503, "Unavailable")));
|
|
258
458
|
}
|
|
259
459
|
let id = __normalize(crypto.randomUUID());
|
|
260
|
-
let record = { id: id, task: { body: body, request: { id: id, method: __normalize(req.method), path: __normalize(req.url), headers: __normalize(req.headers), remoteAddress: req.socket.remoteAddress } }, completed: __normalize(__hostGlobal(["Promise"]).withResolvers()), controller: new (__hostGlobal(["AbortController"]))(), started: false, result: null, expired: false, deadline: __numericAdd(__normalize(__hostGlobal(["Date"]).now()), __normalize(settings.requestTimeoutMs)), timer: null };
|
|
460
|
+
let record = { id: id, task: { authorize: authorize, pollResult: pollResult, body: body, request: { id: id, method: __normalize(req.method), path: __normalize(req.url), headers: __normalize(__hostGlobal(["Object"]).assign({ }, __normalize(req.headers))), remoteAddress: req.socket.remoteAddress } }, completed: __normalize(__hostGlobal(["Promise"]).withResolvers()), controller: new (__hostGlobal(["AbortController"]))(), started: false, result: null, expired: false, deadline: __numericAdd(__normalize(__hostGlobal(["Date"]).now()), __normalize(settings.requestTimeoutMs)), timer: null };
|
|
461
|
+
if (__requireBoolean(token !== null)) {
|
|
462
|
+
record.task.request.headers.authorization = `Bearer ${token}`;
|
|
463
|
+
}
|
|
261
464
|
this.#tasks[id] = record;
|
|
262
465
|
this.#resetDeadline(record, __normalize(settings.requestTimeoutMs));
|
|
263
466
|
__add(this.#waiting, record);
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
return null;
|
|
269
|
-
}));
|
|
270
|
-
this.#pump();
|
|
271
|
-
return record.completed.promise.then(__withArity((result) => {
|
|
272
|
-
result = __boundary(result);
|
|
273
|
-
this.#send(res, result);
|
|
274
|
-
return null;
|
|
467
|
+
let disconnected = () => {
|
|
468
|
+
if (__requireBoolean(!__requireBoolean(__normalize(res.writableEnded)))) {
|
|
469
|
+
this.#cancel(record);
|
|
470
|
+
}
|
|
275
471
|
return null;
|
|
276
|
-
}
|
|
472
|
+
};
|
|
473
|
+
__normalize(res.once("close", disconnected));
|
|
474
|
+
this.#pump();
|
|
475
|
+
return record.completed.promise.catch(__withArity((error) => {
|
|
277
476
|
error = __boundary(error);
|
|
278
|
-
let code = 500;
|
|
279
|
-
let name = "InternalServerError";
|
|
280
477
|
if (__requireBoolean(__normalize(record.expired))) {
|
|
281
|
-
|
|
282
|
-
name = "RequestTimeout";
|
|
478
|
+
return failure(504, "RequestTimeout");
|
|
283
479
|
}
|
|
284
|
-
|
|
480
|
+
return failure(500, "InternalServerError");
|
|
285
481
|
return null;
|
|
482
|
+
}, [0], "closure")).finally(() => {
|
|
483
|
+
__normalize(res.removeListener("close", disconnected));
|
|
286
484
|
return null;
|
|
287
|
-
}
|
|
485
|
+
});
|
|
288
486
|
return null;
|
|
289
487
|
}
|
|
290
488
|
#expire(record) {
|
|
@@ -386,6 +584,14 @@ export class Server {
|
|
|
386
584
|
return null;
|
|
387
585
|
}
|
|
388
586
|
#stop() {
|
|
587
|
+
for (const record of __normalize(this.#connections)) {
|
|
588
|
+
if (__requireBoolean(__normalize(record.active) === 0)) {
|
|
589
|
+
__normalize(record.socket.destroy());
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
for (const [id, session] of __entries(__normalize(this.#polls))) {
|
|
593
|
+
__normalize(session.cancel());
|
|
594
|
+
}
|
|
389
595
|
let drained = new (__hostGlobal(["Promise"]))(__withArity((resolve) => {
|
|
390
596
|
resolve = __boundary(resolve);
|
|
391
597
|
let server = __normalize(this.#server);
|
|
@@ -418,6 +624,7 @@ export class Server {
|
|
|
418
624
|
return this.#destroyPool();
|
|
419
625
|
return null;
|
|
420
626
|
}).finally(() => {
|
|
627
|
+
__normalize(this.#broker.close());
|
|
421
628
|
this.#state = "closed";
|
|
422
629
|
return null;
|
|
423
630
|
});
|
|
@@ -565,4 +772,17 @@ export function main(args) {
|
|
|
565
772
|
}, [0], "closure"));
|
|
566
773
|
return null;
|
|
567
774
|
}
|
|
775
|
+
|
|
776
|
+
function brokerReply(port, message) {
|
|
777
|
+
__requireArity(arguments.length, [0, 1], "brokerReply");
|
|
778
|
+
port = __boundary(port);
|
|
779
|
+
message = __boundary(message);
|
|
780
|
+
try {
|
|
781
|
+
__normalize(port.postMessage(message));
|
|
782
|
+
} catch (error) {
|
|
783
|
+
return null;
|
|
784
|
+
}
|
|
785
|
+
return null;
|
|
786
|
+
return null;
|
|
787
|
+
}
|
|
568
788
|
//# sourceMappingURL=server.mjs.map
|
package/dist/server.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./database\"\n prepareDatabase(settings)\nimport js \"node:http\" as http\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js \"node:crypto\" as crypto\nimport js \"piscina\" as piscina\nimport js global process\nimport js global Promise\nimport js global Date\nimport js global Math\nimport js global Object\nimport js global Reflect\nimport js global AbortController\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./options\"\n deployment(directory)\nimport \"./routes\"\n class Routes\nimport \"./body_reader\"\n class BodyReader\n\nexport main(args)\n\nexport class Server(path, definition = null)\n methods\n start()\n close()\n\nServer(path, definition = null)\n if path != null\n directory = path\n routes = new Routes(directory)\n routes.xml(pathJoin(directory, \"routes.xml\"))\n definition = {\n settings: deployment(directory)\n routes: routes.definitions()\n events: routes.events()\n }\n if definition == null\n throw \"Use Server(directory) or Builder.build()\"\n @definition = from_json(to_json(definition))\n @state = \"new\"\n @server = null\n @pool = null\n @starting = null\n @closing = null\n @waiting = []\n @active = 0\n @tasks = Object/create(null)\n @ready = Promise/withResolvers()\n @readyIds = []\n @destroying = false\n\npathJoin(directory, file)\n return path/join(directory, file)\n\nServer:start()\n if @state != \"new\"\n return Promise/reject(\"Server can only be started once\")\n @state = \"starting\"\n @starting = launch()\n return @starting\n\nServer:launch()\n settings = @definition.settings\n return chain Promise/resolve(null)\n then(ignored)\n capture path\n capture modules\n capture settings\n resolver = modules/createRequire(path/join(settings.root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @pool = new piscina/Piscina({\n filename: path/join(path/dirname(entry), \"worker.mjs\")\n name: \"execute\"\n minThreads: settings.workers\n maxThreads: settings.workers\n maxQueue: settings.maxQueue\n concurrentTasksPerWorker: 1\n closeTimeout: settings.shutdownTimeoutMs\n workerData: @definition\n })\n pool = @pool\n pool.on(\"message\", (message)\n messageReceived(message)\n )\n pool.on(\"error\", (error)\n @ready.reject(error)\n context log\n log.err(\"Worker pool error\")\n )\n return startupDeadline(@ready.promise, settings.startupTimeoutMs)\n then(ignored)\n capture settings\n if @state != \"starting\"\n throw \"Server closed during startup\"\n server = new http/Server((req, res)\n receive(req, res)\n )\n @server = server\n server.headersTimeout = settings.bodyTimeoutMs\n server.requestTimeout = settings.bodyTimeoutMs\n listening = new Promise((resolve, reject)\n capture server\n capture settings\n server.once(\"error\", reject)\n server.listen(settings.port, settings.host, ()\n capture server\n capture resolve\n capture reject\n server.removeListener(\"error\", reject)\n if @state != \"starting\"\n reject(\"Server closed during startup\")\n return null\n @state = \"running\"\n address = server.address()\n resolve({\n host: address.address\n port: address.port\n })\n )\n )\n return listening\n catch(error)\n @state = \"closed\"\n return chain destroyPool()\n then(ignored)\n capture error\n throw error\n\nstartupDeadline(pending, timeout)\n expired = Promise/withResolvers()\n expire = ()\n capture expired\n expired.reject(\"Worker startup timed out\")\n timer = setTimeout(expire, timeout)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n\nServer:messageReceived(message)\n if message.kind == \"ready\"\n if !@readyIds.includes(message.threadId)\n @readyIds.add(message.threadId)\n if @readyIds.length >= @definition.settings.workers\n @ready.resolve(null)\n return null\n if !(message.id in @tasks)\n return null\n record = @tasks[message.id]\n if message.kind == \"prepared\"\n record.result = message.result\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"event\"\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"handler\" and record.result == null\n resetDeadline(record, record.deadline - Date/now())\n return null\n\nServer:resetDeadline(record, duration)\n clearTimeout(record.timer)\n if record.result == null\n duration = Math/min(duration, record.deadline - Date/now())\n expired = ()\n capture record\n expire(record)\n record.timer = setTimeout(expired, Math/max(1, duration))\n return null\n\nServer:receive(req, res)\n req.on(\"error\", (error)\n return null\n )\n if @state != \"running\"\n return rejectHttp(req, res, 503, \"Unavailable\")\n if req.method != \"POST\"\n res.setHeader(\"Allow\", \"POST\")\n return rejectHttp(req, res, 405, \"MethodNotAllowed\")\n if req.url.includes(\"?\") or req.url.includes(\"#\") or req.url.includes(\"\\\\\")\n return rejectHttp(req, res, 400, \"InvalidPath\")\n type = req.headers[\"content-type\"]\n media = \"\"\n if is_string(type)\n parts = type.split(\";\")\n media = parts[0].trim()\n if media.toLowerCase() != \"application/json\"\n return rejectHttp(req, res, 415, \"JsonRequired\")\n settings = @definition.settings\n if @active >= settings.workers and @waiting.length >= settings.maxQueue\n return rejectHttp(req, res, 503, \"QueueFull\")\n complete = (body)\n capture req\n capture res\n submit(req, res, body)\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n reader = new BodyReader(req, res, settings, complete, failed)\n reader.start()\n return null\n\nServer:submit(req, res, body)\n settings = @definition.settings\n if @state != \"running\" or (@active >= settings.workers and @waiting.length >= settings.maxQueue)\n return send(res, failure(503, \"Unavailable\"))\n id = crypto/randomUUID()\n record = {\n id: id\n task: {\n body: body\n request: {\n id: id\n method: req.method\n path: req.url\n headers: req.headers\n remoteAddress: req.socket.remoteAddress\n }\n }\n completed: Promise/withResolvers()\n controller: new AbortController()\n started: false\n result: null\n expired: false\n deadline: Date/now() + settings.requestTimeoutMs\n timer: null\n }\n @tasks[id] = record\n resetDeadline(record, settings.requestTimeoutMs)\n @waiting.add(record)\n res.once(\"close\", ()\n capture res\n capture record\n if !res.writableEnded\n cancel(record)\n )\n pump()\n return chain record.completed.promise\n then(result)\n capture res\n send(res, result)\n return null\n catch(error)\n capture res\n capture record\n code = 500\n name = \"InternalServerError\"\n if record.expired\n code = 504\n name = \"RequestTimeout\"\n send(res, failure(code, name))\n return null\n\nServer:expire(record)\n record.expired = true\n cancel(record)\n return null\n\nServer:cancel(record)\n if !(record.id in @tasks)\n return null\n if record.started\n record.controller.abort()\n else\n index = @waiting.indexOf(record)\n if index >= 0\n @waiting.splice(index, 1)\n finish(record, null, \"Request cancelled\")\n return null\n\nServer:pump()\n loop while !@destroying and @waiting.length > 0 and @active < @definition.settings.workers\n record = @waiting.shift()\n record.started = true\n @active = @active + 1\n pending = @pool.run(record.task, {\n signal: record.controller.signal\n })\n settle(record, pending)\n return null\n\nServer:settle(record, pending)\n return chain pending\n then(result)\n capture record\n finish(record, result, null)\n return null\n catch(error)\n capture record\n if record.result != null\n context log\n log.err(\"[${record.id}] Request event interrupted; preserving prepared result\")\n finish(record, record.result, error)\n return null\n finally\n @active = @active - 1\n pump()\n\nServer:finish(record, result, error)\n clearTimeout(record.timer)\n Reflect/deleteProperty(@tasks, record.id)\n if result != null\n record.completed.resolve(result)\n else\n record.completed.reject(error)\n return null\n\nServer:close()\n if @closing != null\n return @closing\n previous = @state\n @state = \"closing\"\n @shutdownDeadline = Date/now() + @definition.settings.shutdownTimeoutMs\n if previous == \"new\" or previous == \"closed\"\n @state = \"closed\"\n @closing = Promise/resolve(null)\n return @closing\n @ready.reject(\"Server closed during startup\")\n @closing = stop()\n return @closing\n\nServer:stop()\n drained = new Promise((resolve)\n server = @server\n if server == null or !server.listening\n resolve(null)\n else\n server.close(()\n capture resolve\n resolve(null)\n )\n )\n expired = Promise/withResolvers()\n force = ()\n capture expired\n @destroying = true\n for @waiting as record\n finish(record, null, \"Server closed\")\n @waiting = []\n if @server != null\n @server.closeAllConnections()\n expired.reject(\"Server shutdown timed out\")\n timer = setTimeout(force, @definition.settings.shutdownTimeoutMs)\n return chain Promise/race([drained, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n return destroyPool()\n finally\n @state = \"closed\"\n\nServer:destroyPool()\n @destroying = true\n if @pool == null\n return Promise/resolve(null)\n pool = @pool\n pending = Promise/resolve(null)\n if @definition.settings.database != null and @state == \"closing\" and @active == 0\n remaining = @shutdownDeadline - Date/now()\n if remaining > 0\n tasks = []\n for range(@definition.settings.workers) as index\n tasks.add(pool.run({\n close: true\n }))\n pending = startupDeadline(Promise/all(tasks), remaining)\n return chain pending\n finally\n capture pool\n return pool.destroy()\n\nServer:send(res, result)\n if @state == \"closing\"\n result.headers.connection = \"close\"\n return write(res, result)\n\nfailure(status, code)\n return {\n status: status\n headers: {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n body: to_json({\n error: code\n })\n }\n\nwrite(res, result)\n if res.destroyed or res.writableEnded\n return null\n try\n res.writeHead(result.status, result.headers)\n res.end(result.body)\n catch error\n res.destroy()\n return null\n\nrejectHttp(req, res, status, code)\n res.setHeader(\"Connection\", \"close\")\n res.once(\"finish\", ()\n capture req\n req.destroy()\n )\n req.resume()\n return write(res, failure(status, code))\n\nmain(args)\n if args.length != 1\n throw \"Usage: lango-server <application-directory>\"\n server = new Server(args[0])\n stop = ()\n capture server\n return chain server.close()\n catch(error)\n context log\n log.err(\"Server shutdown failed\")\n process.exitCode = 1\n process.once(\"SIGTERM\", stop)\n process.once(\"SIGINT\", stop)\n return chain server.start()\n then(address)\n context log\n log.info(\"Listening on ${address.host}:${address.port}\")\n return null\n catch(error)\n capture stop\n process.removeListener(\"SIGTERM\", stop)\n process.removeListener(\"SIGINT\", stop)\n throw error\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA;;;;;;;;AA6EA;;;;;;;;;;;;;;;;;AAsPA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./longpoll_broker\"\n class LongpollBroker\nimport \"./longpoll_session\"\n class LongpollSession\nimport \"./database\"\n prepareDatabase(settings)\nimport js \"node:http\" as http\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js \"node:crypto\" as crypto\nimport js \"piscina\" as piscina\nimport js global process\nimport js global Promise\nimport js global Date\nimport js global Math\nimport js global Object\nimport js global Reflect\nimport js global AbortController\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./options\"\n deployment(directory)\nimport \"./routes\"\n class Routes\nimport \"./body_reader\"\n class BodyReader\nimport \"./static_files\"\n class StaticFiles\n\nexport main(args)\n\nexport class Server(path, definition = null)\n methods\n start()\n close()\n publish(path, key, data)\n cursor(path, key)\n\nServer(path, definition = null)\n if path != null\n directory = path\n routes = new Routes(directory)\n routes.xml(pathJoin(directory, \"routes.xml\"))\n definition = {\n settings: deployment(directory)\n routes: routes.definitions()\n events: routes.events()\n middlewares: routes.middlewares()\n }\n if definition == null\n throw \"Use Server(directory) or Builder.build()\"\n @definition = from_json(to_json(definition))\n @broker = new LongpollBroker(@definition.settings, @definition.routes)\n @polls = Object/create(null)\n @state = \"new\"\n @connections = []\n @server = null\n @pool = null\n @starting = null\n @closing = null\n @waiting = []\n @active = 0\n @tasks = Object/create(null)\n @ready = Promise/withResolvers()\n @readyIds = []\n @destroying = false\n @static = null\n\npathJoin(directory, file)\n return path/join(directory, file)\n\nServer:publish(path, key, data)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.publish(path, key, data)\n\nServer:cursor(path, key)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.cursor(path, key)\n\nServer:start()\n if @state != \"new\"\n return Promise/reject(\"Server can only be started once\")\n @state = \"starting\"\n @starting = launch()\n return @starting\n\nServer:launch()\n settings = @definition.settings\n if settings.static != null\n try\n @static = new StaticFiles(settings.static)\n catch error\n @state = \"closed\"\n return Promise/reject(error)\n return chain @broker.open()\n then(ignored)\n capture settings\n return prepareDatabase(settings.database)\n then(ignored)\n capture path\n capture modules\n capture settings\n resolver = modules/createRequire(path/join(settings.root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @pool = new piscina/Piscina({\n filename: path/join(path/dirname(entry), \"worker.mjs\")\n name: \"execute\"\n minThreads: settings.workers\n maxThreads: settings.workers\n maxQueue: settings.maxQueue\n concurrentTasksPerWorker: 1\n closeTimeout: settings.shutdownTimeoutMs\n workerData: @definition\n })\n pool = @pool\n pool.on(\"message\", (message)\n messageReceived(message)\n )\n pool.on(\"error\", (error)\n @ready.reject(error)\n context log\n log.err(\"Worker pool error\")\n )\n return startupDeadline(@ready.promise, settings.startupTimeoutMs)\n then(ignored)\n capture settings\n if @state != \"starting\"\n throw \"Server closed during startup\"\n server = new http/Server((req, res)\n receive(req, res)\n )\n @server = server\n server.on(\"connection\", (socket)\n connected(socket)\n )\n server.headersTimeout = settings.bodyTimeoutMs\n server.requestTimeout = settings.bodyTimeoutMs\n listening = new Promise((resolve, reject)\n capture server\n capture settings\n server.once(\"error\", reject)\n server.listen(settings.port, settings.host, ()\n capture server\n capture resolve\n capture reject\n server.removeListener(\"error\", reject)\n if @state != \"starting\"\n reject(\"Server closed during startup\")\n return null\n @state = \"running\"\n address = server.address()\n resolve({\n host: address.address\n port: address.port\n })\n )\n )\n return listening\n catch(error)\n @broker.close()\n @state = \"closed\"\n return chain destroyPool()\n then(ignored)\n capture error\n throw error\n\nstartupDeadline(pending, timeout)\n expired = Promise/withResolvers()\n expire = ()\n capture expired\n expired.reject(\"Worker startup timed out\")\n timer = setTimeout(expire, timeout)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n\nServer:messageReceived(message)\n if message.kind == \"longpoll\"\n brokerMessage(message)\n return null\n if message.kind == \"ready\"\n if !@readyIds.includes(message.threadId)\n @readyIds.add(message.threadId)\n if @readyIds.length >= @definition.settings.workers\n @ready.resolve(null)\n return null\n if !(message.id in @tasks)\n return null\n record = @tasks[message.id]\n if message.kind == \"prepared\"\n record.result = message.result\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"event\"\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"handler\" and record.result == null\n resetDeadline(record, record.deadline - Date/now())\n return null\n\nServer:resetDeadline(record, duration)\n clearTimeout(record.timer)\n if record.result == null\n duration = Math/min(duration, record.deadline - Date/now())\n expired = ()\n capture record\n expire(record)\n record.timer = setTimeout(expired, Math/max(1, duration))\n return null\n\nServer:connected(socket)\n record = {\n socket: socket\n active: 0\n }\n @connections.add(record)\n socket.once(\"close\", ()\n capture record\n index = @connections.indexOf(record)\n if index >= 0\n @connections.splice(index, 1)\n )\n return null\n\nServer:trackResponse(req, res)\n for @connections as record\n if record.socket == req.socket\n record.active = record.active + 1\n state = {\n done: false\n }\n complete = ()\n capture record\n capture state\n if state.done\n return null\n state.done = true\n record.active = record.active - 1\n if @state == \"closing\" and record.active == 0\n record.socket.end()\n return null\n res.once(\"finish\", complete)\n res.once(\"close\", complete)\n return null\n return null\n\nServer:receive(req, res)\n trackResponse(req, res)\n req.on(\"error\", (error)\n return null\n )\n if @state != \"running\"\n return rejectHttp(req, res, 503, \"Unavailable\")\n if @static != null and (req.method == \"GET\" or req.method == \"HEAD\")\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n return @static.receive(req, res, failed)\n if req.method != \"POST\"\n allowed = \"POST\"\n if @static != null\n allowed = \"GET, HEAD, POST\"\n res.setHeader(\"Allow\", allowed)\n return rejectHttp(req, res, 405, \"MethodNotAllowed\")\n if req.url.includes(\"?\") or req.url.includes(\"#\") or req.url.includes(\"\\\\\")\n return rejectHttp(req, res, 400, \"InvalidPath\")\n type = req.headers[\"content-type\"]\n media = \"\"\n if is_string(type)\n parts = type.split(\";\")\n media = parts[0].trim()\n if media.toLowerCase() != \"application/json\"\n return rejectHttp(req, res, 415, \"JsonRequired\")\n settings = @definition.settings\n if @active >= settings.workers and @waiting.length >= settings.maxQueue\n return rejectHttp(req, res, 503, \"QueueFull\")\n complete = (body)\n capture req\n capture res\n submit(req, res, body)\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n reader = new BodyReader(req, res, settings, complete, failed)\n reader.start()\n return null\n\nServer:submit(req, res, body)\n pending = null\n route = @broker.route(req.url)\n if route == null\n pending = dispatch(req, res, body)\n else\n pending = longpoll(req, res, body, route)\n return chain pending\n then(result)\n capture res\n send(res, result)\n return null\n catch(error)\n capture res\n send(res, failure(500, \"InternalServerError\"))\n return null\n\nServer:longpoll(req, res, body, route)\n if Object/keys(@polls).length >= @definition.settings.redis.maxPendingPolls\n return Promise/resolve(failure(503, \"PollLimit\"))\n authorize = (token, result)\n capture req\n capture res\n capture body\n return dispatch(req, res, body, true, token, result)\n session = new LongpollSession(@broker, route, authorize, body)\n id = crypto/randomUUID()\n @polls[id] = session\n disconnected = ()\n capture session\n session.cancel()\n res.once(\"close\", disconnected)\n return chain session.run()\n finally\n capture res\n capture disconnected\n capture id\n res.removeListener(\"close\", disconnected)\n Reflect/deleteProperty(@polls, id)\n\nServer:brokerMessage(message)\n port = message.port\n pending = null\n try\n switch message.operation\n case \"publish\"\n pending = publish(message.path, message.key, message.data)\n case \"cursor\"\n pending = cursor(message.path, message.key)\n else\n pending = Promise/reject(\"Unknown longpoll operation\")\n catch error\n pending = Promise/reject(error)\n return chain pending\n then(value)\n capture port\n brokerReply(port, {\n ok: true\n value: value\n })\n catch(error)\n capture port\n brokerReply(port, {\n ok: false\n })\n finally\n capture port\n port.close()\n\nServer:dispatch(req, res, body, authorize = false, token = null, pollResult = null)\n settings = @definition.settings\n if @state != \"running\" or (@active >= settings.workers and @waiting.length >= settings.maxQueue)\n return Promise/resolve(failure(503, \"Unavailable\"))\n id = crypto/randomUUID()\n record = {\n id: id\n task: {\n authorize: authorize\n pollResult: pollResult\n body: body\n request: {\n id: id\n method: req.method\n path: req.url\n headers: Object/assign({}, req.headers)\n remoteAddress: req.socket.remoteAddress\n }\n }\n completed: Promise/withResolvers()\n controller: new AbortController()\n started: false\n result: null\n expired: false\n deadline: Date/now() + settings.requestTimeoutMs\n timer: null\n }\n if token != null\n record.task.request.headers.authorization = \"Bearer ${token}\"\n @tasks[id] = record\n resetDeadline(record, settings.requestTimeoutMs)\n @waiting.add(record)\n disconnected = ()\n capture res\n capture record\n if !res.writableEnded\n cancel(record)\n res.once(\"close\", disconnected)\n pump()\n return chain record.completed.promise\n catch(error)\n capture record\n if record.expired\n return failure(504, \"RequestTimeout\")\n return failure(500, \"InternalServerError\")\n finally\n capture res\n capture disconnected\n res.removeListener(\"close\", disconnected)\n\nServer:expire(record)\n record.expired = true\n cancel(record)\n return null\n\nServer:cancel(record)\n if !(record.id in @tasks)\n return null\n if record.started\n record.controller.abort()\n else\n index = @waiting.indexOf(record)\n if index >= 0\n @waiting.splice(index, 1)\n finish(record, null, \"Request cancelled\")\n return null\n\nServer:pump()\n loop while !@destroying and @waiting.length > 0 and @active < @definition.settings.workers\n record = @waiting.shift()\n record.started = true\n @active = @active + 1\n pending = @pool.run(record.task, {\n signal: record.controller.signal\n })\n settle(record, pending)\n return null\n\nServer:settle(record, pending)\n return chain pending\n then(result)\n capture record\n finish(record, result, null)\n return null\n catch(error)\n capture record\n if record.result != null\n context log\n log.err(\"[${record.id}] Request event interrupted; preserving prepared result\")\n finish(record, record.result, error)\n return null\n finally\n @active = @active - 1\n pump()\n\nServer:finish(record, result, error)\n clearTimeout(record.timer)\n Reflect/deleteProperty(@tasks, record.id)\n if result != null\n record.completed.resolve(result)\n else\n record.completed.reject(error)\n return null\n\nServer:close()\n if @closing != null\n return @closing\n previous = @state\n @state = \"closing\"\n @shutdownDeadline = Date/now() + @definition.settings.shutdownTimeoutMs\n if previous == \"new\" or previous == \"closed\"\n @state = \"closed\"\n @closing = Promise/resolve(null)\n return @closing\n @ready.reject(\"Server closed during startup\")\n @closing = stop()\n return @closing\n\nServer:stop()\n for @connections as record\n if record.active == 0\n record.socket.destroy()\n for @polls as id: session\n session.cancel()\n drained = new Promise((resolve)\n server = @server\n if server == null or !server.listening\n resolve(null)\n else\n server.close(()\n capture resolve\n resolve(null)\n )\n )\n expired = Promise/withResolvers()\n force = ()\n capture expired\n @destroying = true\n for @waiting as record\n finish(record, null, \"Server closed\")\n @waiting = []\n if @server != null\n @server.closeAllConnections()\n expired.reject(\"Server shutdown timed out\")\n timer = setTimeout(force, @definition.settings.shutdownTimeoutMs)\n return chain Promise/race([drained, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n return destroyPool()\n finally\n @broker.close()\n @state = \"closed\"\n\nServer:destroyPool()\n @destroying = true\n if @pool == null\n return Promise/resolve(null)\n pool = @pool\n pending = Promise/resolve(null)\n if @definition.settings.database != null and @state == \"closing\" and @active == 0\n remaining = @shutdownDeadline - Date/now()\n if remaining > 0\n tasks = []\n for range(@definition.settings.workers) as index\n tasks.add(pool.run({\n close: true\n }))\n pending = startupDeadline(Promise/all(tasks), remaining)\n return chain pending\n finally\n capture pool\n return pool.destroy()\n\nServer:send(res, result)\n if @state == \"closing\"\n result.headers.connection = \"close\"\n return write(res, result)\n\nfailure(status, code)\n return {\n status: status\n headers: {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n body: to_json({\n error: code\n })\n }\n\nwrite(res, result)\n if res.destroyed or res.writableEnded\n return null\n try\n res.writeHead(result.status, result.headers)\n res.end(result.body)\n catch error\n res.destroy()\n return null\n\nrejectHttp(req, res, status, code)\n res.setHeader(\"Connection\", \"close\")\n res.once(\"finish\", ()\n capture req\n req.destroy()\n )\n req.resume()\n return write(res, failure(status, code))\n\nmain(args)\n if args.length != 1\n throw \"Usage: lango-server <application-directory>\"\n server = new Server(args[0])\n stop = ()\n capture server\n return chain server.close()\n catch(error)\n context log\n log.err(\"Server shutdown failed\")\n process.exitCode = 1\n process.once(\"SIGTERM\", stop)\n process.once(\"SIGINT\", stop)\n return chain server.start()\n then(address)\n context log\n log.info(\"Listening on ${address.host}:${address.port}\")\n return null\n catch(error)\n capture stop\n process.removeListener(\"SIGTERM\", stop)\n process.removeListener(\"SIGINT\", stop)\n throw error\n\nbrokerReply(port, message)\n try\n port.postMessage(message)\n catch error\n return null\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;AAoGA;;;;;;;;;;;;;;;;;AAgXA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA;;;;;;;;;;;;;"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import * as threads from "node:worker_threads";
|
|
2
|
+
import {
|
|
3
|
+
hostGlobal as __hostGlobal,
|
|
4
|
+
hostGlobalCall as __hostGlobalCall,
|
|
5
|
+
fromJson as __fromJson,
|
|
6
|
+
toJson as __toJson,
|
|
7
|
+
requireBoolean as __requireBoolean,
|
|
8
|
+
normalize as __normalize,
|
|
9
|
+
call as __call,
|
|
10
|
+
boundary as __boundary,
|
|
11
|
+
requireArity as __requireArity,
|
|
12
|
+
withArity as __withArity,
|
|
13
|
+
} from "./.lango/runtime.mjs";
|
|
14
|
+
|
|
15
|
+
export class ServerContext {
|
|
16
|
+
constructor() {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
publish(path, key, data) {
|
|
20
|
+
__requireArity(arguments.length, [0, 1, 2], "publish");
|
|
21
|
+
path = __boundary(path);
|
|
22
|
+
key = __boundary(key);
|
|
23
|
+
data = __boundary(data);
|
|
24
|
+
return invoke("publish", path, key, data);
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
cursor(path, key) {
|
|
28
|
+
__requireArity(arguments.length, [0, 1], "cursor");
|
|
29
|
+
path = __boundary(path);
|
|
30
|
+
key = __boundary(key);
|
|
31
|
+
return invoke("cursor", path, key, null);
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function invoke(operation, path, key, data) {
|
|
36
|
+
__requireArity(arguments.length, [0, 1, 2, 3], "invoke");
|
|
37
|
+
operation = __boundary(operation);
|
|
38
|
+
path = __boundary(path);
|
|
39
|
+
key = __boundary(key);
|
|
40
|
+
data = __boundary(data);
|
|
41
|
+
let channel = new threads.MessageChannel();
|
|
42
|
+
let port = __normalize(channel.port1);
|
|
43
|
+
let remote = __normalize(channel.port2);
|
|
44
|
+
let pending = new (__hostGlobal(["Promise"]))(__withArity((resolve, reject) => {
|
|
45
|
+
resolve = __boundary(resolve);
|
|
46
|
+
reject = __boundary(reject);
|
|
47
|
+
__normalize(port.once("message", __withArity((message) => {
|
|
48
|
+
message = __boundary(message);
|
|
49
|
+
if (__requireBoolean(__normalize(message.ok))) {
|
|
50
|
+
__call(resolve, __normalize(message.value));
|
|
51
|
+
} else {
|
|
52
|
+
__call(reject, "Longpoll operation failed");
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}, [0], "closure")));
|
|
56
|
+
return null;
|
|
57
|
+
}, [0, 1], "closure"));
|
|
58
|
+
let expired = __normalize(__hostGlobal(["Promise"]).withResolvers());
|
|
59
|
+
let fail = () => {
|
|
60
|
+
__normalize(expired.reject("Longpoll operation timed out"));
|
|
61
|
+
return null;
|
|
62
|
+
};
|
|
63
|
+
let timer = __hostGlobalCall(["setTimeout"], fail, 4000);
|
|
64
|
+
try {
|
|
65
|
+
__normalize(threads.parentPort.postMessage({ kind: "longpoll", operation: operation, path: path, key: key, data: __fromJson(__toJson(data)), port: remote }, [remote]));
|
|
66
|
+
} catch (error) {
|
|
67
|
+
__normalize(port.close());
|
|
68
|
+
__hostGlobalCall(["clearTimeout"], timer);
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
return __normalize(__hostGlobal(["Promise"]).race([pending, __normalize(expired.promise)])).finally(() => {
|
|
72
|
+
__hostGlobalCall(["clearTimeout"], timer);
|
|
73
|
+
__normalize(port.close());
|
|
74
|
+
return null;
|
|
75
|
+
});
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=server_context.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server_context.mjs","sources":["server_context.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class ServerContext()\n methods\n publish(path, key, data)\n cursor(path, key)\n\nServerContext()\n return null\n\nServerContext:publish(path, key, data)\n return invoke(\"publish\", path, key, data)\n\nServerContext:cursor(path, key)\n return invoke(\"cursor\", path, key, null)\n\ninvoke(operation, path, key, data)\n channel = new threads/MessageChannel()\n port = channel.port1\n remote = channel.port2\n pending = new Promise((resolve, reject)\n capture port\n port.once(\"message\", (message)\n capture resolve\n capture reject\n if message.ok\n resolve(message.value)\n else\n reject(\"Longpoll operation failed\")\n )\n )\n expired = Promise/withResolvers()\n fail = ()\n capture expired\n expired.reject(\"Longpoll operation timed out\")\n timer = setTimeout(fail, 4000)\n try\n threads/parentPort/postMessage({\n kind: \"longpoll\"\n operation: operation\n path: path\n key: key\n data: from_json(to_json(data))\n port: remote\n }, [remote])\n catch error\n port.close()\n clearTimeout(timer)\n throw error\n return chain Promise/race([pending, expired.promise])\n finally\n capture port\n capture timer\n clearTimeout(timer)\n port.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|