@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/cli/server.mjs
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { LongpollBroker } from "./longpoll_broker.mjs";
|
|
3
|
+
import { LongpollSession } from "./longpoll_session.mjs";
|
|
2
4
|
import { prepareDatabase } from "./database.mjs";
|
|
3
5
|
import { deployment } from "./options.mjs";
|
|
4
6
|
import { Routes } from "./routes.mjs";
|
|
5
7
|
import { BodyReader } from "./body_reader.mjs";
|
|
8
|
+
import { StaticFiles } from "./static_files.mjs";
|
|
6
9
|
import * as http from "node:http";
|
|
7
10
|
import * as path from "node:path";
|
|
8
11
|
import * as modules from "node:module";
|
|
@@ -22,6 +25,7 @@ import {
|
|
|
22
25
|
isObject as __isObject,
|
|
23
26
|
isArray as __isArray,
|
|
24
27
|
includes as __includes,
|
|
28
|
+
entries as __entries,
|
|
25
29
|
range as __range,
|
|
26
30
|
add as __add,
|
|
27
31
|
requireBoolean as __requireBoolean,
|
|
@@ -36,7 +40,10 @@ import {
|
|
|
36
40
|
|
|
37
41
|
export class Server {
|
|
38
42
|
#definition;
|
|
43
|
+
#broker;
|
|
44
|
+
#polls;
|
|
39
45
|
#state;
|
|
46
|
+
#connections;
|
|
40
47
|
#server;
|
|
41
48
|
#pool;
|
|
42
49
|
#starting;
|
|
@@ -47,6 +54,7 @@ export class Server {
|
|
|
47
54
|
#ready;
|
|
48
55
|
#readyIds;
|
|
49
56
|
#destroying;
|
|
57
|
+
#static;
|
|
50
58
|
#lango;
|
|
51
59
|
#shutdownDeadline;
|
|
52
60
|
constructor(path, definition = null) {
|
|
@@ -57,13 +65,16 @@ export class Server {
|
|
|
57
65
|
let directory = path;
|
|
58
66
|
let routes = new Routes(directory);
|
|
59
67
|
__normalize(routes.xml(pathJoin(directory, "routes.xml")));
|
|
60
|
-
definition = { settings: deployment(directory), routes: __normalize(routes.definitions()), events: __normalize(routes.events()) };
|
|
68
|
+
definition = { settings: deployment(directory), routes: __normalize(routes.definitions()), events: __normalize(routes.events()), middlewares: __normalize(routes.middlewares()) };
|
|
61
69
|
}
|
|
62
70
|
if (__requireBoolean(definition === null)) {
|
|
63
71
|
throw "Use Server(directory) or Builder.build()";
|
|
64
72
|
}
|
|
65
73
|
this.#definition = __fromJson(__toJson(definition));
|
|
74
|
+
this.#broker = new LongpollBroker(__normalize(this.#definition.settings), __normalize(this.#definition.routes));
|
|
75
|
+
this.#polls = __normalize(__hostGlobal(["Object"]).create(null));
|
|
66
76
|
this.#state = "new";
|
|
77
|
+
this.#connections = [];
|
|
67
78
|
this.#server = null;
|
|
68
79
|
this.#pool = null;
|
|
69
80
|
this.#starting = null;
|
|
@@ -74,6 +85,28 @@ export class Server {
|
|
|
74
85
|
this.#ready = __normalize(__hostGlobal(["Promise"]).withResolvers());
|
|
75
86
|
this.#readyIds = [];
|
|
76
87
|
this.#destroying = false;
|
|
88
|
+
this.#static = null;
|
|
89
|
+
}
|
|
90
|
+
publish(path, key, data) {
|
|
91
|
+
__requireArity(arguments.length, [0, 1, 2], "publish");
|
|
92
|
+
path = __boundary(path);
|
|
93
|
+
key = __boundary(key);
|
|
94
|
+
data = __boundary(data);
|
|
95
|
+
if (__requireBoolean(__normalize(this.#state) !== "running")) {
|
|
96
|
+
return __normalize(__hostGlobal(["Promise"]).reject("Server is not running"));
|
|
97
|
+
}
|
|
98
|
+
return __normalize(this.#broker.publish(path, key, data));
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
cursor(path, key) {
|
|
102
|
+
__requireArity(arguments.length, [0, 1], "cursor");
|
|
103
|
+
path = __boundary(path);
|
|
104
|
+
key = __boundary(key);
|
|
105
|
+
if (__requireBoolean(__normalize(this.#state) !== "running")) {
|
|
106
|
+
return __normalize(__hostGlobal(["Promise"]).reject("Server is not running"));
|
|
107
|
+
}
|
|
108
|
+
return __normalize(this.#broker.cursor(path, key));
|
|
109
|
+
return null;
|
|
77
110
|
}
|
|
78
111
|
start() {
|
|
79
112
|
if (__requireBoolean(__normalize(this.#state) !== "new")) {
|
|
@@ -86,7 +119,19 @@ export class Server {
|
|
|
86
119
|
}
|
|
87
120
|
#launch() {
|
|
88
121
|
let settings = __normalize(this.#definition.settings);
|
|
89
|
-
|
|
122
|
+
if (__requireBoolean(__normalize(settings.static) !== null)) {
|
|
123
|
+
try {
|
|
124
|
+
this.#static = new StaticFiles(__normalize(settings.static));
|
|
125
|
+
} catch (error) {
|
|
126
|
+
this.#state = "closed";
|
|
127
|
+
return __normalize(__hostGlobal(["Promise"]).reject(error));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return __normalize(this.#broker.open()).then(__withArity((ignored) => {
|
|
131
|
+
ignored = __boundary(ignored);
|
|
132
|
+
return prepareDatabase(__normalize(settings.database));
|
|
133
|
+
return null;
|
|
134
|
+
}, [0], "closure")).then(__withArity((ignored) => {
|
|
90
135
|
ignored = __boundary(ignored);
|
|
91
136
|
let resolver = __normalize(modules.createRequire(__normalize(path.join(__normalize(settings.root), "package.json"))));
|
|
92
137
|
let entry = __normalize(resolver.resolve("@lango-project/lango-server"));
|
|
@@ -122,6 +167,11 @@ export class Server {
|
|
|
122
167
|
return null;
|
|
123
168
|
}, [0, 1], "closure"));
|
|
124
169
|
this.#server = server;
|
|
170
|
+
__normalize(server.on("connection", __withArity((socket) => {
|
|
171
|
+
socket = __boundary(socket);
|
|
172
|
+
this.#connected(socket);
|
|
173
|
+
return null;
|
|
174
|
+
}, [0], "closure")));
|
|
125
175
|
server.headersTimeout = __normalize(settings.bodyTimeoutMs);
|
|
126
176
|
server.requestTimeout = __normalize(settings.bodyTimeoutMs);
|
|
127
177
|
let listening = new (__hostGlobal(["Promise"]))(__withArity((resolve, reject) => {
|
|
@@ -145,6 +195,7 @@ export class Server {
|
|
|
145
195
|
return null;
|
|
146
196
|
}, [0], "closure")).catch(__withArity((error) => {
|
|
147
197
|
error = __boundary(error);
|
|
198
|
+
__normalize(this.#broker.close());
|
|
148
199
|
this.#state = "closed";
|
|
149
200
|
return this.#destroyPool().then(__withArity((ignored) => {
|
|
150
201
|
ignored = __boundary(ignored);
|
|
@@ -158,6 +209,10 @@ export class Server {
|
|
|
158
209
|
#messageReceived(message) {
|
|
159
210
|
__requireArity(arguments.length, [0], "messageReceived");
|
|
160
211
|
message = __boundary(message);
|
|
212
|
+
if (__requireBoolean(__normalize(message.kind) === "longpoll")) {
|
|
213
|
+
this.#brokerMessage(message);
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
161
216
|
if (__requireBoolean(__normalize(message.kind) === "ready")) {
|
|
162
217
|
if (__requireBoolean(!__requireBoolean(__normalize(this.#readyIds.includes(__normalize(message.threadId)))))) {
|
|
163
218
|
__add(this.#readyIds, __normalize(message.threadId));
|
|
@@ -200,10 +255,54 @@ export class Server {
|
|
|
200
255
|
return null;
|
|
201
256
|
return null;
|
|
202
257
|
}
|
|
258
|
+
#connected(socket) {
|
|
259
|
+
__requireArity(arguments.length, [0], "connected");
|
|
260
|
+
socket = __boundary(socket);
|
|
261
|
+
let record = { socket: socket, active: 0 };
|
|
262
|
+
__add(this.#connections, record);
|
|
263
|
+
__normalize(socket.once("close", () => {
|
|
264
|
+
let index = __normalize(this.#connections.indexOf(record));
|
|
265
|
+
if (__requireBoolean(index >= 0)) {
|
|
266
|
+
__normalize(this.#connections.splice(index, 1));
|
|
267
|
+
}
|
|
268
|
+
return null;
|
|
269
|
+
}));
|
|
270
|
+
return null;
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
#trackResponse(req, res) {
|
|
274
|
+
__requireArity(arguments.length, [0, 1], "trackResponse");
|
|
275
|
+
req = __boundary(req);
|
|
276
|
+
res = __boundary(res);
|
|
277
|
+
for (const record of __normalize(this.#connections)) {
|
|
278
|
+
if (__requireBoolean(__normalize(record.socket) === __normalize(req.socket))) {
|
|
279
|
+
record.active = __numericAdd(__normalize(record.active), 1);
|
|
280
|
+
let state = { done: false };
|
|
281
|
+
let complete = () => {
|
|
282
|
+
if (__requireBoolean(__normalize(state.done))) {
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
285
|
+
state.done = true;
|
|
286
|
+
record.active = __finite(__normalize(record.active) - 1);
|
|
287
|
+
if (__requireBoolean(__requireBoolean(__normalize(this.#state) === "closing") && __requireBoolean(__normalize(record.active) === 0))) {
|
|
288
|
+
__normalize(record.socket.end());
|
|
289
|
+
}
|
|
290
|
+
return null;
|
|
291
|
+
return null;
|
|
292
|
+
};
|
|
293
|
+
__normalize(res.once("finish", complete));
|
|
294
|
+
__normalize(res.once("close", complete));
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return null;
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
203
301
|
#receive(req, res) {
|
|
204
302
|
__requireArity(arguments.length, [0, 1], "receive");
|
|
205
303
|
req = __boundary(req);
|
|
206
304
|
res = __boundary(res);
|
|
305
|
+
this.#trackResponse(req, res);
|
|
207
306
|
__normalize(req.on("error", __withArity((error) => {
|
|
208
307
|
error = __boundary(error);
|
|
209
308
|
return null;
|
|
@@ -212,8 +311,21 @@ export class Server {
|
|
|
212
311
|
if (__requireBoolean(__normalize(this.#state) !== "running")) {
|
|
213
312
|
return rejectHttp(req, res, 503, "Unavailable");
|
|
214
313
|
}
|
|
314
|
+
if (__requireBoolean(__requireBoolean(__normalize(this.#static) !== null) && __requireBoolean(__requireBoolean(__normalize(req.method) === "GET") || __requireBoolean(__normalize(req.method) === "HEAD")))) {
|
|
315
|
+
let failed = __withArity((status, code) => {
|
|
316
|
+
status = __boundary(status);
|
|
317
|
+
code = __boundary(code);
|
|
318
|
+
this.#send(res, failure(status, code));
|
|
319
|
+
return null;
|
|
320
|
+
}, [0, 1], "closure");
|
|
321
|
+
return __normalize(this.#static.receive(req, res, failed));
|
|
322
|
+
}
|
|
215
323
|
if (__requireBoolean(__normalize(req.method) !== "POST")) {
|
|
216
|
-
|
|
324
|
+
let allowed = "POST";
|
|
325
|
+
if (__requireBoolean(__normalize(this.#static) !== null)) {
|
|
326
|
+
allowed = "GET, HEAD, POST";
|
|
327
|
+
}
|
|
328
|
+
__normalize(res.setHeader("Allow", allowed));
|
|
217
329
|
return rejectHttp(req, res, 405, "MethodNotAllowed");
|
|
218
330
|
}
|
|
219
331
|
if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(req.url.includes("?"))) || __requireBoolean(__normalize(req.url.includes("#")))) || __requireBoolean(__normalize(req.url.includes("\\"))))) {
|
|
@@ -253,39 +365,125 @@ export class Server {
|
|
|
253
365
|
req = __boundary(req);
|
|
254
366
|
res = __boundary(res);
|
|
255
367
|
body = __boundary(body);
|
|
368
|
+
let pending = null;
|
|
369
|
+
let route = __normalize(this.#broker.route(__normalize(req.url)));
|
|
370
|
+
if (__requireBoolean(route === null)) {
|
|
371
|
+
pending = this.#dispatch(req, res, body);
|
|
372
|
+
} else {
|
|
373
|
+
pending = this.#longpoll(req, res, body, route);
|
|
374
|
+
}
|
|
375
|
+
return pending.then(__withArity((result) => {
|
|
376
|
+
result = __boundary(result);
|
|
377
|
+
this.#send(res, result);
|
|
378
|
+
return null;
|
|
379
|
+
return null;
|
|
380
|
+
}, [0], "closure")).catch(__withArity((error) => {
|
|
381
|
+
error = __boundary(error);
|
|
382
|
+
this.#send(res, failure(500, "InternalServerError"));
|
|
383
|
+
return null;
|
|
384
|
+
return null;
|
|
385
|
+
}, [0], "closure"));
|
|
386
|
+
return null;
|
|
387
|
+
}
|
|
388
|
+
#longpoll(req, res, body, route) {
|
|
389
|
+
__requireArity(arguments.length, [0, 1, 2, 3], "longpoll");
|
|
390
|
+
req = __boundary(req);
|
|
391
|
+
res = __boundary(res);
|
|
392
|
+
body = __boundary(body);
|
|
393
|
+
route = __boundary(route);
|
|
394
|
+
if (__requireBoolean(__normalize(__normalize(__hostGlobal(["Object"]).keys(__normalize(this.#polls))).length) >= __normalize(this.#definition.settings.redis.maxPendingPolls))) {
|
|
395
|
+
return __normalize(__hostGlobal(["Promise"]).resolve(failure(503, "PollLimit")));
|
|
396
|
+
}
|
|
397
|
+
let authorize = __withArity((token, result) => {
|
|
398
|
+
token = __boundary(token);
|
|
399
|
+
result = __boundary(result);
|
|
400
|
+
return this.#dispatch(req, res, body, true, token, result);
|
|
401
|
+
return null;
|
|
402
|
+
}, [0, 1], "closure");
|
|
403
|
+
let session = new LongpollSession(__normalize(this.#broker), route, authorize, body);
|
|
404
|
+
let id = __normalize(crypto.randomUUID());
|
|
405
|
+
this.#polls[id] = session;
|
|
406
|
+
let disconnected = () => {
|
|
407
|
+
__normalize(session.cancel());
|
|
408
|
+
return null;
|
|
409
|
+
};
|
|
410
|
+
__normalize(res.once("close", disconnected));
|
|
411
|
+
return __normalize(session.run()).finally(() => {
|
|
412
|
+
__normalize(res.removeListener("close", disconnected));
|
|
413
|
+
__normalize(__hostGlobal(["Reflect"]).deleteProperty(__normalize(this.#polls), id));
|
|
414
|
+
return null;
|
|
415
|
+
});
|
|
416
|
+
return null;
|
|
417
|
+
}
|
|
418
|
+
#brokerMessage(message) {
|
|
419
|
+
__requireArity(arguments.length, [0], "brokerMessage");
|
|
420
|
+
message = __boundary(message);
|
|
421
|
+
let port = __normalize(message.port);
|
|
422
|
+
let pending = null;
|
|
423
|
+
try {
|
|
424
|
+
if (__normalize(message.operation) === "publish") {
|
|
425
|
+
pending = this.publish(__normalize(message.path), __normalize(message.key), __normalize(message.data));
|
|
426
|
+
} else if (__normalize(message.operation) === "cursor") {
|
|
427
|
+
pending = this.cursor(__normalize(message.path), __normalize(message.key));
|
|
428
|
+
} else {
|
|
429
|
+
pending = __normalize(__hostGlobal(["Promise"]).reject("Unknown longpoll operation"));
|
|
430
|
+
}
|
|
431
|
+
} catch (error) {
|
|
432
|
+
pending = __normalize(__hostGlobal(["Promise"]).reject(error));
|
|
433
|
+
}
|
|
434
|
+
return pending.then(__withArity((value) => {
|
|
435
|
+
value = __boundary(value);
|
|
436
|
+
brokerReply(port, { ok: true, value: value });
|
|
437
|
+
return null;
|
|
438
|
+
}, [0], "closure")).catch(__withArity((error) => {
|
|
439
|
+
error = __boundary(error);
|
|
440
|
+
brokerReply(port, { ok: false });
|
|
441
|
+
return null;
|
|
442
|
+
}, [0], "closure")).finally(() => {
|
|
443
|
+
__normalize(port.close());
|
|
444
|
+
return null;
|
|
445
|
+
});
|
|
446
|
+
return null;
|
|
447
|
+
}
|
|
448
|
+
#dispatch(req, res, body, authorize = false, token = null, pollResult = null) {
|
|
449
|
+
__requireArity(arguments.length, [0, 1, 2], "dispatch");
|
|
450
|
+
req = __boundary(req);
|
|
451
|
+
res = __boundary(res);
|
|
452
|
+
body = __boundary(body);
|
|
453
|
+
authorize = __boundary(authorize);
|
|
454
|
+
token = __boundary(token);
|
|
455
|
+
pollResult = __boundary(pollResult);
|
|
256
456
|
let settings = __normalize(this.#definition.settings);
|
|
257
457
|
if (__requireBoolean(__requireBoolean(__normalize(this.#state) !== "running") || __requireBoolean(__requireBoolean(__normalize(this.#active) >= __normalize(settings.workers)) && __requireBoolean(__normalize(this.#waiting.length) >= __normalize(settings.maxQueue))))) {
|
|
258
|
-
return
|
|
458
|
+
return __normalize(__hostGlobal(["Promise"]).resolve(failure(503, "Unavailable")));
|
|
259
459
|
}
|
|
260
460
|
let id = __normalize(crypto.randomUUID());
|
|
261
|
-
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 };
|
|
461
|
+
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 };
|
|
462
|
+
if (__requireBoolean(token !== null)) {
|
|
463
|
+
record.task.request.headers.authorization = `Bearer ${token}`;
|
|
464
|
+
}
|
|
262
465
|
this.#tasks[id] = record;
|
|
263
466
|
this.#resetDeadline(record, __normalize(settings.requestTimeoutMs));
|
|
264
467
|
__add(this.#waiting, record);
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
return null;
|
|
270
|
-
}));
|
|
271
|
-
this.#pump();
|
|
272
|
-
return record.completed.promise.then(__withArity((result) => {
|
|
273
|
-
result = __boundary(result);
|
|
274
|
-
this.#send(res, result);
|
|
275
|
-
return null;
|
|
468
|
+
let disconnected = () => {
|
|
469
|
+
if (__requireBoolean(!__requireBoolean(__normalize(res.writableEnded)))) {
|
|
470
|
+
this.#cancel(record);
|
|
471
|
+
}
|
|
276
472
|
return null;
|
|
277
|
-
}
|
|
473
|
+
};
|
|
474
|
+
__normalize(res.once("close", disconnected));
|
|
475
|
+
this.#pump();
|
|
476
|
+
return record.completed.promise.catch(__withArity((error) => {
|
|
278
477
|
error = __boundary(error);
|
|
279
|
-
let code = 500;
|
|
280
|
-
let name = "InternalServerError";
|
|
281
478
|
if (__requireBoolean(__normalize(record.expired))) {
|
|
282
|
-
|
|
283
|
-
name = "RequestTimeout";
|
|
479
|
+
return failure(504, "RequestTimeout");
|
|
284
480
|
}
|
|
285
|
-
|
|
481
|
+
return failure(500, "InternalServerError");
|
|
286
482
|
return null;
|
|
483
|
+
}, [0], "closure")).finally(() => {
|
|
484
|
+
__normalize(res.removeListener("close", disconnected));
|
|
287
485
|
return null;
|
|
288
|
-
}
|
|
486
|
+
});
|
|
289
487
|
return null;
|
|
290
488
|
}
|
|
291
489
|
#expire(record) {
|
|
@@ -387,6 +585,14 @@ export class Server {
|
|
|
387
585
|
return null;
|
|
388
586
|
}
|
|
389
587
|
#stop() {
|
|
588
|
+
for (const record of __normalize(this.#connections)) {
|
|
589
|
+
if (__requireBoolean(__normalize(record.active) === 0)) {
|
|
590
|
+
__normalize(record.socket.destroy());
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
for (const [id, session] of __entries(__normalize(this.#polls))) {
|
|
594
|
+
__normalize(session.cancel());
|
|
595
|
+
}
|
|
390
596
|
let drained = new (__hostGlobal(["Promise"]))(__withArity((resolve) => {
|
|
391
597
|
resolve = __boundary(resolve);
|
|
392
598
|
let server = __normalize(this.#server);
|
|
@@ -419,6 +625,7 @@ export class Server {
|
|
|
419
625
|
return this.#destroyPool();
|
|
420
626
|
return null;
|
|
421
627
|
}).finally(() => {
|
|
628
|
+
__normalize(this.#broker.close());
|
|
422
629
|
this.#state = "closed";
|
|
423
630
|
return null;
|
|
424
631
|
});
|
|
@@ -566,6 +773,19 @@ export function main(args) {
|
|
|
566
773
|
}, [0], "closure"));
|
|
567
774
|
return null;
|
|
568
775
|
}
|
|
776
|
+
|
|
777
|
+
function brokerReply(port, message) {
|
|
778
|
+
__requireArity(arguments.length, [0, 1], "brokerReply");
|
|
779
|
+
port = __boundary(port);
|
|
780
|
+
message = __boundary(message);
|
|
781
|
+
try {
|
|
782
|
+
__normalize(port.postMessage(message));
|
|
783
|
+
} catch (error) {
|
|
784
|
+
return null;
|
|
785
|
+
}
|
|
786
|
+
return null;
|
|
787
|
+
return null;
|
|
788
|
+
}
|
|
569
789
|
const { configure } = await import("./.lango/runtime.mjs");
|
|
570
790
|
configure({ output: (value) => console.log(value) });
|
|
571
791
|
await main(process.argv.slice(2));
|
package/dist/cli/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,125 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import * as files from "serve-static";
|
|
4
|
+
import {
|
|
5
|
+
hostGlobal as __hostGlobal,
|
|
6
|
+
isNumber as __isNumber,
|
|
7
|
+
isString as __isString,
|
|
8
|
+
isBool as __isBool,
|
|
9
|
+
isObject as __isObject,
|
|
10
|
+
isArray as __isArray,
|
|
11
|
+
entries as __entries,
|
|
12
|
+
requireBoolean as __requireBoolean,
|
|
13
|
+
normalize as __normalize,
|
|
14
|
+
finite as __finite,
|
|
15
|
+
call as __call,
|
|
16
|
+
boundary as __boundary,
|
|
17
|
+
requireArity as __requireArity,
|
|
18
|
+
withArity as __withArity,
|
|
19
|
+
} from "./.lango/runtime.mjs";
|
|
20
|
+
|
|
21
|
+
export class StaticFiles {
|
|
22
|
+
#settings;
|
|
23
|
+
#serve;
|
|
24
|
+
constructor(settings) {
|
|
25
|
+
__requireArity(arguments.length, [0], "constructor");
|
|
26
|
+
settings = __boundary(settings);
|
|
27
|
+
this.#settings = settings;
|
|
28
|
+
if (__requireBoolean(!__requireBoolean(__normalize(__normalize(fs.statSync(__normalize(settings.directory))).isDirectory())))) {
|
|
29
|
+
throw "Static directory must be a directory";
|
|
30
|
+
}
|
|
31
|
+
this.#serve = __normalize(files.default(__normalize(settings.directory), { index: __normalize(settings.index), dotfiles: "deny", fallthrough: false, redirect: false }));
|
|
32
|
+
}
|
|
33
|
+
receive(req, res, failed) {
|
|
34
|
+
__requireArity(arguments.length, [0, 1, 2], "receive");
|
|
35
|
+
req = __boundary(req);
|
|
36
|
+
res = __boundary(res);
|
|
37
|
+
failed = __boundary(failed);
|
|
38
|
+
let mount = __normalize(this.#settings.path);
|
|
39
|
+
let url = __normalize(req.url);
|
|
40
|
+
let pathname = __normalize(__normalize(url.split("?"))[0]);
|
|
41
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(mount !== "/") && __requireBoolean(pathname !== mount)) && __requireBoolean(!__requireBoolean(__normalize(pathname.startsWith(`${mount}/`)))))) {
|
|
42
|
+
__call(failed, 404, "NotFound");
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
if (__requireBoolean(mount !== "/")) {
|
|
46
|
+
req.url = __normalize(url.slice(__normalize(mount.length)));
|
|
47
|
+
if (__requireBoolean(__requireBoolean(__normalize(req.url) === "") || __requireBoolean(__normalize(req.url.startsWith("?"))))) {
|
|
48
|
+
req.url = `/${__normalize(req.url)}`;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
let done = __withArity((error) => {
|
|
52
|
+
error = __boundary(error);
|
|
53
|
+
if (__requireBoolean(__normalize(res.headersSent))) {
|
|
54
|
+
__normalize(res.destroy());
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
let status = 404;
|
|
58
|
+
let code = "NotFound";
|
|
59
|
+
if (__requireBoolean(error !== null)) {
|
|
60
|
+
if (__normalize(error.status) === 400) {
|
|
61
|
+
status = 400;
|
|
62
|
+
code = "InvalidPath";
|
|
63
|
+
} else if (__normalize(error.status) === 403) {
|
|
64
|
+
status = 403;
|
|
65
|
+
code = "Forbidden";
|
|
66
|
+
} else if (__normalize(error.status) === 416) {
|
|
67
|
+
status = 416;
|
|
68
|
+
code = "RangeNotSatisfiable";
|
|
69
|
+
} else if (__normalize(error.status) === 404) {
|
|
70
|
+
status = 404;
|
|
71
|
+
} else {
|
|
72
|
+
status = 500;
|
|
73
|
+
code = "InternalServerError";
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
__call(failed, status, code);
|
|
77
|
+
return null;
|
|
78
|
+
}, [0], "closure");
|
|
79
|
+
let serve = __normalize(this.#serve);
|
|
80
|
+
__call(serve, req, res, done);
|
|
81
|
+
return null;
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
export function staticOptions(root, spec) {
|
|
86
|
+
__requireArity(arguments.length, [0, 1], "staticOptions");
|
|
87
|
+
root = __boundary(root);
|
|
88
|
+
spec = __boundary(spec);
|
|
89
|
+
if (__requireBoolean(spec === null)) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(spec))) || __requireBoolean(__isArray(spec)))) {
|
|
93
|
+
throw "static must be a map";
|
|
94
|
+
}
|
|
95
|
+
let allowed = ["path", "directory", "index"];
|
|
96
|
+
for (const [key, value] of __entries(spec)) {
|
|
97
|
+
if (__requireBoolean(!__requireBoolean(__normalize(allowed.includes(key))))) {
|
|
98
|
+
throw `Unknown static option: ${key}`;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
let mount = __normalize(spec.path);
|
|
102
|
+
if (__requireBoolean(mount === null)) {
|
|
103
|
+
mount = "/";
|
|
104
|
+
}
|
|
105
|
+
let pattern = new (__hostGlobal(["RegExp"]))("^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$");
|
|
106
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(mount))) || __requireBoolean(!__requireBoolean(__normalize(pattern.test(mount)))))) {
|
|
107
|
+
throw "Static path must be an absolute URL prefix";
|
|
108
|
+
}
|
|
109
|
+
if (__requireBoolean(__requireBoolean(mount !== "/") && __requireBoolean(__normalize(mount.endsWith("/"))))) {
|
|
110
|
+
mount = __normalize(mount.slice(0, __finite(-1)));
|
|
111
|
+
}
|
|
112
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec.directory)))) || __requireBoolean(__normalize(spec.directory.trim()) === ""))) {
|
|
113
|
+
throw "Static directory is required";
|
|
114
|
+
}
|
|
115
|
+
let index = __normalize(spec.index);
|
|
116
|
+
if (__requireBoolean(index === null)) {
|
|
117
|
+
index = "index.html";
|
|
118
|
+
}
|
|
119
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(index))) || __requireBoolean(index === "")) || __requireBoolean(__normalize(index.startsWith(".")))) || __requireBoolean(__normalize(index.includes("/")))) || __requireBoolean(__normalize(index.includes("\\"))))) {
|
|
120
|
+
throw "Static index must be a file name";
|
|
121
|
+
}
|
|
122
|
+
return { path: mount, directory: __normalize(path.resolve(root, __normalize(spec.directory))), index: index };
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
//# sourceMappingURL=static_files.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"serve-static\" as files\nimport js global RegExp\n\nexport staticOptions(root, spec)\nexport class StaticFiles(settings)\n methods\n receive(req, res, failed)\n\nstaticOptions(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"static must be a map\"\n allowed = [\"path\", \"directory\", \"index\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown static option: ${key}\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n pattern = new RegExp(\"^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$\")\n if !is_string(mount) or !pattern.test(mount)\n throw \"Static path must be an absolute URL prefix\"\n if mount != \"/\" and mount.endsWith(\"/\")\n mount = mount.slice(0, -1)\n if !is_string(spec.directory) or spec.directory.trim() == \"\"\n throw \"Static directory is required\"\n index = spec.index\n if index == null\n index = \"index.html\"\n if !is_string(index) or index == \"\" or index.startsWith(\".\") or index.includes(\"/\") or index.includes(\"\\\\\")\n throw \"Static index must be a file name\"\n return {\n path: mount\n directory: path/resolve(root, spec.directory)\n index: index\n }\n\nStaticFiles(settings)\n @settings = settings\n if !fs/statSync(settings.directory).isDirectory()\n throw \"Static directory must be a directory\"\n @serve = files/default(settings.directory, {\n index: settings.index\n dotfiles: \"deny\"\n fallthrough: false\n redirect: false\n })\n\nStaticFiles:receive(req, res, failed)\n mount = @settings.path\n url = req.url\n pathname = url.split(\"?\")[0]\n if mount != \"/\" and pathname != mount and !pathname.startsWith(\"${mount}/\")\n failed(404, \"NotFound\")\n return null\n if mount != \"/\"\n req.url = url.slice(mount.length)\n if req.url == \"\" or req.url.startsWith(\"?\")\n req.url = \"/${req.url}\"\n done = (error)\n capture res\n capture failed\n if res.headersSent\n res.destroy()\n return null\n status = 404\n code = \"NotFound\"\n if error != null\n switch error.status\n case 400\n status = 400\n code = \"InvalidPath\"\n case 403\n status = 403\n code = \"Forbidden\"\n case 416\n status = 416\n code = \"RangeNotSatisfiable\"\n case 404\n status = 404\n else\n status = 500\n code = \"InternalServerError\"\n failed(status, code)\n serve = @serve\n serve(req, res, done)\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/endpoint.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { middlewareName } from "./middleware.mjs";
|
|
1
2
|
import {
|
|
2
3
|
isNumber as __isNumber,
|
|
3
4
|
isString as __isString,
|
|
@@ -15,6 +16,7 @@ export class Endpoint {
|
|
|
15
16
|
module;
|
|
16
17
|
handler;
|
|
17
18
|
auth;
|
|
19
|
+
middleware;
|
|
18
20
|
constructor(spec) {
|
|
19
21
|
__requireArity(arguments.length, [0], "constructor");
|
|
20
22
|
spec = __boundary(spec);
|
|
@@ -32,6 +34,10 @@ export class Endpoint {
|
|
|
32
34
|
this.path = __normalize(spec.path);
|
|
33
35
|
this.module = __normalize(spec.module);
|
|
34
36
|
this.handler = __normalize(spec.handler);
|
|
37
|
+
this.middleware = __normalize(spec.middleware);
|
|
38
|
+
if (__requireBoolean(__normalize(this.middleware) !== null)) {
|
|
39
|
+
middlewareName(__normalize(this.middleware));
|
|
40
|
+
}
|
|
35
41
|
this.auth = __normalize(spec.auth);
|
|
36
42
|
if (__requireBoolean(__normalize(this.auth) === null)) {
|
|
37
43
|
this.auth = "login";
|
package/dist/endpoint.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["import \"./middleware\"\n middlewareName(name)\n\nexport class Endpoint(spec)\n properties\n path\n module\n handler\n auth\n middleware\n\nEndpoint(spec)\n if !is_string(spec.path) or !spec.path.startsWith(\"/\") or spec.path.includes(\"?\") or spec.path.includes(\"#\") or spec.path.includes(\"\\\\\") or spec.path.includes(\"//\")\n throw \"Endpoint requires an absolute URL path\"\n if spec.path.includes(\"*\") and (!spec.path.endsWith(\"/*\") or spec.path.indexOf(\"*\") != spec.path.lastIndexOf(\"*\"))\n throw \"Only trailing /* wildcards are supported\"\n for [\"module\", \"handler\"] as key\n if !is_string(spec[key]) or spec[key] == \"\"\n throw \"Endpoint requires ${key}\"\n @path = spec.path\n @module = spec.module\n @handler = spec.handler\n @middleware = spec.middleware\n if @middleware != null\n middlewareName(@middleware)\n @auth = spec.auth\n if @auth == null\n @auth = \"login\"\n if !is_string(@auth) or @auth == \"\" or @auth.includes(\",\")\n throw \"Endpoint auth must name one permission\"\n"],"names":[],"mappings":";;;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|