@lango-project/lango-server 0.1.0 → 0.1.2

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 (80) hide show
  1. package/README.md +368 -10
  2. package/dist/builder.mjs +16 -1
  3. package/dist/builder.mjs.map +1 -1
  4. package/dist/cli/endpoint.mjs +8 -6
  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/route_pattern.mjs +129 -0
  17. package/dist/cli/route_pattern.mjs.map +1 -0
  18. package/dist/cli/routes.mjs +80 -4
  19. package/dist/cli/routes.mjs.map +1 -1
  20. package/dist/cli/server.mjs +243 -23
  21. package/dist/cli/server.mjs.map +1 -1
  22. package/dist/cli/static_files.mjs +125 -0
  23. package/dist/cli/static_files.mjs.map +1 -0
  24. package/dist/endpoint.mjs +8 -6
  25. package/dist/endpoint.mjs.map +1 -1
  26. package/dist/group.mjs +17 -1
  27. package/dist/group.mjs.map +1 -1
  28. package/dist/http_failure.mjs +45 -0
  29. package/dist/http_failure.mjs.map +1 -0
  30. package/dist/longpoll_broker.mjs +214 -0
  31. package/dist/longpoll_broker.mjs.map +1 -0
  32. package/dist/longpoll_options.mjs +102 -0
  33. package/dist/longpoll_options.mjs.map +1 -0
  34. package/dist/longpoll_session.mjs +135 -0
  35. package/dist/longpoll_session.mjs.map +1 -0
  36. package/dist/middleware.mjs +25 -0
  37. package/dist/middleware.mjs.map +1 -0
  38. package/dist/options.mjs +14 -2
  39. package/dist/options.mjs.map +1 -1
  40. package/dist/response.mjs +8 -0
  41. package/dist/response.mjs.map +1 -1
  42. package/dist/route_info.mjs +22 -0
  43. package/dist/route_info.mjs.map +1 -0
  44. package/dist/route_pattern.mjs +129 -0
  45. package/dist/route_pattern.mjs.map +1 -0
  46. package/dist/routes.mjs +80 -4
  47. package/dist/routes.mjs.map +1 -1
  48. package/dist/runtime.mjs +170 -59
  49. package/dist/runtime.mjs.map +1 -1
  50. package/dist/server.mjs +243 -23
  51. package/dist/server.mjs.map +1 -1
  52. package/dist/server_context.mjs +88 -0
  53. package/dist/server_context.mjs.map +1 -0
  54. package/dist/static_files.mjs +125 -0
  55. package/dist/static_files.mjs.map +1 -0
  56. package/dist/token.mjs +12 -0
  57. package/dist/token.mjs.map +1 -1
  58. package/dist/tokens.mjs +16 -1
  59. package/dist/tokens.mjs.map +1 -1
  60. package/package.json +9 -4
  61. package/src/builder.lango +11 -0
  62. package/src/endpoint.lango +10 -4
  63. package/src/group.lango +14 -0
  64. package/src/http_failure.lango +26 -0
  65. package/src/longpoll.lua +61 -0
  66. package/src/longpoll_broker.lango +161 -0
  67. package/src/longpoll_options.lango +79 -0
  68. package/src/longpoll_session.lango +90 -0
  69. package/src/middleware.lango +10 -0
  70. package/src/options.lango +16 -0
  71. package/src/response.lango +6 -0
  72. package/src/route_info.lango +15 -0
  73. package/src/route_pattern.lango +86 -0
  74. package/src/routes.lango +80 -4
  75. package/src/runtime.lango +113 -13
  76. package/src/server.lango +182 -17
  77. package/src/server_context.lango +66 -0
  78. package/src/static_files.lango +90 -0
  79. package/src/token.lango +11 -0
  80. package/src/tokens.lango +11 -1
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
@@ -103,20 +137,24 @@ worker-local, not shared or client-specific. An optional configured SQL database
103
137
  launcher module. Absolute or relative file modules are also accepted for
104
138
  application-local code; relative modules in XML resolve from the containing
105
139
  package, and Builder modules resolve from its application root.
106
- * Groups concatenate path prefixes. Paths are case-sensitive. Exact paths win;
107
- otherwise the longest matching trailing `/*` prefix wins. `/orders/*` matches
108
- `/orders/save`, not `/orders`. Duplicate paths and unsupported wildcard forms
109
- are startup errors. The handler sees the actual path in `context request`.
140
+ * Groups concatenate path prefixes. Paths are case-sensitive. Literal endpoints
141
+ beat parameterized endpoints, which beat trailing `/*` wildcards. Among matching
142
+ patterns in the same category, the first differing literal segment beats a
143
+ parameter; otherwise longer wildcard prefixes win. `/orders/*` matches
144
+ `/orders/save`, not `/orders`. Duplicate paths, equivalent parameter patterns
145
+ and unsupported wildcard forms are startup errors. The handler and middleware
146
+ see the original actual path in `context request`.
110
147
  * Includes resolve the package's exported `./routes.xml`. Publish the XML file
111
148
  and add it to the package's `exports` and `files`. Nested includes resolve
112
149
  dependencies from the including package. Include prefixes concatenate; a
113
150
  missing include path mounts at `/`. The same package can be mounted at several
114
151
  prefixes. Include cycles, missing exports, and duplicate endpoints fail early.
115
- * Included files contain routes only. They cannot register global lifecycle
152
+ * Included files contain routes only. They cannot register middleware, global lifecycle
116
153
  events or change deployment/JWT settings. Events belong to the application's
117
154
  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.
155
+ * Custom endpoint tags must name registered middleware. Unknown attributes are
156
+ rejected. XML and Builder definitions use the same endpoint validation and
157
+ startup loading path.
120
158
 
121
159
  A feature package can expose its definitions as follows:
122
160
 
@@ -135,6 +173,51 @@ A feature package can expose its definitions as follows:
135
173
  Its XML still names the handler module explicitly, for example
136
174
  `<endpoint path="/list" module="@shop/catalog" handler="list"/>`.
137
175
 
176
+ ### Path parameters
177
+
178
+ An endpoint can capture complete path segments with `{name}`:
179
+
180
+ ```lango
181
+ builder.endpoint({
182
+ path: "/user/{userId}"
183
+ module: "@shop/users"
184
+ handler: "read"
185
+ auth: "login"
186
+ })
187
+ ```
188
+
189
+ ```xml
190
+ <endpoint path="/user/{userId}" module="@shop/users" handler="read"/>
191
+ ```
192
+
193
+ A POST to `/user/007` with body `{ "name": "Ada", "userId": "body-value" }`
194
+ passes `{ name: "Ada", userId: "007" }` to the handler. URL parameters overwrite
195
+ same-named body fields and are available before Register, middleware and handler
196
+ execution. The JSON body must still be an object. Validate retains its existing
197
+ input contract; parameters are not added to request headers or route metadata.
198
+
199
+ Values are strings, never inferred as numbers. Each parameter consumes exactly
200
+ one nonempty raw segment and is percent-decoded exactly once after choosing the
201
+ winning route. `%20` becomes a space, `+` remains a plus, `%2F` becomes a slash
202
+ inside that value, and `%252F` becomes `%2F`. Invalid percent encoding in a captured
203
+ value produces HTTP 400 InvalidPath before application code runs. request.path
204
+ and the middleware path argument retain the original encoded path.
205
+
206
+ Multiple parameters, group prefixes, XML groups and npm include prefixes are
207
+ supported. A trailing wildcard can follow parameters (`/user/{userId}/*`);
208
+ no wildcard value is added to input. Query strings and path parameters remain
209
+ separate concepts; this feature does not change the existing POST query policy.
210
+
211
+ Parameter names are case-sensitive ASCII identifiers beginning with a letter or
212
+ underscore. A name must occupy an entire segment, occur only once in a route,
213
+ and cannot be __proto__, constructor or prototype. Routes such as `/user/{id}`
214
+ and `/user/{name}` have the same structure and cannot both be registered.
215
+ Overlapping structures with different literal positions are resolved from left
216
+ to right, independently of registration order. For example, `/choose/static/{id}`
217
+ beats `/choose/{id}/fixed` when both match `/choose/static/fixed`.
218
+
219
+ Longpoll channel and fallback paths remain exact and do not accept parameters.
220
+
138
221
  ## Builder
139
222
 
140
223
  ```lango
@@ -167,13 +250,104 @@ createServer(root, signingKey)
167
250
  return builder.build()
168
251
  ```
169
252
 
170
- `Builder(root)` defaults to the current directory. `configure`, `endpoint`,
253
+ `Builder(root)` defaults to the current directory. `configure`, `addMiddleware`, `endpoint`,
171
254
  `include`, and `event` return the Builder. `group` returns a group supporting
172
255
  `endpoint`, nested `group`, and `include`; retain the Builder for `build()`.
173
256
  The built Server snapshots definitions; later Builder changes do not affect it.
174
257
  `new server/Server(directory)` is the XML equivalent. Routes, Endpoint, worker
175
258
  classes, and token implementation classes are internal package details.
176
259
 
260
+ ## Route middleware
261
+
262
+ Middleware wraps an application handler inside its worker. Register an exported
263
+ function by module and export name before calling `build()`:
264
+
265
+ ```lango
266
+ builder.addMiddleware("ui", {
267
+ module: "@shop/middleware"
268
+ handler: "wrap"
269
+ })
270
+ builder.endpoint({
271
+ path: "/orders/save"
272
+ module: "@shop/orders"
273
+ handler: "save"
274
+ middleware: "ui"
275
+ })
276
+ ```
277
+
278
+ `Group.endpoint()` accepts the same optional `middleware` field. Omitting it or
279
+ setting it to `null` invokes the application handler directly; middleware is
280
+ not inherited from a group. An endpoint selects one middleware. The registration
281
+ name `ui` is application-defined; the server has no built-in UI dependency.
282
+
283
+ The XML equivalent uses a declaration in the application's root `routes.xml` and
284
+ the registered name as its endpoint tag:
285
+
286
+ ```xml
287
+ <routes>
288
+ <ui path="/orders/save" module="@shop/orders" handler="save"/>
289
+ <middleware name="ui" module="@shop/middleware" handler="wrap"/>
290
+ </routes>
291
+ ```
292
+
293
+ Declarations may appear before or after their routes. Custom tags support the
294
+ same path, module, handler and auth attributes as `endpoint`; group defaults,
295
+ wildcards and include prefixes apply normally. Included packages can use registered
296
+ middleware but cannot declare it, and declarations inside groups are rejected.
297
+ Registration names are server-wide. Duplicate registrations fail, including
298
+ duplicates across XML and programmatic registration on the same route collection.
299
+ Names must match `[A-Za-z_][A-Za-z0-9_-]*`. The names `routes`, `endpoint`,
300
+ `longpoll`, `group`, `include`, `event` and `middleware` are reserved. Longpoll
301
+ routes retain their own transport behavior and do not accept endpoint middleware.
302
+
303
+ Each worker loads and verifies all registered exports during startup, even unused
304
+ registrations. An unresolved module, missing/non-function export, or route using
305
+ unregistered middleware fails startup. No function or captured closure is
306
+ transferred from the main thread, and no per-request import is needed.
307
+
308
+ Middleware registrations may also specify `validate: "checkRoutes"` (or the XML
309
+ attribute `validate="checkRoutes"`). This names another export in the same
310
+ module, called once in each worker before listening with an independent route
311
+ metadata snapshot. It may return a Promise. A missing/non-function validator or
312
+ a thrown/rejected error fails startup. Validators run without request contexts;
313
+ they check configuration rather than handling requests.
314
+
315
+ Inside request handlers and middleware, `context server` also provides
316
+ `routes()`. It returns a fresh array of `{ path, kind, auth, middleware }` records,
317
+ where kind is `endpoint` or `longpoll`. Module paths and handler names are not
318
+ exposed. Mutating a snapshot cannot change routing. Startup validators receive
319
+ the same metadata shape, allowing libraries to discover their configured URLs
320
+ without introducing library-specific behavior into the server.
321
+
322
+ The middleware signature is `wrap(handler, path, input)`: `handler` is the resolved
323
+ application function, `path` is the actual request path including mounted prefixes,
324
+ and `input` is the decoded request object. For example, the registered module can
325
+ transform both synchronous and Promise results:
326
+
327
+ ```lango
328
+ import js global Promise
329
+
330
+ export wrap(handler, path, input)
331
+
332
+ wrap(handler, path, input)
333
+ return chain Promise/resolve(handler(input))
334
+ then(output)
335
+ capture path
336
+ return {
337
+ path: path
338
+ result: output
339
+ }
340
+ ```
341
+
342
+ Middleware runs after Register/Validate and route authorization, with the existing
343
+ request, response, token, log, db and server contexts. It can establish its own
344
+ contexts for the application handler; callbacks retain them using normal Lango
345
+ `capture` rules. It is responsible for invoking the application handler when
346
+ needed and returns the final result, which the server resolves and JSON-serializes
347
+ in the worker. Request events observe that final serialized result. Middleware,
348
+ handler and serialization errors follow the existing error/token behavior;
349
+ request/event deadlines and SQL transaction cleanup still apply.
350
+
177
351
  ## Configuration
178
352
 
179
353
  ```xml
@@ -208,8 +382,14 @@ timestamps are checked. Keys are never generated or stored by the server.
208
382
 
209
383
  Handlers and events can declare `context request`, `response`, `token`, and `log`.
210
384
  Request metadata is read-only: `id`, `method`, `path`, `headers`, `remoteAddress`.
211
- Response supports `status(code)` and `header(name, value)`; the handler return
212
- value supplies its JSON body. Transport/token headers remain server-owned.
385
+ Response supports `status(code)`, `header(name, value)` and `reject(status, code)`;
386
+ the handler return value supplies its JSON body. Transport/token headers remain
387
+ server-owned. `reject` throws a controlled HTTP failure (400–599) with a short
388
+ error code, for example `response.reject(400, "InvalidInput")`. Codes start with
389
+ an ASCII letter and contain at most 64 letters, digits or underscores. Configured
390
+ response headers are preserved. Rejections roll back open SQL transactions and
391
+ send `{ error: code }` without a token; committed side effects are not undone.
392
+ Unexpected exceptions still produce a generic 500.
213
393
 
214
394
  Tokens arrive in `Authorization: Bearer <jwt>` and successful replies contain
215
395
  `X-Lango-Token`. Missing tokens create an anonymous identity with a UUID
@@ -223,6 +403,8 @@ Unauthorized requests do not receive a newly created token.
223
403
  * `AddAuth("login")`, `clearAuth()`, `hasAuth("admin")`: exact trimmed membership.
224
404
  * `get(name)`, `set(name, value)`: JSON custom claims; server-owned JWT fields are
225
405
  protected. `get` returns a copy for structured values.
406
+ * `renew()`: requests renewal after successful serialization and SQL cleanup on
407
+ a reply with a status below 400. It does not immediately change `expiresAt`.
226
408
 
227
409
  Default endpoint auth is `login`. `auth="anonymous"` permits anonymous callers;
228
410
  other values require that exact permission. `admin` does not imply `login`.
@@ -235,6 +417,15 @@ updates the returned token; it does not invalidate previously issued copies.
235
417
  Use application-owned storage and Validate to enforce logout/revocation across
236
418
  old tokens. There is no built-in session database or UI replay protocol.
237
419
 
420
+ Renewal sets the new JWT's `iat` to the current second and `exp` to that value
421
+ plus `ttlSeconds`. Identity, permissions and custom claims are retained. The
422
+ timestamp of the last actual Validate result is preserved, so it may precede
423
+ the renewed token's issuance time. Renewal does not fake a fresh validation.
424
+ Read-only event tokens cannot request renewal. Expiration is checked again
425
+ before renewal and signing; an expired token cannot be revived. Failed or
426
+ rejected requests publish no renewal. Previously issued tokens remain valid
427
+ until their own expiry unless the application's Validate policy revokes them.
428
+
238
429
  ## Events
239
430
 
240
431
  Event modules and function names are strings, resolved during worker startup.
@@ -430,3 +621,170 @@ lango-js 0.1.13 archive before running a fresh registry-based installation or CI
430
621
  then build/publish lango-server and rebuild application SQL modules. Local validation
431
622
  uses the exact prepared compiler archive, without npm links; nothing is automatically
432
623
  published by these commands.
624
+
625
+ ## Long polling
626
+
627
+ Long polling uses Redis Streams for shared, retained history. Ordinary HTTP/SQL
628
+ applications do not connect to Redis. Applications declaring a longpoll route must
629
+ configure Redis; a missing configuration or unreachable Redis fails startup.
630
+ Redis 6.2 or newer is required. Use a single Redis endpoint (including a managed HA
631
+ endpoint); Redis Cluster and Sentinel discovery are not supported in this release.
632
+ All pods must use the same namespace, routes, JWT configuration and Redis database.
633
+ No sticky sessions are required.
634
+
635
+ ```xml
636
+ <!-- deploy.xml -->
637
+ <deploy>
638
+ <jwt keyEnv="APP_JWT_KEY"/>
639
+ <redis connectionEnv="REDIS_URL" namespace="my-app" maxPendingPolls="1024"/>
640
+ </deploy>
641
+ ```
642
+
643
+ ```xml
644
+ <!-- routes.xml -->
645
+ <routes>
646
+ <longpoll path="/updates" auth="login" waitTimeoutMs="20000"
647
+ retentionMs="300000" maxMessages="1000" fallback="/state"/>
648
+ </routes>
649
+ ```
650
+
651
+ The Builder equivalent is `builder.longpoll(options)` or
652
+ `group.longpoll(options)`. No module or handler is needed. Group and include
653
+ prefixes apply to both `path` and `fallback`; auth is inherited and defaults to
654
+ `login`. Paths must be exact absolute URL paths, without parameters, wildcards or query
655
+ strings. Duplicate paths conflict with endpoints as well as other longpoll routes.
656
+ The fallback is returned to the client; the server never calls it automatically.
657
+
658
+ Publish from any handler or event:
659
+
660
+ ```lango
661
+ notify(input)
662
+ context server
663
+ return chain server.publish("/updates", input.key, {
664
+ type: "changed"
665
+ value: input.value
666
+ })
667
+ then(cursor)
668
+ return {
669
+ cursor: cursor
670
+ }
671
+ ```
672
+
673
+ `server.publish(path, key, data)` resolves to an opaque cursor after Redis has
674
+ accepted the JSON message. `server.cursor(path, key)` resolves to the current
675
+ cursor without publishing. Both are also methods on the public `Server` instance
676
+ for application code outside workers. They require a running server and a declared
677
+ longpoll path. The framework does not expose a public HTTP publish endpoint.
678
+ Inside workers, `context server` forwards these calls to the main process.
679
+ Application URLs passed to these methods are the final mounted paths.
680
+
681
+ The key is an application-generated capability string, containing 1–1024 UTF-8
682
+ bytes. Use an unpredictable value and share it only with intended subscribers.
683
+ It is deliberately independent of `clientId`: all authorized subscribers sharing
684
+ a key receive the same messages. Route auth and JWT validation still apply.
685
+
686
+ ### HTTP protocol
687
+
688
+ Send JSON POST requests to the longpoll URL, with the usual Bearer token:
689
+
690
+ ```json
691
+ {"key":"application-generated-secret", "cursor":null}
692
+ ```
693
+
694
+ Omitting `cursor` or sending `null` starts at the oldest currently retained
695
+ message. It does not claim to recover messages removed before the subscription
696
+ started. To subscribe only to future changes, obtain an application-provided
697
+ `server.cursor()` value first. The application is responsible for coordinating
698
+ that cursor with its initial snapshot.
699
+
700
+ A successful response (HTTP 200) has this shape:
701
+
702
+ ```json
703
+ {
704
+ "messages": [{"id":"opaque-message-cursor", "data":{"value":42}}],
705
+ "cursor":"opaque-last-delivered-cursor",
706
+ "resyncRequired":false
707
+ }
708
+ ```
709
+
710
+ The usual `x-lango-token` response header carries the updated token. A normal wait
711
+ timeout returns HTTP 200 with `messages: []` and a continuation cursor. Send the
712
+ next request immediately. Only advance the stored cursor after processing the
713
+ messages successfully. Delivery can repeat; `messages[].id` supports deduplication.
714
+ Reading does not delete messages or consume another subscriber's share.
715
+
716
+ An expired/recreated channel, missing history, future position, malformed cursor
717
+ or cursor from another channel returns HTTP 409:
718
+
719
+ ```json
720
+ {"resyncRequired":true, "fallback":"/state"}
721
+ ```
722
+
723
+ `fallback` is `null` when unconfigured. No replacement cursor is silently issued.
724
+ Fetch a fresh snapshot through the application's normal authenticated endpoint,
725
+ then resume using the cursor accompanying that snapshot. A cursor identifies its
726
+ channel generation and Redis message ID; a pod restart alone does not invalidate it.
727
+ A cursor equal to the most recently trimmed message remains a valid continuation
728
+ if no later unseen message was removed.
729
+
730
+ Invalid poll input returns 400. Missing/invalid/expired credentials or insufficient
731
+ route permission return 401. Unavailable Redis, command timeout or shutdown while
732
+ waiting returns 503; exceeding the pending limit returns 503 `PollLimit`.
733
+ No token or advanced cursor is returned for infrastructure failures. Redis errors
734
+ never turn into successful empty responses or an in-memory history fallback.
735
+ Retry failures with backoff; abort the HTTP request when the subscription closes.
736
+
737
+ ### Waiting, limits and operations
738
+
739
+ Waiting HTTP requests stay in the main process and hold neither a worker nor a
740
+ request database scope. Short worker jobs run Register/Validate/auth before
741
+ waiting and validate again before message delivery, resync or normal timeout.
742
+ The existing one-second Validate freshness window applies; waiting never extends
743
+ JWT expiry. Request events run for completed poll responses using the normal
744
+ prepared-result behavior. Worker jobs retain the usual queue/deadline limits.
745
+
746
+ One shared, nonblocking Redis connection per Server reads pending subscriptions
747
+ at intervals of up to 250 ms. There is no connection per poll and no Pub/Sub
748
+ correctness dependency. A read immediately precedes waiting, so a publication
749
+ between reads is replayed from history. Command and startup Redis waits are bounded
750
+ to three seconds; reconnect attempts happen automatically. Disconnected requests
751
+ and shutdown release timers and pending subscriptions.
752
+
753
+ | Limit | Default | Supported range |
754
+ | --- | ---: | ---: |
755
+ | `waitTimeoutMs` | 20,000 | 1–60,000 ms |
756
+ | `retentionMs` | 300,000 | 1–86,400,000 ms |
757
+ | `maxMessages` per channel | 1,000 | 1–10,000 |
758
+ | Redis `maxPendingPolls` per Server | 1,024 | 1–10,000 |
759
+ | Key size | — | 1–1,024 UTF-8 bytes |
760
+ | Published JSON size | — | up to 262,144 UTF-8 bytes |
761
+ | Messages per response | — | up to 16 |
762
+ | Sum of message JSON bytes per response | — | up to 1,048,576 bytes |
763
+
764
+ JSON envelope and cursor bytes are additional to the response data limit. Normal
765
+ HTTP body limits also apply. Streams and metadata expire after an idle retention
766
+ period; reads do not keep unused channels alive. Publishing refreshes that expiry.
767
+ Age/count trimming and cursor checks execute atomically in a small Redis Lua
768
+ resource; framework code and worker integration are written in Lango. Channel
769
+ storage keys hash the namespace, URL and capability key. Configure Redis capacity,
770
+ eviction policy, persistence and HA for the application; eviction/lost history
771
+ requires resync. Keep retention comfortably above the polling/retry interval.
772
+
773
+ A publish timing out has an uncertain outcome: Redis may have accepted it. Retry
774
+ with application message identifiers if business-level deduplication is required.
775
+ SQL writes and Redis publication are separate operations. Use an application
776
+ outbox when they must reliably occur together. Likewise, reading a database
777
+ snapshot followed by the latest cursor is not an atomic snapshot protocol; use a
778
+ consistent application revision or replay-safe updates. Redis failover does not
779
+ provide a universal zero-data-loss guarantee.
780
+
781
+ Run the Redis integration suite against a **disposable** Redis database:
782
+
783
+ ```sh
784
+ npm run build
785
+ LANGO_TEST_REDIS=redis://127.0.0.1:6379 npm run test:longpoll
786
+ ```
787
+
788
+ The suite briefly pauses Redis commands to test infrastructure timeouts. Do not
789
+ point it at a shared or production Redis instance. CI runs this suite separately
790
+ 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,5 @@
1
+ import { routePattern } from "./route_pattern.mjs";
2
+ import { middlewareName } from "./middleware.mjs";
1
3
  import {
2
4
  isNumber as __isNumber,
3
5
  isString as __isString,
@@ -15,15 +17,11 @@ export class Endpoint {
15
17
  module;
16
18
  handler;
17
19
  auth;
20
+ middleware;
18
21
  constructor(spec) {
19
22
  __requireArity(arguments.length, [0], "constructor");
20
23
  spec = __boundary(spec);
21
- if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec.path)))) || __requireBoolean(!__requireBoolean(__normalize(spec.path.startsWith("/"))))) || __requireBoolean(__normalize(spec.path.includes("?")))) || __requireBoolean(__normalize(spec.path.includes("#")))) || __requireBoolean(__normalize(spec.path.includes("\\")))) || __requireBoolean(__normalize(spec.path.includes("//"))))) {
22
- throw "Endpoint requires an absolute URL path";
23
- }
24
- if (__requireBoolean(__requireBoolean(__normalize(spec.path.includes("*"))) && __requireBoolean(__requireBoolean(!__requireBoolean(__normalize(spec.path.endsWith("/*")))) || __requireBoolean(__normalize(spec.path.indexOf("*")) !== __normalize(spec.path.lastIndexOf("*")))))) {
25
- throw "Only trailing /* wildcards are supported";
26
- }
24
+ routePattern(__normalize(spec.path));
27
25
  for (const key of ["module", "handler"]) {
28
26
  if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(spec[key])))) || __requireBoolean(__normalize(spec[key]) === ""))) {
29
27
  throw `Endpoint requires ${key}`;
@@ -32,6 +30,10 @@ export class Endpoint {
32
30
  this.path = __normalize(spec.path);
33
31
  this.module = __normalize(spec.module);
34
32
  this.handler = __normalize(spec.handler);
33
+ this.middleware = __normalize(spec.middleware);
34
+ if (__requireBoolean(__normalize(this.middleware) !== null)) {
35
+ middlewareName(__normalize(this.middleware));
36
+ }
35
37
  this.auth = __normalize(spec.auth);
36
38
  if (__requireBoolean(__normalize(this.auth) === null)) {
37
39
  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 \"./route_pattern\"\n routePattern(path)\nimport \"./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 routePattern(spec.path)\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":";;;;;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}