@lango-project/lango-server 0.2.4 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +8 -0
  2. package/dist/body_reader.mjs.map +1 -1
  3. package/dist/builder.mjs.map +1 -1
  4. package/dist/cli/server.mjs +3 -838
  5. package/dist/cli/server.mjs.map +1 -1
  6. package/dist/client_identity.mjs.map +1 -1
  7. package/dist/database.mjs.map +1 -1
  8. package/dist/database_action.mjs.map +1 -1
  9. package/dist/database_options.mjs.map +1 -1
  10. package/dist/database_scope.mjs.map +1 -1
  11. package/dist/endpoint.mjs.map +1 -1
  12. package/dist/error_details.mjs.map +1 -1
  13. package/dist/execution_failure.mjs.map +1 -1
  14. package/dist/execution_identity.mjs.map +1 -1
  15. package/dist/execution_log.mjs.map +1 -1
  16. package/dist/execution_runtime.mjs.map +1 -1
  17. package/dist/execution_worker.mjs.map +1 -1
  18. package/dist/executor.mjs.map +1 -1
  19. package/dist/group.mjs.map +1 -1
  20. package/dist/http_failure.mjs.map +1 -1
  21. package/dist/job_configuration.mjs.map +1 -1
  22. package/dist/job_context.mjs.map +1 -1
  23. package/dist/library.mjs.map +1 -1
  24. package/dist/longpoll_broker.mjs.map +1 -1
  25. package/dist/longpoll_options.mjs.map +1 -1
  26. package/dist/longpoll_session.mjs.map +1 -1
  27. package/dist/middleware.mjs.map +1 -1
  28. package/dist/module_loader.mjs.map +1 -1
  29. package/dist/options.mjs.map +1 -1
  30. package/dist/origin.mjs.map +1 -1
  31. package/dist/policy.mjs.map +1 -1
  32. package/dist/postgres_adapter.mjs.map +1 -1
  33. package/dist/postgres_worker.mjs.map +1 -1
  34. package/dist/queue_provider.mjs.map +1 -1
  35. package/dist/request_identity.mjs.map +1 -1
  36. package/dist/response.mjs.map +1 -1
  37. package/dist/route_info.mjs.map +1 -1
  38. package/dist/route_pattern.mjs.map +1 -1
  39. package/dist/routes.mjs.map +1 -1
  40. package/dist/runtime.mjs.map +1 -1
  41. package/dist/server.mjs.map +1 -1
  42. package/dist/server_context.mjs.map +1 -1
  43. package/dist/sqlite_adapter.mjs.map +1 -1
  44. package/dist/static_files.mjs.map +1 -1
  45. package/dist/token.mjs.map +1 -1
  46. package/dist/tokens.mjs.map +1 -1
  47. package/dist/trace.mjs.map +1 -1
  48. package/dist/worker.mjs.map +1 -1
  49. package/examples/security/package.json +1 -1
  50. package/package.json +6 -4
  51. package/dist/cli/.lango/bignumber.mjs +0 -3119
  52. package/dist/cli/.lango/localization.mjs +0 -108
  53. package/dist/cli/.lango/runtime.mjs +0 -725
  54. package/dist/cli/.lango/vendor/i18next.LICENSE +0 -21
  55. package/dist/cli/.lango/vendor/i18next.mjs +0 -2434
  56. package/dist/cli/.lango/xmldom/conventions.js +0 -429
  57. package/dist/cli/.lango/xmldom/dom-parser.js +0 -591
  58. package/dist/cli/.lango/xmldom/dom.js +0 -3759
  59. package/dist/cli/.lango/xmldom/entities.js +0 -2171
  60. package/dist/cli/.lango/xmldom/errors.js +0 -205
  61. package/dist/cli/.lango/xmldom/grammar.js +0 -559
  62. package/dist/cli/.lango/xmldom/index.js +0 -41
  63. package/dist/cli/.lango/xmldom/package.json +0 -1
  64. package/dist/cli/.lango/xmldom/sax.js +0 -983
  65. package/dist/cli/.lango/xmldom.LICENSE.md +0 -8
  66. package/dist/cli/body_reader.mjs +0 -180
  67. package/dist/cli/body_reader.mjs.map +0 -1
  68. package/dist/cli/client_identity.mjs +0 -250
  69. package/dist/cli/client_identity.mjs.map +0 -1
  70. package/dist/cli/database.mjs +0 -116
  71. package/dist/cli/database.mjs.map +0 -1
  72. package/dist/cli/database_options.mjs +0 -83
  73. package/dist/cli/database_options.mjs.map +0 -1
  74. package/dist/cli/database_scope.mjs +0 -93
  75. package/dist/cli/database_scope.mjs.map +0 -1
  76. package/dist/cli/endpoint.mjs +0 -50
  77. package/dist/cli/endpoint.mjs.map +0 -1
  78. package/dist/cli/error_details.mjs +0 -45
  79. package/dist/cli/error_details.mjs.map +0 -1
  80. package/dist/cli/longpoll_broker.mjs +0 -215
  81. package/dist/cli/longpoll_broker.mjs.map +0 -1
  82. package/dist/cli/longpoll_options.mjs +0 -103
  83. package/dist/cli/longpoll_options.mjs.map +0 -1
  84. package/dist/cli/longpoll_session.mjs +0 -136
  85. package/dist/cli/longpoll_session.mjs.map +0 -1
  86. package/dist/cli/middleware.mjs +0 -25
  87. package/dist/cli/middleware.mjs.map +0 -1
  88. package/dist/cli/options.mjs +0 -214
  89. package/dist/cli/options.mjs.map +0 -1
  90. package/dist/cli/origin.mjs +0 -87
  91. package/dist/cli/origin.mjs.map +0 -1
  92. package/dist/cli/policy.mjs +0 -121
  93. package/dist/cli/policy.mjs.map +0 -1
  94. package/dist/cli/postgres_adapter.mjs +0 -178
  95. package/dist/cli/postgres_adapter.mjs.map +0 -1
  96. package/dist/cli/route_pattern.mjs +0 -129
  97. package/dist/cli/route_pattern.mjs.map +0 -1
  98. package/dist/cli/routes.mjs +0 -360
  99. package/dist/cli/routes.mjs.map +0 -1
  100. package/dist/cli/sqlite_adapter.mjs +0 -163
  101. package/dist/cli/sqlite_adapter.mjs.map +0 -1
  102. package/dist/cli/static_files.mjs +0 -224
  103. package/dist/cli/static_files.mjs.map +0 -1
  104. package/dist/cli/trace.mjs +0 -53
  105. package/dist/cli/trace.mjs.map +0 -1
@@ -1,842 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { resolvePolicies } from "./policy.mjs";
3
- import { trace, responseLog } from "./trace.mjs";
4
- import { LongpollBroker } from "./longpoll_broker.mjs";
5
- import { LongpollSession } from "./longpoll_session.mjs";
6
- import { prepareDatabase } from "./database.mjs";
7
- import { errorDetails } from "./error_details.mjs";
8
- import { deployment } from "./options.mjs";
9
- import { Routes } from "./routes.mjs";
10
- import { BodyReader } from "./body_reader.mjs";
11
- import { StaticFiles } from "./static_files.mjs";
12
- import * as http from "node:http";
13
- import * as path from "node:path";
14
- import * as modules from "node:module";
15
- import * as crypto from "node:crypto";
16
- import * as piscina from "piscina";
17
- import {
18
- hostGlobal as __hostGlobal,
19
- hostGlobalCall as __hostGlobalCall,
20
- contextGet as __contextGet,
21
- contextSet as __contextSet,
22
- contextRestore as __contextRestore,
23
- bindContexts as __bindContexts,
24
- fromJson as __fromJson,
25
- toJson as __toJson,
26
- isNumber as __isNumber,
27
- isString as __isString,
28
- isBool as __isBool,
29
- isObject as __isObject,
30
- isArray as __isArray,
31
- includes as __includes,
32
- entries as __entries,
33
- range as __range,
34
- add as __add,
35
- requireBoolean as __requireBoolean,
36
- normalize as __normalize,
37
- finite as __finite,
38
- numericAdd as __numericAdd,
39
- call as __call,
40
- boundary as __boundary,
41
- requireArity as __requireArity,
42
- withArity as __withArity,
43
- } from "./.lango/runtime.mjs";
44
-
45
- export class Server {
46
- #definition;
47
- #broker;
48
- #polls;
49
- #state;
50
- #connections;
51
- #server;
52
- #pool;
53
- #starting;
54
- #closing;
55
- #waiting;
56
- #active;
57
- #tasks;
58
- #ready;
59
- #readyIds;
60
- #destroying;
61
- #static;
62
- #lango;
63
- #shutdownDeadline;
64
- constructor(path, definition = null) {
65
- __requireArity(arguments.length, [0], "constructor");
66
- path = __boundary(path);
67
- definition = __boundary(definition);
68
- if (__requireBoolean(path !== null)) {
69
- let directory = path;
70
- let routes = new Routes(directory);
71
- __normalize(routes.xml(pathJoin(directory, "routes.xml")));
72
- definition = { settings: deployment(directory), routes: __normalize(routes.definitions()), jobs: __normalize(routes.jobs()), events: __normalize(routes.events()), middlewares: __normalize(routes.middlewares()) };
73
- }
74
- if (__requireBoolean(definition === null)) {
75
- throw "Use Server(directory) or Builder.build()";
76
- }
77
- this.#definition = __fromJson(__toJson(definition));
78
- let settings = __normalize(this.#definition.settings);
79
- resolvePolicies(__normalize(this.#definition.routes), __normalize(settings.policies));
80
- if (__requireBoolean(__normalize(this.#definition.jobs) !== null)) {
81
- resolvePolicies(__normalize(this.#definition.jobs), __normalize(settings.policies));
82
- }
83
- this.#broker = new LongpollBroker(__normalize(this.#definition.settings), __normalize(this.#definition.routes));
84
- this.#polls = __normalize(__hostGlobal(["Object"]).create(null));
85
- this.#state = "new";
86
- this.#connections = [];
87
- this.#server = null;
88
- this.#pool = null;
89
- this.#starting = null;
90
- this.#closing = null;
91
- this.#waiting = [];
92
- this.#active = 0;
93
- this.#tasks = __normalize(__hostGlobal(["Object"]).create(null));
94
- this.#ready = __normalize(__hostGlobal(["Promise"]).withResolvers());
95
- this.#readyIds = [];
96
- this.#destroying = false;
97
- this.#static = null;
98
- }
99
- publish(path, key, data) {
100
- __requireArity(arguments.length, [0, 1, 2], "publish");
101
- path = __boundary(path);
102
- key = __boundary(key);
103
- data = __boundary(data);
104
- if (__requireBoolean(__normalize(this.#state) !== "running")) {
105
- return __normalize(__hostGlobal(["Promise"]).reject("Server is not running"));
106
- }
107
- return __normalize(this.#broker.publish(path, key, data));
108
- return null;
109
- }
110
- cursor(path, key) {
111
- __requireArity(arguments.length, [0, 1], "cursor");
112
- path = __boundary(path);
113
- key = __boundary(key);
114
- if (__requireBoolean(__normalize(this.#state) !== "running")) {
115
- return __normalize(__hostGlobal(["Promise"]).reject("Server is not running"));
116
- }
117
- return __normalize(this.#broker.cursor(path, key));
118
- return null;
119
- }
120
- start() {
121
- if (__requireBoolean(__normalize(this.#state) !== "new")) {
122
- return __normalize(__hostGlobal(["Promise"]).reject("Server can only be started once"));
123
- }
124
- this.#state = "starting";
125
- this.#starting = this.#launch();
126
- return __normalize(this.#starting);
127
- return null;
128
- }
129
- #launch() {
130
- let settings = __normalize(this.#definition.settings);
131
- trace(`Server starting: ${__normalize(settings.root)}; workers=${__normalize(settings.workers)}`);
132
- if (__requireBoolean(__normalize(settings.static) !== null)) {
133
- try {
134
- this.#static = new StaticFiles(__normalize(settings.static));
135
- } catch (error) {
136
- this.#state = "closed";
137
- return __normalize(__hostGlobal(["Promise"]).reject(error));
138
- }
139
- }
140
- return __normalize(this.#broker.open()).then(__withArity(__bindContexts((ignored) => {
141
- ignored = __boundary(ignored);
142
- return prepareDatabase(__normalize(settings.database), __normalize(settings.root), __normalize(settings.client));
143
- return null;
144
- }), [0], "closure")).then(__withArity(__bindContexts((ignored) => {
145
- ignored = __boundary(ignored);
146
- let resolver = __normalize(modules.createRequire(__normalize(path.join(__normalize(settings.root), "package.json"))));
147
- let entry = __normalize(resolver.resolve("@lango-project/lango-server"));
148
- this.#pool = new piscina.Piscina({ filename: __normalize(path.join(__normalize(path.dirname(entry)), "worker.mjs")), name: "execute", minThreads: __normalize(settings.workers), maxThreads: __normalize(settings.workers), maxQueue: __normalize(settings.maxQueue), concurrentTasksPerWorker: 1, closeTimeout: __normalize(settings.shutdownTimeoutMs), workerData: __normalize(this.#definition) });
149
- let pool = __normalize(this.#pool);
150
- __normalize(pool.on("message", __withArity(__bindContexts((message) => {
151
- message = __boundary(message);
152
- this.#messageReceived(message);
153
- return null;
154
- }), [0], "closure")));
155
- __normalize(pool.on("error", __withArity(__bindContexts((error) => {
156
- const __contextScope = [];
157
- try {
158
- error = __boundary(error);
159
- __normalize(this.#ready.reject(error));
160
- __normalize(__contextGet("log").err(`Worker pool error: ${errorDetails(error)}`));
161
- return null;
162
- } finally {
163
- __contextRestore(__contextScope);
164
- }
165
- }), [0], "closure")));
166
- return startupDeadline(__normalize(this.#ready.promise), __normalize(settings.startupTimeoutMs));
167
- return null;
168
- }), [0], "closure")).then(__withArity(__bindContexts((ignored) => {
169
- ignored = __boundary(ignored);
170
- if (__requireBoolean(__normalize(this.#state) !== "starting")) {
171
- throw "Server closed during startup";
172
- }
173
- let server = new http.Server(__withArity(__bindContexts((req, res) => {
174
- req = __boundary(req);
175
- res = __boundary(res);
176
- this.#receive(req, res);
177
- return null;
178
- }), [0, 1], "closure"));
179
- this.#server = server;
180
- __normalize(server.on("connection", __withArity(__bindContexts((socket) => {
181
- socket = __boundary(socket);
182
- this.#connected(socket);
183
- return null;
184
- }), [0], "closure")));
185
- server.headersTimeout = __normalize(settings.bodyTimeoutMs);
186
- server.requestTimeout = __normalize(settings.bodyTimeoutMs);
187
- let listening = new (__hostGlobal(["Promise"]))(__withArity(__bindContexts((resolve, reject) => {
188
- resolve = __boundary(resolve);
189
- reject = __boundary(reject);
190
- __normalize(server.once("error", reject));
191
- __normalize(server.listen(__normalize(settings.port), __normalize(settings.host), __bindContexts(() => {
192
- __normalize(server.removeListener("error", reject));
193
- if (__requireBoolean(__normalize(this.#state) !== "starting")) {
194
- __call(reject, "Server closed during startup");
195
- return null;
196
- }
197
- this.#state = "running";
198
- let address = __normalize(server.address());
199
- __call(resolve, { host: __normalize(address.address), port: __normalize(address.port) });
200
- return null;
201
- })));
202
- return null;
203
- }), [0, 1], "closure"));
204
- return listening;
205
- return null;
206
- }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
207
- error = __boundary(error);
208
- __normalize(this.#broker.close());
209
- this.#state = "closed";
210
- return this.#destroyPool().then(__withArity(__bindContexts((ignored) => {
211
- ignored = __boundary(ignored);
212
- throw error;
213
- return null;
214
- }), [0], "closure"));
215
- return null;
216
- }), [0], "closure"));
217
- return null;
218
- }
219
- #messageReceived(message) {
220
- __requireArity(arguments.length, [0], "messageReceived");
221
- message = __boundary(message);
222
- if (__requireBoolean(__normalize(message.kind) === "longpoll")) {
223
- this.#brokerMessage(message);
224
- return null;
225
- }
226
- if (__requireBoolean(__normalize(message.kind) === "ready")) {
227
- if (__requireBoolean(!__requireBoolean(__normalize(this.#readyIds.includes(__normalize(message.threadId)))))) {
228
- __add(this.#readyIds, __normalize(message.threadId));
229
- }
230
- if (__requireBoolean(__normalize(this.#readyIds.length) >= __normalize(this.#definition.settings.workers))) {
231
- __normalize(this.#ready.resolve(null));
232
- }
233
- return null;
234
- }
235
- if (__requireBoolean(!__requireBoolean(__includes(__normalize(message.id), __normalize(this.#tasks))))) {
236
- return null;
237
- }
238
- let record = __normalize(this.#tasks[__normalize(message.id)]);
239
- if (__requireBoolean(__normalize(message.kind) === "prepared")) {
240
- record.result = __normalize(message.result);
241
- record.logIdentity = __normalize(message.logIdentity);
242
- this.#resetDeadline(record, __normalize(this.#definition.settings.eventTimeoutMs));
243
- }
244
- if (__requireBoolean(__normalize(message.kind) === "event")) {
245
- this.#resetDeadline(record, __normalize(this.#definition.settings.eventTimeoutMs));
246
- }
247
- if (__requireBoolean(__requireBoolean(__normalize(message.kind) === "handler") && __requireBoolean(__normalize(record.result) === null))) {
248
- this.#resetDeadline(record, __finite(__normalize(record.deadline) - __normalize(__hostGlobal(["Date"]).now())));
249
- }
250
- return null;
251
- return null;
252
- }
253
- #resetDeadline(record, duration) {
254
- __requireArity(arguments.length, [0, 1], "resetDeadline");
255
- record = __boundary(record);
256
- duration = __boundary(duration);
257
- __hostGlobalCall(["clearTimeout"], __normalize(record.timer));
258
- if (__requireBoolean(__normalize(record.result) === null)) {
259
- duration = __normalize(__hostGlobal(["Math"]).min(duration, __finite(__normalize(record.deadline) - __normalize(__hostGlobal(["Date"]).now()))));
260
- }
261
- let expired = __bindContexts(() => {
262
- this.#expire(record);
263
- return null;
264
- });
265
- record.timer = __hostGlobalCall(["setTimeout"], expired, __normalize(__hostGlobal(["Math"]).max(1, duration)));
266
- return null;
267
- return null;
268
- }
269
- #connected(socket) {
270
- __requireArity(arguments.length, [0], "connected");
271
- socket = __boundary(socket);
272
- let record = { socket: socket, active: 0 };
273
- __add(this.#connections, record);
274
- __normalize(socket.once("close", __bindContexts(() => {
275
- let index = __normalize(this.#connections.indexOf(record));
276
- if (__requireBoolean(index >= 0)) {
277
- __normalize(this.#connections.splice(index, 1));
278
- }
279
- return null;
280
- })));
281
- return null;
282
- return null;
283
- }
284
- #trackResponse(req, res) {
285
- __requireArity(arguments.length, [0, 1], "trackResponse");
286
- req = __boundary(req);
287
- res = __boundary(res);
288
- let target = __normalize(__normalize(req.url.split("?"))[0]);
289
- for (const record of __normalize(this.#connections)) {
290
- if (__requireBoolean(__normalize(record.socket) === __normalize(req.socket))) {
291
- record.active = __numericAdd(__normalize(record.active), 1);
292
- let state = { done: false };
293
- let complete = __bindContexts(() => {
294
- if (__requireBoolean(__normalize(state.done))) {
295
- return null;
296
- }
297
- state.done = true;
298
- if (__requireBoolean(__normalize(res.writableFinished))) {
299
- responseLog(__normalize(res.langoRequestId), __normalize(req.method), target, __normalize(res.statusCode));
300
- } else {
301
- trace(`HTTP ${__normalize(req.method)} ${target} connection closed before response completed`);
302
- }
303
- record.active = __finite(__normalize(record.active) - 1);
304
- if (__requireBoolean(__requireBoolean(__normalize(this.#state) === "closing") && __requireBoolean(__normalize(record.active) === 0))) {
305
- __normalize(record.socket.end());
306
- }
307
- return null;
308
- return null;
309
- });
310
- __normalize(res.once("finish", complete));
311
- __normalize(res.once("close", complete));
312
- return null;
313
- }
314
- }
315
- return null;
316
- return null;
317
- }
318
- #receive(req, res) {
319
- __requireArity(arguments.length, [0, 1], "receive");
320
- req = __boundary(req);
321
- res = __boundary(res);
322
- this.#trackResponse(req, res);
323
- __normalize(req.on("error", __withArity(__bindContexts((error) => {
324
- error = __boundary(error);
325
- return null;
326
- return null;
327
- }), [0], "closure")));
328
- if (__requireBoolean(__normalize(this.#state) !== "running")) {
329
- return rejectHttp(req, res, 503, "Unavailable");
330
- }
331
- trace(`HTTP ${__normalize(req.method)} ${__normalize(__normalize(req.url.split("?"))[0])}`);
332
- if (__requireBoolean(__requireBoolean(__normalize(this.#static) !== null) && __requireBoolean(__requireBoolean(__normalize(req.method) === "GET") || __requireBoolean(__normalize(req.method) === "HEAD")))) {
333
- let failed = __withArity(__bindContexts((status, code) => {
334
- status = __boundary(status);
335
- code = __boundary(code);
336
- this.#send(res, failure(status, code));
337
- return null;
338
- }), [0, 1], "closure");
339
- return __normalize(this.#static.receive(req, res, failed));
340
- }
341
- if (__requireBoolean(__normalize(req.method) !== "POST")) {
342
- let allowed = "POST";
343
- if (__requireBoolean(__normalize(this.#static) !== null)) {
344
- allowed = "GET, HEAD, POST";
345
- }
346
- __normalize(res.setHeader("Allow", allowed));
347
- return rejectHttp(req, res, 405, "MethodNotAllowed");
348
- }
349
- if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(req.url.includes("?"))) || __requireBoolean(__normalize(req.url.includes("#")))) || __requireBoolean(__normalize(req.url.includes("\\"))))) {
350
- return rejectHttp(req, res, 400, "InvalidPath");
351
- }
352
- let type = req.headers["content-type"];
353
- let media = "";
354
- if (__requireBoolean(__isString(type))) {
355
- let parts = __normalize(type.split(";"));
356
- media = __normalize(__normalize(parts[0]).trim());
357
- }
358
- if (__requireBoolean(__normalize(media.toLowerCase()) !== "application/json")) {
359
- return rejectHttp(req, res, 415, "JsonRequired");
360
- }
361
- let settings = __normalize(this.#definition.settings);
362
- if (__requireBoolean(__requireBoolean(__normalize(this.#active) >= __normalize(settings.workers)) && __requireBoolean(__normalize(this.#waiting.length) >= __normalize(settings.maxQueue)))) {
363
- return rejectHttp(req, res, 503, "QueueFull");
364
- }
365
- let complete = __withArity(__bindContexts((body) => {
366
- body = __boundary(body);
367
- this.#submit(req, res, body);
368
- return null;
369
- }), [0], "closure");
370
- let failed = __withArity(__bindContexts((status, code) => {
371
- status = __boundary(status);
372
- code = __boundary(code);
373
- this.#send(res, failure(status, code));
374
- return null;
375
- }), [0, 1], "closure");
376
- let reader = new BodyReader(req, res, settings, complete, failed);
377
- __normalize(reader.start());
378
- return null;
379
- return null;
380
- }
381
- #submit(req, res, body) {
382
- __requireArity(arguments.length, [0, 1, 2], "submit");
383
- req = __boundary(req);
384
- res = __boundary(res);
385
- body = __boundary(body);
386
- let pending = null;
387
- let route = __normalize(this.#broker.route(__normalize(req.url)));
388
- if (__requireBoolean(route === null)) {
389
- pending = this.#dispatch(req, res, body);
390
- } else {
391
- pending = this.#longpoll(req, res, body, route);
392
- }
393
- return pending.then(__withArity(__bindContexts((result) => {
394
- result = __boundary(result);
395
- this.#send(res, result);
396
- return null;
397
- return null;
398
- }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
399
- const __contextScope = [];
400
- try {
401
- error = __boundary(error);
402
- __normalize(__contextGet("log").err(`HTTP ${__normalize(req.method)} ${__normalize(__normalize(req.url.split("?"))[0])} request failed: ${errorDetails(error)}`));
403
- this.#send(res, failure(500, "InternalServerError"));
404
- return null;
405
- return null;
406
- } finally {
407
- __contextRestore(__contextScope);
408
- }
409
- }), [0], "closure"));
410
- return null;
411
- }
412
- #longpoll(req, res, body, route) {
413
- __requireArity(arguments.length, [0, 1, 2, 3], "longpoll");
414
- req = __boundary(req);
415
- res = __boundary(res);
416
- body = __boundary(body);
417
- route = __boundary(route);
418
- if (__requireBoolean(__normalize(__normalize(__hostGlobal(["Object"]).keys(__normalize(this.#polls))).length) >= __normalize(this.#definition.settings.redis.maxPendingPolls))) {
419
- return __normalize(__hostGlobal(["Promise"]).resolve(failure(503, "PollLimit")));
420
- }
421
- let authorize = __withArity(__bindContexts((token, result) => {
422
- token = __boundary(token);
423
- result = __boundary(result);
424
- return this.#dispatch(req, res, body, true, token, result);
425
- return null;
426
- }), [0, 1], "closure");
427
- let session = new LongpollSession(__normalize(this.#broker), route, authorize, body);
428
- let id = __normalize(crypto.randomUUID());
429
- this.#polls[id] = session;
430
- let disconnected = __bindContexts(() => {
431
- __normalize(session.cancel());
432
- return null;
433
- });
434
- __normalize(res.once("close", disconnected));
435
- return __normalize(session.run()).finally(__bindContexts(() => {
436
- __normalize(res.removeListener("close", disconnected));
437
- __normalize(__hostGlobal(["Reflect"]).deleteProperty(__normalize(this.#polls), id));
438
- return null;
439
- }));
440
- return null;
441
- }
442
- #brokerMessage(message) {
443
- __requireArity(arguments.length, [0], "brokerMessage");
444
- message = __boundary(message);
445
- let port = __normalize(message.port);
446
- let pending = null;
447
- try {
448
- if (__normalize(message.operation) === "publish") {
449
- pending = this.publish(__normalize(message.path), __normalize(message.key), __normalize(message.data));
450
- } else if (__normalize(message.operation) === "cursor") {
451
- pending = this.cursor(__normalize(message.path), __normalize(message.key));
452
- } else {
453
- pending = __normalize(__hostGlobal(["Promise"]).reject("Unknown longpoll operation"));
454
- }
455
- } catch (error) {
456
- pending = __normalize(__hostGlobal(["Promise"]).reject(error));
457
- }
458
- return pending.then(__withArity(__bindContexts((value) => {
459
- value = __boundary(value);
460
- brokerReply(port, { ok: true, value: value });
461
- return null;
462
- }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
463
- error = __boundary(error);
464
- brokerReply(port, { ok: false });
465
- return null;
466
- }), [0], "closure")).finally(__bindContexts(() => {
467
- __normalize(port.close());
468
- return null;
469
- }));
470
- return null;
471
- }
472
- #dispatch(req, res, body, authorize = false, token = null, pollResult = null) {
473
- __requireArity(arguments.length, [0, 1, 2], "dispatch");
474
- req = __boundary(req);
475
- res = __boundary(res);
476
- body = __boundary(body);
477
- authorize = __boundary(authorize);
478
- token = __boundary(token);
479
- pollResult = __boundary(pollResult);
480
- let settings = __normalize(this.#definition.settings);
481
- if (__requireBoolean(__requireBoolean(__normalize(this.#state) !== "running") || __requireBoolean(__requireBoolean(__normalize(this.#active) >= __normalize(settings.workers)) && __requireBoolean(__normalize(this.#waiting.length) >= __normalize(settings.maxQueue))))) {
482
- return __normalize(__hostGlobal(["Promise"]).resolve(failure(503, "Unavailable")));
483
- }
484
- let id = __normalize(crypto.randomUUID());
485
- res.langoRequestId = id;
486
- trace(`[${id}] Queued request ${__normalize(req.method)} ${__normalize(req.url)}`);
487
- 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 };
488
- if (__requireBoolean(token !== null)) {
489
- record.task.request.headers.authorization = `Bearer ${token}`;
490
- }
491
- this.#tasks[id] = record;
492
- this.#resetDeadline(record, __normalize(settings.requestTimeoutMs));
493
- __add(this.#waiting, record);
494
- let disconnected = __bindContexts(() => {
495
- if (__requireBoolean(!__requireBoolean(__normalize(res.writableEnded)))) {
496
- this.#cancel(record);
497
- }
498
- return null;
499
- });
500
- __normalize(res.once("close", disconnected));
501
- this.#pump();
502
- return record.completed.promise.catch(__withArity(__bindContexts((error) => {
503
- error = __boundary(error);
504
- if (__requireBoolean(__normalize(record.expired))) {
505
- return failure(504, "RequestTimeout");
506
- }
507
- return failure(500, "InternalServerError");
508
- return null;
509
- }), [0], "closure")).finally(__bindContexts(() => {
510
- __normalize(res.removeListener("close", disconnected));
511
- return null;
512
- }));
513
- return null;
514
- }
515
- #expire(record) {
516
- __requireArity(arguments.length, [0], "expire");
517
- record = __boundary(record);
518
- record.expired = true;
519
- this.#cancel(record);
520
- return null;
521
- return null;
522
- }
523
- #cancel(record) {
524
- __requireArity(arguments.length, [0], "cancel");
525
- record = __boundary(record);
526
- if (__requireBoolean(!__requireBoolean(__includes(__normalize(record.id), __normalize(this.#tasks))))) {
527
- return null;
528
- }
529
- if (__requireBoolean(__normalize(record.started))) {
530
- __normalize(record.controller.abort());
531
- } else {
532
- let index = __normalize(this.#waiting.indexOf(record));
533
- if (__requireBoolean(index >= 0)) {
534
- __normalize(this.#waiting.splice(index, 1));
535
- }
536
- this.#finish(record, null, "Request cancelled");
537
- }
538
- return null;
539
- return null;
540
- }
541
- #pump() {
542
- __loop1: while (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(this.#destroying))) && __requireBoolean(__normalize(this.#waiting.length) > 0)) && __requireBoolean(__normalize(this.#active) < __normalize(this.#definition.settings.workers)))) {
543
- let record = __normalize(this.#waiting.shift());
544
- record.started = true;
545
- this.#active = __numericAdd(__normalize(this.#active), 1);
546
- trace(`[${__normalize(record.id)}] Dispatching to worker`);
547
- let pending = __normalize(this.#pool.run(__normalize(record.task), { signal: record.controller.signal }));
548
- this.#settle(record, pending);
549
- }
550
- return null;
551
- return null;
552
- }
553
- #settle(record, pending) {
554
- __requireArity(arguments.length, [0, 1], "settle");
555
- record = __boundary(record);
556
- pending = __boundary(pending);
557
- return pending.then(__withArity(__bindContexts((result) => {
558
- result = __boundary(result);
559
- this.#finish(record, result, null);
560
- return null;
561
- return null;
562
- }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
563
- const __contextScope = [];
564
- try {
565
- error = __boundary(error);
566
- if (__requireBoolean(__normalize(record.result) !== null)) {
567
- __normalize(__contextGet("log").err(`${__normalize(record.logIdentity)} Request event interrupted; preserving prepared result`));
568
- }
569
- this.#finish(record, __normalize(record.result), error);
570
- return null;
571
- return null;
572
- } finally {
573
- __contextRestore(__contextScope);
574
- }
575
- }), [0], "closure")).finally(__bindContexts(() => {
576
- this.#active = __finite(__normalize(this.#active) - 1);
577
- this.#pump();
578
- return null;
579
- }));
580
- return null;
581
- }
582
- #finish(record, result, error) {
583
- __requireArity(arguments.length, [0, 1, 2], "finish");
584
- record = __boundary(record);
585
- result = __boundary(result);
586
- error = __boundary(error);
587
- __hostGlobalCall(["clearTimeout"], __normalize(record.timer));
588
- __normalize(__hostGlobal(["Reflect"]).deleteProperty(__normalize(this.#tasks), __normalize(record.id)));
589
- if (__requireBoolean(result !== null)) {
590
- __normalize(record.completed.resolve(result));
591
- } else {
592
- __normalize(record.completed.reject(error));
593
- }
594
- return null;
595
- return null;
596
- }
597
- close() {
598
- if (__requireBoolean(__normalize(this.#closing) !== null)) {
599
- return __normalize(this.#closing);
600
- }
601
- let previous = __normalize(this.#state);
602
- this.#state = "closing";
603
- this.#shutdownDeadline = __numericAdd(__normalize(__hostGlobal(["Date"]).now()), __normalize(this.#definition.settings.shutdownTimeoutMs));
604
- if (__requireBoolean(__requireBoolean(previous === "new") || __requireBoolean(previous === "closed"))) {
605
- this.#state = "closed";
606
- this.#closing = __normalize(__hostGlobal(["Promise"]).resolve(null));
607
- return __normalize(this.#closing);
608
- }
609
- __normalize(this.#ready.reject("Server closed during startup"));
610
- this.#closing = this.#stop();
611
- return __normalize(this.#closing);
612
- return null;
613
- }
614
- #stop() {
615
- for (const record of __normalize(this.#connections)) {
616
- if (__requireBoolean(__normalize(record.active) === 0)) {
617
- __normalize(record.socket.destroy());
618
- }
619
- }
620
- for (const [id, session] of __entries(__normalize(this.#polls))) {
621
- __normalize(session.cancel());
622
- }
623
- let drained = new (__hostGlobal(["Promise"]))(__withArity(__bindContexts((resolve) => {
624
- resolve = __boundary(resolve);
625
- let server = __normalize(this.#server);
626
- if (__requireBoolean(__requireBoolean(server === null) || __requireBoolean(!__requireBoolean(__normalize(server.listening))))) {
627
- __call(resolve, null);
628
- } else {
629
- server.close(__bindContexts(() => {
630
- __call(resolve, null);
631
- return null;
632
- }));
633
- }
634
- return null;
635
- }), [0], "closure"));
636
- let expired = __normalize(__hostGlobal(["Promise"]).withResolvers());
637
- let force = __bindContexts(() => {
638
- this.#destroying = true;
639
- for (const record of __normalize(this.#waiting)) {
640
- this.#finish(record, null, "Server closed");
641
- }
642
- this.#waiting = [];
643
- if (__requireBoolean(__normalize(this.#server) !== null)) {
644
- __normalize(this.#server.closeAllConnections());
645
- }
646
- __normalize(expired.reject("Server shutdown timed out"));
647
- return null;
648
- });
649
- let timer = __hostGlobalCall(["setTimeout"], force, __normalize(this.#definition.settings.shutdownTimeoutMs));
650
- return __normalize(__hostGlobal(["Promise"]).race([drained, __normalize(expired.promise)])).finally(__bindContexts(() => {
651
- __hostGlobalCall(["clearTimeout"], timer);
652
- return this.#destroyPool();
653
- return null;
654
- })).finally(__bindContexts(() => {
655
- __normalize(this.#broker.close());
656
- this.#state = "closed";
657
- return null;
658
- }));
659
- return null;
660
- }
661
- #destroyPool() {
662
- this.#destroying = true;
663
- if (__requireBoolean(__normalize(this.#pool) === null)) {
664
- return __normalize(__hostGlobal(["Promise"]).resolve(null));
665
- }
666
- let pool = __normalize(this.#pool);
667
- let pending = __normalize(__hostGlobal(["Promise"]).resolve(null));
668
- if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(this.#definition.settings.database) !== null) && __requireBoolean(__normalize(this.#state) === "closing")) && __requireBoolean(__normalize(this.#active) === 0))) {
669
- let remaining = __finite(__normalize(this.#shutdownDeadline) - __normalize(__hostGlobal(["Date"]).now()));
670
- if (__requireBoolean(remaining > 0)) {
671
- let tasks = [];
672
- for (const index of __range(0, __normalize(this.#definition.settings.workers))) {
673
- tasks.push(__normalize(pool.run({ close: true })));
674
- }
675
- pending = startupDeadline(__normalize(__hostGlobal(["Promise"]).all(tasks)), remaining);
676
- }
677
- }
678
- return pending.finally(__bindContexts(() => {
679
- return __normalize(pool.destroy());
680
- return null;
681
- }));
682
- return null;
683
- }
684
- #send(res, result) {
685
- __requireArity(arguments.length, [0, 1], "send");
686
- res = __boundary(res);
687
- result = __boundary(result);
688
- trace(`HTTP response status=${__normalize(result.status)}`);
689
- if (__requireBoolean(__normalize(this.#state) === "closing")) {
690
- result.headers.connection = "close";
691
- }
692
- return write(res, result);
693
- return null;
694
- }
695
- }
696
- function pathJoin(directory, file) {
697
- __requireArity(arguments.length, [0, 1], "pathJoin");
698
- directory = __boundary(directory);
699
- file = __boundary(file);
700
- return __normalize(path.join(directory, file));
701
- return null;
702
- }
703
-
704
- function startupDeadline(pending, timeout) {
705
- __requireArity(arguments.length, [0, 1], "startupDeadline");
706
- pending = __boundary(pending);
707
- timeout = __boundary(timeout);
708
- let expired = __normalize(__hostGlobal(["Promise"]).withResolvers());
709
- let expire = __bindContexts(() => {
710
- __normalize(expired.reject("Worker startup timed out"));
711
- return null;
712
- });
713
- let timer = __hostGlobalCall(["setTimeout"], expire, timeout);
714
- return __normalize(__hostGlobal(["Promise"]).race([pending, __normalize(expired.promise)])).finally(__bindContexts(() => {
715
- __hostGlobalCall(["clearTimeout"], timer);
716
- return null;
717
- }));
718
- return null;
719
- }
720
-
721
- function failure(status, code) {
722
- __requireArity(arguments.length, [0, 1], "failure");
723
- status = __boundary(status);
724
- code = __boundary(code);
725
- return { status: status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }, body: __toJson({ error: code }) };
726
- return null;
727
- }
728
-
729
- function write(res, result) {
730
- const __contextScope = [];
731
- try {
732
- __requireArity(arguments.length, [0, 1], "write");
733
- res = __boundary(res);
734
- result = __boundary(result);
735
- if (__requireBoolean(__requireBoolean(__normalize(res.destroyed)) || __requireBoolean(__normalize(res.writableEnded)))) {
736
- return null;
737
- }
738
- try {
739
- __normalize(res.writeHead(__normalize(result.status), __normalize(result.headers)));
740
- __normalize(res.end(__normalize(result.body)));
741
- } catch (error) {
742
- __normalize(__contextGet("log").err(`[${__normalize(res.langoRequestId)}] Response write failed: ${errorDetails(error)}`));
743
- __normalize(res.destroy());
744
- }
745
- return null;
746
- return null;
747
- } finally {
748
- __contextRestore(__contextScope);
749
- }
750
- }
751
-
752
- function rejectHttp(req, res, status, code) {
753
- __requireArity(arguments.length, [0, 1, 2, 3], "rejectHttp");
754
- req = __boundary(req);
755
- res = __boundary(res);
756
- status = __boundary(status);
757
- code = __boundary(code);
758
- __normalize(res.setHeader("Connection", "close"));
759
- __normalize(res.once("finish", __bindContexts(() => {
760
- __normalize(req.destroy());
761
- return null;
762
- })));
763
- __normalize(req.resume());
764
- return write(res, failure(status, code));
765
- return null;
766
- }
767
-
768
- export function main(args) {
769
- __requireArity(arguments.length, [0], "main");
770
- args = __boundary(args);
771
- let directory = null;
772
- let verbose = false;
773
- for (const arg of args) {
774
- if (__requireBoolean(arg === "--verbose")) {
775
- verbose = true;
776
- } else {
777
- if (__requireBoolean(__requireBoolean(__normalize(arg.startsWith("--"))) || __requireBoolean(directory !== null))) {
778
- throw "Usage: lango-server <application-directory> [--verbose]";
779
- }
780
- directory = arg;
781
- }
782
- }
783
- if (__requireBoolean(directory === null)) {
784
- throw "Usage: lango-server <application-directory> [--verbose]";
785
- }
786
- if (__requireBoolean(verbose)) {
787
- __hostGlobal(["process"]).env.LANGO_VERBOSE = "1";
788
- }
789
- trace(`Loading server configuration: ${directory}`);
790
- let server = new Server(directory);
791
- let stop = __bindContexts(() => {
792
- return __normalize(server.close()).catch(__withArity(__bindContexts((error) => {
793
- const __contextScope = [];
794
- try {
795
- error = __boundary(error);
796
- __normalize(__contextGet("log").err("Server shutdown failed"));
797
- __hostGlobal(["process"]).exitCode = 1;
798
- return null;
799
- } finally {
800
- __contextRestore(__contextScope);
801
- }
802
- }), [0], "closure"));
803
- return null;
804
- });
805
- __normalize(__hostGlobal(["process"]).once("SIGTERM", stop));
806
- __normalize(__hostGlobal(["process"]).once("SIGINT", stop));
807
- return __normalize(server.start()).then(__withArity(__bindContexts((address) => {
808
- const __contextScope = [];
809
- try {
810
- address = __boundary(address);
811
- __normalize(__contextGet("log").info(`Listening on ${__normalize(address.host)}:${__normalize(address.port)}`));
812
- return null;
813
- return null;
814
- } finally {
815
- __contextRestore(__contextScope);
816
- }
817
- }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
818
- error = __boundary(error);
819
- __normalize(__hostGlobal(["process"]).removeListener("SIGTERM", stop));
820
- __normalize(__hostGlobal(["process"]).removeListener("SIGINT", stop));
821
- throw error;
822
- return null;
823
- }), [0], "closure"));
824
- return null;
825
- }
826
-
827
- function brokerReply(port, message) {
828
- __requireArity(arguments.length, [0, 1], "brokerReply");
829
- port = __boundary(port);
830
- message = __boundary(message);
831
- try {
832
- __normalize(port.postMessage(message));
833
- } catch (error) {
834
- return null;
835
- }
836
- return null;
837
- return null;
838
- }
839
- const { configure } = await import("./.lango/runtime.mjs");
2
+ import { main } from "../server.mjs";
3
+ export * from "../server.mjs";
4
+ import { configure } from "../.lango/runtime.mjs";
840
5
  configure({ output: (value) => console.log(value) });
841
6
  await main(process.argv.slice(2));
842
7
  //# sourceMappingURL=server.mjs.map