@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.
Files changed (60) hide show
  1. package/README.md +283 -4
  2. package/dist/builder.mjs +16 -1
  3. package/dist/builder.mjs.map +1 -1
  4. package/dist/cli/endpoint.mjs +6 -0
  5. package/dist/cli/endpoint.mjs.map +1 -1
  6. package/dist/cli/longpoll_broker.mjs +214 -0
  7. package/dist/cli/longpoll_broker.mjs.map +1 -0
  8. package/dist/cli/longpoll_options.mjs +102 -0
  9. package/dist/cli/longpoll_options.mjs.map +1 -0
  10. package/dist/cli/longpoll_session.mjs +135 -0
  11. package/dist/cli/longpoll_session.mjs.map +1 -0
  12. package/dist/cli/middleware.mjs +25 -0
  13. package/dist/cli/middleware.mjs.map +1 -0
  14. package/dist/cli/options.mjs +14 -2
  15. package/dist/cli/options.mjs.map +1 -1
  16. package/dist/cli/routes.mjs +66 -2
  17. package/dist/cli/routes.mjs.map +1 -1
  18. package/dist/cli/server.mjs +243 -23
  19. package/dist/cli/server.mjs.map +1 -1
  20. package/dist/cli/static_files.mjs +125 -0
  21. package/dist/cli/static_files.mjs.map +1 -0
  22. package/dist/endpoint.mjs +6 -0
  23. package/dist/endpoint.mjs.map +1 -1
  24. package/dist/group.mjs +17 -1
  25. package/dist/group.mjs.map +1 -1
  26. package/dist/longpoll_broker.mjs +214 -0
  27. package/dist/longpoll_broker.mjs.map +1 -0
  28. package/dist/longpoll_options.mjs +102 -0
  29. package/dist/longpoll_options.mjs.map +1 -0
  30. package/dist/longpoll_session.mjs +135 -0
  31. package/dist/longpoll_session.mjs.map +1 -0
  32. package/dist/middleware.mjs +25 -0
  33. package/dist/middleware.mjs.map +1 -0
  34. package/dist/options.mjs +14 -2
  35. package/dist/options.mjs.map +1 -1
  36. package/dist/routes.mjs +66 -2
  37. package/dist/routes.mjs.map +1 -1
  38. package/dist/runtime.mjs +118 -44
  39. package/dist/runtime.mjs.map +1 -1
  40. package/dist/server.mjs +243 -23
  41. package/dist/server.mjs.map +1 -1
  42. package/dist/server_context.mjs +78 -0
  43. package/dist/server_context.mjs.map +1 -0
  44. package/dist/static_files.mjs +125 -0
  45. package/dist/static_files.mjs.map +1 -0
  46. package/package.json +9 -4
  47. package/src/builder.lango +11 -0
  48. package/src/endpoint.lango +7 -0
  49. package/src/group.lango +14 -0
  50. package/src/longpoll.lua +61 -0
  51. package/src/longpoll_broker.lango +161 -0
  52. package/src/longpoll_options.lango +79 -0
  53. package/src/longpoll_session.lango +90 -0
  54. package/src/middleware.lango +10 -0
  55. package/src/options.lango +16 -0
  56. package/src/routes.lango +65 -1
  57. package/src/runtime.lango +62 -0
  58. package/src/server.lango +182 -17
  59. package/src/server_context.lango +58 -0
  60. package/src/static_files.lango +90 -0
package/README.md CHANGED
@@ -80,6 +80,40 @@ Lango's explicit `capture` rules; capture any contexts needed by later callbacks
80
80
  Workers retain their loaded modules between requests. Module-level state is
81
81
  worker-local, not shared or client-specific. An optional configured SQL database is available through `context db`; application schema and migrations remain application-owned.
82
82
 
83
+ ## Static files
84
+
85
+ Static serving is optional. Add a section to `deploy.xml`:
86
+
87
+ ```xml
88
+ <static path="/" directory="./public" index="index.html"/>
89
+ ```
90
+
91
+ Or configure the same settings with a Builder:
92
+
93
+ ```lango
94
+ builder.configure({
95
+ static: {
96
+ path: "/"
97
+ directory: "./public"
98
+ index: "index.html"
99
+ }
100
+ })
101
+ ```
102
+
103
+ `directory` is required and resolves against the application directory. The URL
104
+ prefix defaults to `/`; `index` defaults to `index.html`. The directory must
105
+ exist when the server starts. Only one static root is supported.
106
+
107
+ GET and HEAD stream files in the main thread without reserving a worker or
108
+ creating a token. HTML is served unchanged. File responses support conditional
109
+ requests and byte ranges through `serve-static`. Query strings are allowed for
110
+ static assets. Missing files and directories without an index return 404;
111
+ directory listings and SPA fallbacks are not enabled. Dotfiles are denied.
112
+
113
+ POST requests retain the normal JSON worker pipeline, including at `/`. Static
114
+ serving alone does not reserve that POST path or install UI lifecycle handlers.
115
+ JWT authorization applies to POST handlers; static files are public.
116
+
83
117
  ## Routes
84
118
 
85
119
  ```xml
@@ -112,11 +146,12 @@ worker-local, not shared or client-specific. An optional configured SQL database
112
146
  dependencies from the including package. Include prefixes concatenate; a
113
147
  missing include path mounts at `/`. The same package can be mounted at several
114
148
  prefixes. Include cycles, missing exports, and duplicate endpoints fail early.
115
- * Included files contain routes only. They cannot register global lifecycle
149
+ * Included files contain routes only. They cannot register middleware, global lifecycle
116
150
  events or change deployment/JWT settings. Events belong to the application's
117
151
  root routes file (or Builder). Each event can be registered once.
118
- * Unknown XML elements and attributes are rejected. XML and Builder definitions
119
- use the same endpoint validation and startup loading path.
152
+ * Custom endpoint tags must name registered middleware. Unknown attributes are
153
+ rejected. XML and Builder definitions use the same endpoint validation and
154
+ startup loading path.
120
155
 
121
156
  A feature package can expose its definitions as follows:
122
157
 
@@ -167,13 +202,90 @@ createServer(root, signingKey)
167
202
  return builder.build()
168
203
  ```
169
204
 
170
- `Builder(root)` defaults to the current directory. `configure`, `endpoint`,
205
+ `Builder(root)` defaults to the current directory. `configure`, `addMiddleware`, `endpoint`,
171
206
  `include`, and `event` return the Builder. `group` returns a group supporting
172
207
  `endpoint`, nested `group`, and `include`; retain the Builder for `build()`.
173
208
  The built Server snapshots definitions; later Builder changes do not affect it.
174
209
  `new server/Server(directory)` is the XML equivalent. Routes, Endpoint, worker
175
210
  classes, and token implementation classes are internal package details.
176
211
 
212
+ ## Route middleware
213
+
214
+ Middleware wraps an application handler inside its worker. Register an exported
215
+ function by module and export name before calling `build()`:
216
+
217
+ ```lango
218
+ builder.addMiddleware("ui", {
219
+ module: "@shop/middleware"
220
+ handler: "wrap"
221
+ })
222
+ builder.endpoint({
223
+ path: "/orders/save"
224
+ module: "@shop/orders"
225
+ handler: "save"
226
+ middleware: "ui"
227
+ })
228
+ ```
229
+
230
+ `Group.endpoint()` accepts the same optional `middleware` field. Omitting it or
231
+ setting it to `null` invokes the application handler directly; middleware is
232
+ not inherited from a group. An endpoint selects one middleware. The registration
233
+ name `ui` is application-defined; the server has no built-in UI dependency.
234
+
235
+ The XML equivalent uses a declaration in the application's root `routes.xml` and
236
+ the registered name as its endpoint tag:
237
+
238
+ ```xml
239
+ <routes>
240
+ <ui path="/orders/save" module="@shop/orders" handler="save"/>
241
+ <middleware name="ui" module="@shop/middleware" handler="wrap"/>
242
+ </routes>
243
+ ```
244
+
245
+ Declarations may appear before or after their routes. Custom tags support the
246
+ same path, module, handler and auth attributes as `endpoint`; group defaults,
247
+ wildcards and include prefixes apply normally. Included packages can use registered
248
+ middleware but cannot declare it, and declarations inside groups are rejected.
249
+ Registration names are server-wide. Duplicate registrations fail, including
250
+ duplicates across XML and programmatic registration on the same route collection.
251
+ Names must match `[A-Za-z_][A-Za-z0-9_-]*`. The names `routes`, `endpoint`,
252
+ `longpoll`, `group`, `include`, `event` and `middleware` are reserved. Longpoll
253
+ routes retain their own transport behavior and do not accept endpoint middleware.
254
+
255
+ Each worker loads and verifies all registered exports during startup, even unused
256
+ registrations. An unresolved module, missing/non-function export, or route using
257
+ unregistered middleware fails startup. No function or captured closure is
258
+ transferred from the main thread, and no per-request import is needed.
259
+
260
+ The middleware signature is `wrap(handler, path, input)`: `handler` is the resolved
261
+ application function, `path` is the actual request path including mounted prefixes,
262
+ and `input` is the decoded request object. For example, the registered module can
263
+ transform both synchronous and Promise results:
264
+
265
+ ```lango
266
+ import js global Promise
267
+
268
+ export wrap(handler, path, input)
269
+
270
+ wrap(handler, path, input)
271
+ return chain Promise/resolve(handler(input))
272
+ then(output)
273
+ capture path
274
+ return {
275
+ path: path
276
+ result: output
277
+ }
278
+ ```
279
+
280
+ Middleware runs after Register/Validate and route authorization, with the existing
281
+ request, response, token, log, db and server contexts. It can establish its own
282
+ contexts for the application handler; callbacks retain them using normal Lango
283
+ `capture` rules. It is responsible for invoking the application handler when
284
+ needed and returns the final result, which the server resolves and JSON-serializes
285
+ in the worker. Request events observe that final serialized result. Middleware,
286
+ handler and serialization errors follow the existing error/token behavior;
287
+ request/event deadlines and SQL transaction cleanup still apply.
288
+
177
289
  ## Configuration
178
290
 
179
291
  ```xml
@@ -430,3 +542,170 @@ lango-js 0.1.13 archive before running a fresh registry-based installation or CI
430
542
  then build/publish lango-server and rebuild application SQL modules. Local validation
431
543
  uses the exact prepared compiler archive, without npm links; nothing is automatically
432
544
  published by these commands.
545
+
546
+ ## Long polling
547
+
548
+ Long polling uses Redis Streams for shared, retained history. Ordinary HTTP/SQL
549
+ applications do not connect to Redis. Applications declaring a longpoll route must
550
+ configure Redis; a missing configuration or unreachable Redis fails startup.
551
+ Redis 6.2 or newer is required. Use a single Redis endpoint (including a managed HA
552
+ endpoint); Redis Cluster and Sentinel discovery are not supported in this release.
553
+ All pods must use the same namespace, routes, JWT configuration and Redis database.
554
+ No sticky sessions are required.
555
+
556
+ ```xml
557
+ <!-- deploy.xml -->
558
+ <deploy>
559
+ <jwt keyEnv="APP_JWT_KEY"/>
560
+ <redis connectionEnv="REDIS_URL" namespace="my-app" maxPendingPolls="1024"/>
561
+ </deploy>
562
+ ```
563
+
564
+ ```xml
565
+ <!-- routes.xml -->
566
+ <routes>
567
+ <longpoll path="/updates" auth="login" waitTimeoutMs="20000"
568
+ retentionMs="300000" maxMessages="1000" fallback="/state"/>
569
+ </routes>
570
+ ```
571
+
572
+ The Builder equivalent is `builder.longpoll(options)` or
573
+ `group.longpoll(options)`. No module or handler is needed. Group and include
574
+ prefixes apply to both `path` and `fallback`; auth is inherited and defaults to
575
+ `login`. Paths must be exact absolute URL paths, without wildcards or query
576
+ strings. Duplicate paths conflict with endpoints as well as other longpoll routes.
577
+ The fallback is returned to the client; the server never calls it automatically.
578
+
579
+ Publish from any handler or event:
580
+
581
+ ```lango
582
+ notify(input)
583
+ context server
584
+ return chain server.publish("/updates", input.key, {
585
+ type: "changed"
586
+ value: input.value
587
+ })
588
+ then(cursor)
589
+ return {
590
+ cursor: cursor
591
+ }
592
+ ```
593
+
594
+ `server.publish(path, key, data)` resolves to an opaque cursor after Redis has
595
+ accepted the JSON message. `server.cursor(path, key)` resolves to the current
596
+ cursor without publishing. Both are also methods on the public `Server` instance
597
+ for application code outside workers. They require a running server and a declared
598
+ longpoll path. The framework does not expose a public HTTP publish endpoint.
599
+ Inside workers, `context server` forwards these calls to the main process.
600
+ Application URLs passed to these methods are the final mounted paths.
601
+
602
+ The key is an application-generated capability string, containing 1–1024 UTF-8
603
+ bytes. Use an unpredictable value and share it only with intended subscribers.
604
+ It is deliberately independent of `clientId`: all authorized subscribers sharing
605
+ a key receive the same messages. Route auth and JWT validation still apply.
606
+
607
+ ### HTTP protocol
608
+
609
+ Send JSON POST requests to the longpoll URL, with the usual Bearer token:
610
+
611
+ ```json
612
+ {"key":"application-generated-secret", "cursor":null}
613
+ ```
614
+
615
+ Omitting `cursor` or sending `null` starts at the oldest currently retained
616
+ message. It does not claim to recover messages removed before the subscription
617
+ started. To subscribe only to future changes, obtain an application-provided
618
+ `server.cursor()` value first. The application is responsible for coordinating
619
+ that cursor with its initial snapshot.
620
+
621
+ A successful response (HTTP 200) has this shape:
622
+
623
+ ```json
624
+ {
625
+ "messages": [{"id":"opaque-message-cursor", "data":{"value":42}}],
626
+ "cursor":"opaque-last-delivered-cursor",
627
+ "resyncRequired":false
628
+ }
629
+ ```
630
+
631
+ The usual `x-lango-token` response header carries the updated token. A normal wait
632
+ timeout returns HTTP 200 with `messages: []` and a continuation cursor. Send the
633
+ next request immediately. Only advance the stored cursor after processing the
634
+ messages successfully. Delivery can repeat; `messages[].id` supports deduplication.
635
+ Reading does not delete messages or consume another subscriber's share.
636
+
637
+ An expired/recreated channel, missing history, future position, malformed cursor
638
+ or cursor from another channel returns HTTP 409:
639
+
640
+ ```json
641
+ {"resyncRequired":true, "fallback":"/state"}
642
+ ```
643
+
644
+ `fallback` is `null` when unconfigured. No replacement cursor is silently issued.
645
+ Fetch a fresh snapshot through the application's normal authenticated endpoint,
646
+ then resume using the cursor accompanying that snapshot. A cursor identifies its
647
+ channel generation and Redis message ID; a pod restart alone does not invalidate it.
648
+ A cursor equal to the most recently trimmed message remains a valid continuation
649
+ if no later unseen message was removed.
650
+
651
+ Invalid poll input returns 400. Missing/invalid/expired credentials or insufficient
652
+ route permission return 401. Unavailable Redis, command timeout or shutdown while
653
+ waiting returns 503; exceeding the pending limit returns 503 `PollLimit`.
654
+ No token or advanced cursor is returned for infrastructure failures. Redis errors
655
+ never turn into successful empty responses or an in-memory history fallback.
656
+ Retry failures with backoff; abort the HTTP request when the subscription closes.
657
+
658
+ ### Waiting, limits and operations
659
+
660
+ Waiting HTTP requests stay in the main process and hold neither a worker nor a
661
+ request database scope. Short worker jobs run Register/Validate/auth before
662
+ waiting and validate again before message delivery, resync or normal timeout.
663
+ The existing one-second Validate freshness window applies; waiting never extends
664
+ JWT expiry. Request events run for completed poll responses using the normal
665
+ prepared-result behavior. Worker jobs retain the usual queue/deadline limits.
666
+
667
+ One shared, nonblocking Redis connection per Server reads pending subscriptions
668
+ at intervals of up to 250 ms. There is no connection per poll and no Pub/Sub
669
+ correctness dependency. A read immediately precedes waiting, so a publication
670
+ between reads is replayed from history. Command and startup Redis waits are bounded
671
+ to three seconds; reconnect attempts happen automatically. Disconnected requests
672
+ and shutdown release timers and pending subscriptions.
673
+
674
+ | Limit | Default | Supported range |
675
+ | --- | ---: | ---: |
676
+ | `waitTimeoutMs` | 20,000 | 1–60,000 ms |
677
+ | `retentionMs` | 300,000 | 1–86,400,000 ms |
678
+ | `maxMessages` per channel | 1,000 | 1–10,000 |
679
+ | Redis `maxPendingPolls` per Server | 1,024 | 1–10,000 |
680
+ | Key size | — | 1–1,024 UTF-8 bytes |
681
+ | Published JSON size | — | up to 262,144 UTF-8 bytes |
682
+ | Messages per response | — | up to 16 |
683
+ | Sum of message JSON bytes per response | — | up to 1,048,576 bytes |
684
+
685
+ JSON envelope and cursor bytes are additional to the response data limit. Normal
686
+ HTTP body limits also apply. Streams and metadata expire after an idle retention
687
+ period; reads do not keep unused channels alive. Publishing refreshes that expiry.
688
+ Age/count trimming and cursor checks execute atomically in a small Redis Lua
689
+ resource; framework code and worker integration are written in Lango. Channel
690
+ storage keys hash the namespace, URL and capability key. Configure Redis capacity,
691
+ eviction policy, persistence and HA for the application; eviction/lost history
692
+ requires resync. Keep retention comfortably above the polling/retry interval.
693
+
694
+ A publish timing out has an uncertain outcome: Redis may have accepted it. Retry
695
+ with application message identifiers if business-level deduplication is required.
696
+ SQL writes and Redis publication are separate operations. Use an application
697
+ outbox when they must reliably occur together. Likewise, reading a database
698
+ snapshot followed by the latest cursor is not an atomic snapshot protocol; use a
699
+ consistent application revision or replay-safe updates. Redis failover does not
700
+ provide a universal zero-data-loss guarantee.
701
+
702
+ Run the Redis integration suite against a **disposable** Redis database:
703
+
704
+ ```sh
705
+ npm run build
706
+ LANGO_TEST_REDIS=redis://127.0.0.1:6379 npm run test:longpoll
707
+ ```
708
+
709
+ The suite briefly pauses Redis commands to test infrastructure timeouts. Do not
710
+ point it at a shared or production Redis instance. CI runs this suite separately
711
+ from `npm test`, alongside the PostgreSQL integration suite.
package/dist/builder.mjs CHANGED
@@ -34,6 +34,14 @@ export class Builder {
34
34
  return this;
35
35
  return null;
36
36
  }
37
+ addMiddleware(name, spec) {
38
+ __requireArity(arguments.length, [0, 1], "addMiddleware");
39
+ name = __boundary(name);
40
+ spec = __boundary(spec);
41
+ __normalize(this.#routes.addMiddleware(name, spec));
42
+ return this;
43
+ return null;
44
+ }
37
45
  endpoint(spec) {
38
46
  __requireArity(arguments.length, [0], "endpoint");
39
47
  spec = __boundary(spec);
@@ -41,6 +49,13 @@ export class Builder {
41
49
  return this;
42
50
  return null;
43
51
  }
52
+ longpoll(spec) {
53
+ __requireArity(arguments.length, [0], "longpoll");
54
+ spec = __boundary(spec);
55
+ __normalize(this.#routes.longpoll(spec));
56
+ return this;
57
+ return null;
58
+ }
44
59
  group(spec) {
45
60
  __requireArity(arguments.length, [0], "group");
46
61
  spec = __boundary(spec);
@@ -62,7 +77,7 @@ export class Builder {
62
77
  return null;
63
78
  }
64
79
  build() {
65
- return new Server(null, { settings: options(__normalize(this.#root), __normalize(this.#settings)), routes: __normalize(this.#routes.definitions()), events: __normalize(this.#routes.events()) });
80
+ return new Server(null, { settings: options(__normalize(this.#root), __normalize(this.#settings)), routes: __normalize(this.#routes.definitions()), events: __normalize(this.#routes.events()), middlewares: __normalize(this.#routes.middlewares()) });
66
81
  return null;
67
82
  }
68
83
  }
@@ -1 +1 @@
1
- {"version":3,"file":"builder.mjs","sources":["builder.lango"],"sourcesContent":["import js \"node:path\" as path\nimport js global process\nimport \"./routes\"\n class Routes\nimport \"./group\"\n class Group\nimport \"./options\"\n options(root, supplied = null)\nimport \"./server\"\n class Server\n\nexport class Builder(root = null)\n methods\n configure(settings)\n endpoint(spec)\n group(spec)\n include(spec)\n event(spec)\n build()\n\nBuilder(root = null)\n if root == null\n root = process.cwd()\n @root = path/resolve(root)\n @settings = {}\n @routes = new Routes(@root)\n\nBuilder:configure(settings)\n for settings as key: value\n @settings[key] = value\n return @this\n\nBuilder:endpoint(spec)\n @routes.endpoint(spec)\n return @this\n\nBuilder:group(spec)\n return new Group(@routes, spec)\n\nBuilder:include(spec)\n @routes.include(spec)\n return @this\n\nBuilder:event(spec)\n @routes.event(spec)\n return @this\n\nBuilder:build()\n return new Server(null, {\n settings: options(@root, @settings)\n routes: @routes.definitions()\n events: @routes.events()\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"builder.mjs","sources":["builder.lango"],"sourcesContent":["import js \"node:path\" as path\nimport js global process\nimport \"./routes\"\n class Routes\nimport \"./group\"\n class Group\nimport \"./options\"\n options(root, supplied = null)\nimport \"./server\"\n class Server\n\nexport class Builder(root = null)\n methods\n configure(settings)\n addMiddleware(name, spec)\n endpoint(spec)\n longpoll(spec)\n group(spec)\n include(spec)\n event(spec)\n build()\n\nBuilder(root = null)\n if root == null\n root = process.cwd()\n @root = path/resolve(root)\n @settings = {}\n @routes = new Routes(@root)\n\nBuilder:configure(settings)\n for settings as key: value\n @settings[key] = value\n return @this\n\nBuilder:addMiddleware(name, spec)\n @routes.addMiddleware(name, spec)\n return @this\n\nBuilder:endpoint(spec)\n @routes.endpoint(spec)\n return @this\n\nBuilder:longpoll(spec)\n @routes.longpoll(spec)\n return @this\n\nBuilder:group(spec)\n return new Group(@routes, spec)\n\nBuilder:include(spec)\n @routes.include(spec)\n return @this\n\nBuilder:event(spec)\n @routes.event(spec)\n return @this\n\nBuilder:build()\n return new Server(null, {\n settings: options(@root, @settings)\n routes: @routes.definitions()\n events: @routes.events()\n middlewares: @routes.middlewares()\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -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";
@@ -1 +1 @@
1
- {"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["export class Endpoint(spec)\n properties\n path\n module\n handler\n auth\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 @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":";;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,214 @@
1
+ import * as redis from "redis";
2
+ import * as crypto from "node:crypto";
3
+ import * as fs from "node:fs";
4
+ import * as path from "node:path";
5
+ import * as modules from "node:module";
6
+ import {
7
+ hostGlobal as __hostGlobal,
8
+ hostGlobalCall as __hostGlobalCall,
9
+ fromJson as __fromJson,
10
+ toJson as __toJson,
11
+ isNumber as __isNumber,
12
+ isString as __isString,
13
+ isBool as __isBool,
14
+ isObject as __isObject,
15
+ isArray as __isArray,
16
+ requireBoolean as __requireBoolean,
17
+ normalize as __normalize,
18
+ boundary as __boundary,
19
+ requireArity as __requireArity,
20
+ withArity as __withArity,
21
+ } from "./.lango/runtime.mjs";
22
+
23
+ export class LongpollBroker {
24
+ #routes;
25
+ #settings;
26
+ #client;
27
+ #script;
28
+ #root;
29
+ #lango;
30
+ constructor(settings, routes) {
31
+ __requireArity(arguments.length, [0, 1], "constructor");
32
+ settings = __boundary(settings);
33
+ routes = __boundary(routes);
34
+ this.#routes = __normalize(__hostGlobal(["Object"]).create(null));
35
+ for (const item of routes) {
36
+ if (__requireBoolean(__normalize(item.kind) === "longpoll")) {
37
+ this.#routes[__normalize(item.path)] = item;
38
+ }
39
+ }
40
+ this.#settings = __normalize(settings.redis);
41
+ this.#client = null;
42
+ this.#script = null;
43
+ if (__requireBoolean(__requireBoolean(__normalize(__normalize(__hostGlobal(["Object"]).keys(__normalize(this.#routes))).length) > 0) && __requireBoolean(__normalize(this.#settings) === null))) {
44
+ throw "Longpoll routes require Redis configuration";
45
+ }
46
+ this.#root = __normalize(settings.root);
47
+ }
48
+ route(path) {
49
+ __requireArity(arguments.length, [0], "route");
50
+ path = __boundary(path);
51
+ if (__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(__normalize(this.#routes), path)))) {
52
+ return __normalize(this.#routes[path]);
53
+ }
54
+ return null;
55
+ return null;
56
+ }
57
+ open() {
58
+ if (__requireBoolean(__normalize(__normalize(__hostGlobal(["Object"]).keys(__normalize(this.#routes))).length) === 0)) {
59
+ return __normalize(__hostGlobal(["Promise"]).resolve(null));
60
+ }
61
+ let resolver = __normalize(modules.createRequire(__normalize(path.join(__normalize(this.#root), "package.json"))));
62
+ let entry = __normalize(resolver.resolve("@lango-project/lango-server"));
63
+ this.#script = __normalize(fs.readFileSync(__normalize(path.join(__normalize(path.dirname(entry)), "../src/longpoll.lua")), "utf8"));
64
+ let config = __normalize(this.#settings);
65
+ let name = __normalize(config.connectionEnv);
66
+ this.#client = __normalize(redis.createClient({ url: __normalize(__hostGlobal(["process"]).env[name]), disableOfflineQueue: true, commandsQueueMaxLength: 2048, socket: { connectTimeout: 2000, reconnectStrategy: 500 } }));
67
+ let client = __normalize(this.#client);
68
+ __normalize(client.on("error", __withArity((error) => {
69
+ error = __boundary(error);
70
+ return null;
71
+ return null;
72
+ }, [0], "closure")));
73
+ return bounded(__normalize(client.connect()), 3000);
74
+ return null;
75
+ }
76
+ close() {
77
+ if (__requireBoolean(__requireBoolean(__normalize(this.#client) !== null) && __requireBoolean(__normalize(this.#client.isOpen)))) {
78
+ __normalize(this.#client.destroy());
79
+ }
80
+ return null;
81
+ return null;
82
+ }
83
+ publish(path, key, data) {
84
+ __requireArity(arguments.length, [0, 1, 2], "publish");
85
+ path = __boundary(path);
86
+ key = __boundary(key);
87
+ data = __boundary(data);
88
+ let body = __normalize(__hostGlobal(["JSON"]).stringify(data));
89
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(body))) || __requireBoolean(__normalize(__hostGlobal(["Buffer"]).byteLength(body)) > 262144))) {
90
+ return __normalize(__hostGlobal(["Promise"]).reject("Longpoll message must be JSON within 262144 bytes"));
91
+ }
92
+ return this.#execute("publish", path, key, null, body);
93
+ return null;
94
+ }
95
+ cursor(path, key) {
96
+ __requireArity(arguments.length, [0, 1], "cursor");
97
+ path = __boundary(path);
98
+ key = __boundary(key);
99
+ return this.#execute("cursor", path, key, null, "");
100
+ return null;
101
+ }
102
+ read(path, key, cursor) {
103
+ __requireArity(arguments.length, [0, 1, 2], "read");
104
+ path = __boundary(path);
105
+ key = __boundary(key);
106
+ cursor = __boundary(cursor);
107
+ return this.#execute("read", path, key, cursor, "");
108
+ return null;
109
+ }
110
+ #execute(operation, path, key, cursor, body) {
111
+ __requireArity(arguments.length, [0, 1, 2, 3, 4], "execute");
112
+ operation = __boundary(operation);
113
+ path = __boundary(path);
114
+ key = __boundary(key);
115
+ cursor = __boundary(cursor);
116
+ body = __boundary(body);
117
+ let item = this.route(path);
118
+ if (__requireBoolean(item === null)) {
119
+ return __normalize(__hostGlobal(["Promise"]).reject("Unknown longpoll path"));
120
+ }
121
+ if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(key))) || __requireBoolean(key === "")) || __requireBoolean(__normalize(__hostGlobal(["Buffer"]).byteLength(key)) > 1024))) {
122
+ return __normalize(__hostGlobal(["Promise"]).reject("Longpoll key must contain 1 to 1024 bytes"));
123
+ }
124
+ if (__requireBoolean(__requireBoolean(__normalize(this.#client) === null) || __requireBoolean(!__requireBoolean(__normalize(this.#client.isReady))))) {
125
+ return __normalize(__hostGlobal(["Promise"]).reject("RedisUnavailable"));
126
+ }
127
+ let hash = __normalize(crypto.createHash("sha256"));
128
+ __normalize(hash.update(__toJson([__normalize(this.#settings.namespace), path, key])));
129
+ let channel = __normalize(hash.digest("hex"));
130
+ let prefix = `lango:longpoll:{${channel}}`;
131
+ let position = { generation: "", id: "0-0" };
132
+ if (__requireBoolean(cursor !== null)) {
133
+ position = decode(cursor, channel);
134
+ if (__requireBoolean(position === null)) {
135
+ return __normalize(__hostGlobal(["Promise"]).resolve({ resyncRequired: true }));
136
+ }
137
+ }
138
+ let pending = __normalize(this.#client.eval(__normalize(this.#script), { keys: [`${prefix}:stream`, `${prefix}:meta`], arguments: [operation, __normalize(crypto.randomUUID()), `${__normalize(item.retentionMs)}`, `${__normalize(item.maxMessages)}`, __normalize(position.generation), __normalize(position.id), body] }));
139
+ return bounded(pending, 3000).then(__withArity((raw) => {
140
+ raw = __boundary(raw);
141
+ let result = __normalize(__hostGlobal(["JSON"]).parse(raw));
142
+ if (__requireBoolean(__normalize(result.resyncRequired) === true)) {
143
+ return result;
144
+ }
145
+ result.cursor = encode(channel, __normalize(result.generation), __normalize(result.id));
146
+ if (__requireBoolean(operation !== "read")) {
147
+ return __normalize(result.cursor);
148
+ }
149
+ let messages = [];
150
+ if (__requireBoolean(__isArray(__normalize(result.messages)))) {
151
+ for (const message of __normalize(result.messages)) {
152
+ messages.push({ id: encode(channel, __normalize(result.generation), __normalize(message.id)), data: __normalize(__hostGlobal(["JSON"]).parse(__normalize(message.data))) });
153
+ }
154
+ }
155
+ return { messages: messages, cursor: __normalize(result.cursor), resyncRequired: false };
156
+ return null;
157
+ }, [0], "closure"));
158
+ return null;
159
+ }
160
+ }
161
+ function encode(channel, generation, id) {
162
+ __requireArity(arguments.length, [0, 1, 2], "encode");
163
+ channel = __boundary(channel);
164
+ generation = __boundary(generation);
165
+ id = __boundary(id);
166
+ let buffer = __normalize(__hostGlobal(["Buffer"]).from(__toJson([channel, generation, id])));
167
+ return __normalize(buffer.toString("base64url"));
168
+ return null;
169
+ }
170
+
171
+ function decode(cursor, channel) {
172
+ __requireArity(arguments.length, [0, 1], "decode");
173
+ cursor = __boundary(cursor);
174
+ channel = __boundary(channel);
175
+ let buffer;
176
+ let parts;
177
+ let pattern;
178
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(cursor))) || __requireBoolean(__normalize(cursor.length) > 512))) {
179
+ return null;
180
+ }
181
+ try {
182
+ buffer = __normalize(__hostGlobal(["Buffer"]).from(cursor, "base64url"));
183
+ parts = __fromJson(__normalize(buffer.toString("utf8")));
184
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isArray(parts))) || __requireBoolean(__normalize(parts.length) !== 3)) || __requireBoolean(__normalize(parts[0]) !== channel)) || __requireBoolean(!__requireBoolean(__isString(__normalize(parts[1]))))) || __requireBoolean(!__requireBoolean(__isString(__normalize(parts[2])))))) {
185
+ return null;
186
+ }
187
+ pattern = new (__hostGlobal(["RegExp"]))("^(0|[1-9][0-9]{0,18})-(0|[1-9][0-9]{0,18})$");
188
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(pattern.test(__normalize(parts[2]))))) || __requireBoolean(__normalize(__normalize(parts[2]).length) > 40))) {
189
+ return null;
190
+ }
191
+ return { generation: __normalize(parts[1]), id: __normalize(parts[2]) };
192
+ } catch (error) {
193
+ return null;
194
+ }
195
+ return null;
196
+ }
197
+
198
+ function bounded(pending, ms) {
199
+ __requireArity(arguments.length, [0, 1], "bounded");
200
+ pending = __boundary(pending);
201
+ ms = __boundary(ms);
202
+ let expired = __normalize(__hostGlobal(["Promise"]).withResolvers());
203
+ let fail = () => {
204
+ __normalize(expired.reject("RedisUnavailable"));
205
+ return null;
206
+ };
207
+ let timer = __hostGlobalCall(["setTimeout"], fail, ms);
208
+ return __normalize(__hostGlobal(["Promise"]).race([pending, __normalize(expired.promise)])).finally(() => {
209
+ __hostGlobalCall(["clearTimeout"], timer);
210
+ return null;
211
+ });
212
+ return null;
213
+ }
214
+ //# sourceMappingURL=longpoll_broker.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"longpoll_broker.mjs","sources":["longpoll_broker.lango"],"sourcesContent":["import js \"redis\" as redis\nimport js \"node:crypto\" as crypto\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js global Buffer\nimport js global Promise\nimport js global process\nimport js global JSON\nimport js global RegExp\nimport js global Object\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class LongpollBroker(settings, routes)\n methods\n open()\n close()\n route(path)\n publish(path, key, data)\n cursor(path, key)\n read(path, key, cursor)\n\nLongpollBroker(settings, routes)\n @routes = Object/create(null)\n for routes as item\n if item.kind == \"longpoll\"\n @routes[item.path] = item\n @settings = settings.redis\n @client = null\n @script = null\n if Object/keys(@routes).length > 0 and @settings == null\n throw \"Longpoll routes require Redis configuration\"\n @root = settings.root\n\nLongpollBroker:route(path)\n if Object/hasOwn(@routes, path)\n return @routes[path]\n return null\n\nLongpollBroker:open()\n if Object/keys(@routes).length == 0\n return Promise/resolve(null)\n resolver = modules/createRequire(path/join(@root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @script = fs/readFileSync(path/join(path/dirname(entry), \"../src/longpoll.lua\"), \"utf8\")\n config = @settings\n name = config.connectionEnv\n @client = redis/createClient({\n url: process.env[name]\n disableOfflineQueue: true\n commandsQueueMaxLength: 2048\n socket: {\n connectTimeout: 2000\n reconnectStrategy: 500\n }\n })\n client = @client\n client.on(\"error\", (error)\n return null\n )\n return bounded(client.connect(), 3000)\n\nLongpollBroker:close()\n if @client != null and @client.isOpen\n @client.destroy()\n return null\n\nLongpollBroker:publish(path, key, data)\n body = JSON/stringify(data)\n if !is_string(body) or Buffer/byteLength(body) > 262144\n return Promise/reject(\"Longpoll message must be JSON within 262144 bytes\")\n return execute(\"publish\", path, key, null, body)\n\nLongpollBroker:cursor(path, key)\n return execute(\"cursor\", path, key, null, \"\")\n\nLongpollBroker:read(path, key, cursor)\n return execute(\"read\", path, key, cursor, \"\")\n\nLongpollBroker:execute(operation, path, key, cursor, body)\n item = route(path)\n if item == null\n return Promise/reject(\"Unknown longpoll path\")\n if !is_string(key) or key == \"\" or Buffer/byteLength(key) > 1024\n return Promise/reject(\"Longpoll key must contain 1 to 1024 bytes\")\n if @client == null or !@client.isReady\n return Promise/reject(\"RedisUnavailable\")\n hash = crypto/createHash(\"sha256\")\n hash.update(to_json([@settings.namespace, path, key]))\n channel = hash.digest(\"hex\")\n prefix = \"lango:longpoll:{${channel}}\"\n position = {\n generation: \"\"\n id: \"0-0\"\n }\n if cursor != null\n position = decode(cursor, channel)\n if position == null\n return Promise/resolve({\n resyncRequired: true\n })\n pending = @client.eval(@script, {\n keys: [\"${prefix}:stream\", \"${prefix}:meta\"]\n arguments: [operation, crypto/randomUUID(), \"${item.retentionMs}\", \"${item.maxMessages}\", position.generation, position.id, body]\n })\n return chain bounded(pending, 3000)\n then(raw)\n capture channel\n capture operation\n result = JSON/parse(raw)\n if result.resyncRequired == true\n return result\n result.cursor = encode(channel, result.generation, result.id)\n if operation != \"read\"\n return result.cursor\n messages = []\n if is_array(result.messages)\n for result.messages as message\n messages.add({\n id: encode(channel, result.generation, message.id)\n data: JSON/parse(message.data)\n })\n return {\n messages: messages\n cursor: result.cursor\n resyncRequired: false\n }\n\nencode(channel, generation, id)\n buffer = Buffer/from(to_json([channel, generation, id]))\n return buffer.toString(\"base64url\")\n\ndecode(cursor, channel)\n if !is_string(cursor) or cursor.length > 512\n return null\n try\n buffer = Buffer/from(cursor, \"base64url\")\n parts = from_json(buffer.toString(\"utf8\"))\n if !is_array(parts) or parts.length != 3 or parts[0] != channel or !is_string(parts[1]) or !is_string(parts[2])\n return null\n pattern = new RegExp(\"^(0|[1-9][0-9]{0,18})-(0|[1-9][0-9]{0,18})$\")\n if !pattern.test(parts[2]) or parts[2].length > 40\n return null\n return {\n generation: parts[1]\n id: parts[2]\n }\n catch error\n return null\n\nbounded(pending, ms)\n expired = Promise/withResolvers()\n fail = ()\n capture expired\n expired.reject(\"RedisUnavailable\")\n timer = setTimeout(fail, ms)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmHA;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;"}