@lango-project/lango-server 0.0.0-stage → 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 (134) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +710 -2
  4. package/dist/.lango/bignumber.mjs +3119 -0
  5. package/dist/.lango/runtime.mjs +683 -0
  6. package/dist/.lango/xmldom/conventions.js +429 -0
  7. package/dist/.lango/xmldom/dom-parser.js +591 -0
  8. package/dist/.lango/xmldom/dom.js +3759 -0
  9. package/dist/.lango/xmldom/entities.js +2171 -0
  10. package/dist/.lango/xmldom/errors.js +205 -0
  11. package/dist/.lango/xmldom/grammar.js +559 -0
  12. package/dist/.lango/xmldom/index.js +41 -0
  13. package/dist/.lango/xmldom/package.json +1 -0
  14. package/dist/.lango/xmldom/sax.js +983 -0
  15. package/dist/.lango/xmldom.LICENSE.md +8 -0
  16. package/dist/body_reader.mjs +179 -0
  17. package/dist/body_reader.mjs.map +1 -0
  18. package/dist/builder.mjs +84 -0
  19. package/dist/builder.mjs.map +1 -0
  20. package/dist/cli/.lango/bignumber.mjs +3119 -0
  21. package/dist/cli/.lango/runtime.mjs +683 -0
  22. package/dist/cli/.lango/xmldom/conventions.js +429 -0
  23. package/dist/cli/.lango/xmldom/dom-parser.js +591 -0
  24. package/dist/cli/.lango/xmldom/dom.js +3759 -0
  25. package/dist/cli/.lango/xmldom/entities.js +2171 -0
  26. package/dist/cli/.lango/xmldom/errors.js +205 -0
  27. package/dist/cli/.lango/xmldom/grammar.js +559 -0
  28. package/dist/cli/.lango/xmldom/index.js +41 -0
  29. package/dist/cli/.lango/xmldom/package.json +1 -0
  30. package/dist/cli/.lango/xmldom/sax.js +983 -0
  31. package/dist/cli/.lango/xmldom.LICENSE.md +8 -0
  32. package/dist/cli/body_reader.mjs +179 -0
  33. package/dist/cli/body_reader.mjs.map +1 -0
  34. package/dist/cli/database.mjs +101 -0
  35. package/dist/cli/database.mjs.map +1 -0
  36. package/dist/cli/database_options.mjs +83 -0
  37. package/dist/cli/database_options.mjs.map +1 -0
  38. package/dist/cli/database_scope.mjs +82 -0
  39. package/dist/cli/database_scope.mjs.map +1 -0
  40. package/dist/cli/endpoint.mjs +50 -0
  41. package/dist/cli/endpoint.mjs.map +1 -0
  42. package/dist/cli/longpoll_broker.mjs +214 -0
  43. package/dist/cli/longpoll_broker.mjs.map +1 -0
  44. package/dist/cli/longpoll_options.mjs +102 -0
  45. package/dist/cli/longpoll_options.mjs.map +1 -0
  46. package/dist/cli/longpoll_session.mjs +135 -0
  47. package/dist/cli/longpoll_session.mjs.map +1 -0
  48. package/dist/cli/middleware.mjs +25 -0
  49. package/dist/cli/middleware.mjs.map +1 -0
  50. package/dist/cli/options.mjs +177 -0
  51. package/dist/cli/options.mjs.map +1 -0
  52. package/dist/cli/postgres_adapter.mjs +166 -0
  53. package/dist/cli/postgres_adapter.mjs.map +1 -0
  54. package/dist/cli/routes.mjs +297 -0
  55. package/dist/cli/routes.mjs.map +1 -0
  56. package/dist/cli/server.mjs +792 -0
  57. package/dist/cli/server.mjs.map +1 -0
  58. package/dist/cli/sqlite_adapter.mjs +163 -0
  59. package/dist/cli/sqlite_adapter.mjs.map +1 -0
  60. package/dist/cli/static_files.mjs +125 -0
  61. package/dist/cli/static_files.mjs.map +1 -0
  62. package/dist/database.mjs +101 -0
  63. package/dist/database.mjs.map +1 -0
  64. package/dist/database_options.mjs +83 -0
  65. package/dist/database_options.mjs.map +1 -0
  66. package/dist/database_scope.mjs +82 -0
  67. package/dist/database_scope.mjs.map +1 -0
  68. package/dist/endpoint.mjs +50 -0
  69. package/dist/endpoint.mjs.map +1 -0
  70. package/dist/group.mjs +91 -0
  71. package/dist/group.mjs.map +1 -0
  72. package/dist/library.mjs +6 -0
  73. package/dist/library.mjs.map +1 -0
  74. package/dist/longpoll_broker.mjs +214 -0
  75. package/dist/longpoll_broker.mjs.map +1 -0
  76. package/dist/longpoll_options.mjs +102 -0
  77. package/dist/longpoll_options.mjs.map +1 -0
  78. package/dist/longpoll_session.mjs +135 -0
  79. package/dist/longpoll_session.mjs.map +1 -0
  80. package/dist/middleware.mjs +25 -0
  81. package/dist/middleware.mjs.map +1 -0
  82. package/dist/options.mjs +177 -0
  83. package/dist/options.mjs.map +1 -0
  84. package/dist/postgres_adapter.mjs +166 -0
  85. package/dist/postgres_adapter.mjs.map +1 -0
  86. package/dist/postgres_worker.mjs +119 -0
  87. package/dist/postgres_worker.mjs.map +1 -0
  88. package/dist/response.mjs +62 -0
  89. package/dist/response.mjs.map +1 -0
  90. package/dist/routes.mjs +297 -0
  91. package/dist/routes.mjs.map +1 -0
  92. package/dist/runtime.mjs +549 -0
  93. package/dist/runtime.mjs.map +1 -0
  94. package/dist/server.mjs +788 -0
  95. package/dist/server.mjs.map +1 -0
  96. package/dist/server_context.mjs +78 -0
  97. package/dist/server_context.mjs.map +1 -0
  98. package/dist/sqlite_adapter.mjs +163 -0
  99. package/dist/sqlite_adapter.mjs.map +1 -0
  100. package/dist/static_files.mjs +125 -0
  101. package/dist/static_files.mjs.map +1 -0
  102. package/dist/token.mjs +106 -0
  103. package/dist/token.mjs.map +1 -0
  104. package/dist/tokens.mjs +76 -0
  105. package/dist/tokens.mjs.map +1 -0
  106. package/dist/worker.mjs +57 -0
  107. package/dist/worker.mjs.map +1 -0
  108. package/package.json +44 -4
  109. package/src/body_reader.lango +113 -0
  110. package/src/builder.lango +64 -0
  111. package/src/database.lango +66 -0
  112. package/src/database_options.lango +57 -0
  113. package/src/database_scope.lango +59 -0
  114. package/src/endpoint.lango +30 -0
  115. package/src/group.lango +61 -0
  116. package/src/library.lango +10 -0
  117. package/src/longpoll.lua +61 -0
  118. package/src/longpoll_broker.lango +161 -0
  119. package/src/longpoll_options.lango +79 -0
  120. package/src/longpoll_session.lango +90 -0
  121. package/src/middleware.lango +10 -0
  122. package/src/options.lango +144 -0
  123. package/src/postgres_adapter.lango +138 -0
  124. package/src/postgres_worker.lango +114 -0
  125. package/src/response.lango +42 -0
  126. package/src/routes.lango +224 -0
  127. package/src/runtime.lango +382 -0
  128. package/src/server.lango +597 -0
  129. package/src/server_context.lango +58 -0
  130. package/src/sqlite_adapter.lango +127 -0
  131. package/src/static_files.lango +90 -0
  132. package/src/token.lango +70 -0
  133. package/src/tokens.lango +70 -0
  134. package/src/worker.lango +43 -0
package/README.md CHANGED
@@ -1,3 +1,711 @@
1
- # Temporary Holding Version
1
+ # Lango Server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A JSON HTTP server written in Lango. Its public package API contains two classes:
4
+ `Server` and `Builder`. Application handlers are exported functions identified by
5
+ module and function names. Each request runs in one worker; worker setup stays
6
+ inside the server.
7
+
8
+ This is a new package. It does not migrate or modify Lango API, UI, or Client.
9
+
10
+ ## Requirements and installation
11
+
12
+ Node.js 24 or later is required. Install the server in the application package:
13
+
14
+ ```sh
15
+ npm install @lango-project/lango-server
16
+ ```
17
+
18
+ Version 0.1.0 is currently prepared locally; this command requires publication.
19
+ For a local package archive, run `npm install /path/to/lango-project-lango-server-0.1.0.tgz`.
20
+
21
+ Keep application modules separate from the server launcher. Compile application
22
+ Lango sources before starting the server and expose the generated modules using
23
+ normal npm package exports. Linked packages work when their compiled exports
24
+ exist; the server does not compile, watch, or restart application code.
25
+
26
+ ## Standalone server
27
+
28
+ An application directory contains `package.json`, `routes.xml`, and `deploy.xml`.
29
+ Relative configuration file paths resolve against this directory. Module names
30
+ resolve using its npm dependencies.
31
+
32
+ ```sh
33
+ export LANGO_JWT_KEY='replace-with-a-random-secret-of-at-least-32-characters'
34
+ npx lango-server /path/to/application
35
+ ```
36
+
37
+ On Windows PowerShell, set `$env:LANGO_JWT_KEY` before running the same command.
38
+ Use a process manager, container, or service wrapper for deployment. The launcher
39
+ handles SIGINT and SIGTERM by awaiting `close()`; the library installs no signal
40
+ handlers. TLS and public web-server configuration belong to deployment.
41
+
42
+ `start()` resolves with `{ host, port }` after all workers have loaded and
43
+ validated their handlers and the HTTP listener is ready. Port zero selects an
44
+ available port. A second call rejects. Startup failures reject and release the
45
+ pool. `close()` is idempotent, stops accepting work, drains accepted requests,
46
+ and releases the listener and pool. A shutdown deadline forces closure and
47
+ rejects rather than silently reporting a graceful shutdown. Closing an unused
48
+ server is safe; a closed server cannot be restarted.
49
+
50
+ ## Application handlers
51
+
52
+ ```lango
53
+ export greet(input)
54
+
55
+ greet(input)
56
+ context token
57
+ context log
58
+ log.info("Greeting requested")
59
+ return {
60
+ message: "Hello, ${input.name}"
61
+ clientId: token.clientId
62
+ }
63
+ ```
64
+
65
+ The handler receives one JSON object. The server accepts POST requests with
66
+ `Content-Type: application/json`; query strings are not supported. Malformed
67
+ JSON, empty bodies, arrays, and primitive input values are rejected. This is an
68
+ RPC transport rather than a general-purpose HTTP framework.
69
+
70
+ A handler may return a Promise. Its resolved result is serialized with native
71
+ `JSON.stringify()` **inside the worker**, so a returned class can provide a
72
+ public `toJSON()` method. An omitted Lango return produces JSON null. Unserializable
73
+ results fail with HTTP 500. The result can be any JSON value, although ordinary
74
+ application handlers normally return objects. Serialization and handler failures
75
+ never publish token changes. Private exception details are not sent to clients.
76
+
77
+ A worker processes one request at a time, including its Promise and events.
78
+ Synchronous work does not block the main HTTP loop. Promise callbacks still use
79
+ Lango's explicit `capture` rules; capture any contexts needed by later callbacks.
80
+ Workers retain their loaded modules between requests. Module-level state is
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
+
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
+
117
+ ## Routes
118
+
119
+ ```xml
120
+ <routes>
121
+ <group path="/orders" module="@shop/orders">
122
+ <endpoint path="/save" handler="save"/>
123
+ <endpoint path="/list" handler="list"/>
124
+ </group>
125
+ <endpoint path="/login" module="@shop/auth" handler="login" auth="anonymous"/>
126
+ <include module="@shop/catalog" path="/catalog"/>
127
+ <event name="register" module="@shop/auth" handler="register"/>
128
+ <event name="validate" module="@shop/auth" handler="validate"/>
129
+ <event name="request" module="@shop/audit" handler="record"/>
130
+ </routes>
131
+ ```
132
+
133
+ * Every endpoint has a module and exported function name. A group can supply the
134
+ module and auth permission to its children. Includes inherit group auth as a
135
+ default; explicit permissions inside an included file still take precedence.
136
+ The including group does not supply handler modules across the package boundary. No handler is looked up in the
137
+ launcher module. Absolute or relative file modules are also accepted for
138
+ application-local code; relative modules in XML resolve from the containing
139
+ package, and Builder modules resolve from its application root.
140
+ * Groups concatenate path prefixes. Paths are case-sensitive. Exact paths win;
141
+ otherwise the longest matching trailing `/*` prefix wins. `/orders/*` matches
142
+ `/orders/save`, not `/orders`. Duplicate paths and unsupported wildcard forms
143
+ are startup errors. The handler sees the actual path in `context request`.
144
+ * Includes resolve the package's exported `./routes.xml`. Publish the XML file
145
+ and add it to the package's `exports` and `files`. Nested includes resolve
146
+ dependencies from the including package. Include prefixes concatenate; a
147
+ missing include path mounts at `/`. The same package can be mounted at several
148
+ prefixes. Include cycles, missing exports, and duplicate endpoints fail early.
149
+ * Included files contain routes only. They cannot register middleware, global lifecycle
150
+ events or change deployment/JWT settings. Events belong to the application's
151
+ root routes file (or Builder). Each event can be registered once.
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.
155
+
156
+ A feature package can expose its definitions as follows:
157
+
158
+ ```json
159
+ {
160
+ "name": "@shop/catalog",
161
+ "type": "module",
162
+ "exports": {
163
+ ".": "./dist/catalog.mjs",
164
+ "./routes.xml": "./routes.xml"
165
+ },
166
+ "files": ["dist/**", "routes.xml"]
167
+ }
168
+ ```
169
+
170
+ Its XML still names the handler module explicitly, for example
171
+ `<endpoint path="/list" module="@shop/catalog" handler="list"/>`.
172
+
173
+ ## Builder
174
+
175
+ ```lango
176
+ import js "@lango-project/lango-server" as server
177
+
178
+ createServer(root, signingKey)
179
+ builder = new server/Builder(root)
180
+ builder.configure({
181
+ host: "127.0.0.1"
182
+ port: 3000
183
+ key: signingKey
184
+ })
185
+ orders = builder.group({
186
+ path: "/orders"
187
+ module: "@shop/orders"
188
+ })
189
+ orders.endpoint({
190
+ path: "/save"
191
+ handler: "save"
192
+ })
193
+ builder.include({
194
+ module: "@shop/catalog"
195
+ path: "/catalog"
196
+ })
197
+ builder.event({
198
+ name: "validate"
199
+ module: "@shop/auth"
200
+ handler: "validate"
201
+ })
202
+ return builder.build()
203
+ ```
204
+
205
+ `Builder(root)` defaults to the current directory. `configure`, `addMiddleware`, `endpoint`,
206
+ `include`, and `event` return the Builder. `group` returns a group supporting
207
+ `endpoint`, nested `group`, and `include`; retain the Builder for `build()`.
208
+ The built Server snapshots definitions; later Builder changes do not affect it.
209
+ `new server/Server(directory)` is the XML equivalent. Routes, Endpoint, worker
210
+ classes, and token implementation classes are internal package details.
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
+
289
+ ## Configuration
290
+
291
+ ```xml
292
+ <deploy>
293
+ <http host="127.0.0.1" port="3000" bodyLimit="1048576" bodyTimeoutMs="30000"/>
294
+ <workers workers="2" maxQueue="64" requestTimeoutMs="30000"
295
+ startupTimeoutMs="30000" shutdownTimeoutMs="30000"/>
296
+ <events requestEvent="false" eventTimeoutMs="5000"/>
297
+ <jwt keyEnv="LANGO_JWT_KEY" issuer="shop" audience="shop-client" ttlSeconds="900"/>
298
+ </deploy>
299
+ ```
300
+
301
+ These are also the default values, apart from the required signing key and the
302
+ example issuer/audience (defaults: `lango-server` / `lango-client`). Builder uses
303
+ these attribute names directly in `configure`. Unknown options are errors.
304
+ `bodyLimit` is bytes; timeouts are milliseconds. Workers range from 1 to 128;
305
+ `maxQueue: 0` disables waiting. JWT lifetime is 1 to 86400 seconds.
306
+
307
+ For rotation, use `keysFile` instead of `keyEnv`, and select `activeKeyId`:
308
+
309
+ ```xml
310
+ <jwt keysFile="keys.json" activeKeyId="current" issuer="shop" audience="shop-client"/>
311
+ ```
312
+
313
+ The file is a JSON map of key IDs to secrets. Builder accepts `keys` and
314
+ `activeKeyId`, or a single `key` under the default `current` ID. Each secret must
315
+ contain at least 32 characters and should be cryptographically random. Only
316
+ HS256 is accepted; algorithm, key ID, issuer, audience, expiry, and server-owned
317
+ timestamps are checked. Keys are never generated or stored by the server.
318
+
319
+ ## Contexts and authorization
320
+
321
+ Handlers and events can declare `context request`, `response`, `token`, and `log`.
322
+ Request metadata is read-only: `id`, `method`, `path`, `headers`, `remoteAddress`.
323
+ Response supports `status(code)` and `header(name, value)`; the handler return
324
+ value supplies its JSON body. Transport/token headers remain server-owned.
325
+
326
+ Tokens arrive in `Authorization: Bearer <jwt>` and successful replies contain
327
+ `X-Lango-Token`. Missing tokens create an anonymous identity with a UUID
328
+ `clientId`. Invalid, expired, or incorrectly signed tokens yield 401 even on an
329
+ anonymous endpoint; they never silently create a replacement identity.
330
+ Unauthorized requests do not receive a newly created token.
331
+
332
+ `context token` supports:
333
+
334
+ * `clientId`, `auth`, `expiresAt`: identity, comma-separated permissions, expiry.
335
+ * `AddAuth("login")`, `clearAuth()`, `hasAuth("admin")`: exact trimmed membership.
336
+ * `get(name)`, `set(name, value)`: JSON custom claims; server-owned JWT fields are
337
+ protected. `get` returns a copy for structured values.
338
+
339
+ Default endpoint auth is `login`. `auth="anonymous"` permits anonymous callers;
340
+ other values require that exact permission. `admin` does not imply `login`.
341
+ The application authenticates credentials and grants permissions. These methods
342
+ do not authenticate anyone automatically.
343
+
344
+ Token updates are committed only after the handler and JSON serialization
345
+ succeed. Validation updates preserve the original token expiry. `clearAuth()`
346
+ updates the returned token; it does not invalidate previously issued copies.
347
+ Use application-owned storage and Validate to enforce logout/revocation across
348
+ old tokens. There is no built-in session database or UI replay protocol.
349
+
350
+ ## Events
351
+
352
+ Event modules and function names are strings, resolved during worker startup.
353
+ Promise results are supported, and events run under the request's contexts.
354
+
355
+ * **register(input)** runs for a tokenless request after assigning `clientId`,
356
+ before endpoint authorization. It can initialize custom token claims. Failure
357
+ prevents the handler and publishes no token. Return values are ignored; throw
358
+ or reject to fail registration. It is not an account-creation
359
+ guarantee: callers can omit tokens, so application side effects need their own
360
+ policy. No Register event is required.
361
+ * **validate(input)** receives null and runs after standard JWT verification
362
+ when the signed `validatedAt` is at least one second old. It receives a read-only
363
+ token. Only `true` continues; `false` produces 401. Exceptions, invalid return
364
+ types, mutation, or timeouts fail the request without running the handler;
365
+ operational failures are not reported as invalid credentials. Successful
366
+ validation updates the server-owned timestamp in the next successful reply.
367
+ Recent-token use does not advance it. If no event is configured, standard JWT
368
+ verification is sufficient. Revocation checks have a one-second freshness
369
+ allowance and depend on the application's storage consistency.
370
+ * **request(metadata)** is enabled only by `requestEvent: true`. It runs after
371
+ the handler completes and JSON serialization succeeds, before the reply is
372
+ sent. Metadata contains the original `input` JSON string, serialized `output`
373
+ JSON string, and HTTP `status`. It observes read-only metadata/token; response
374
+ mutation is unavailable. Event failure is logged and cannot change the
375
+ prepared result. The main process retains that result before invoking the
376
+ event, so even an event that blocks its worker can be terminated without losing
377
+ the successful response. Enabling this event exposes application input/output
378
+ to its configured handler; redact credentials and other sensitive fields there.
379
+
380
+ Each event has `eventTimeoutMs`. The request deadline covers queueing, Register,
381
+ Validate, and the handler; Request has its own event deadline after the result is
382
+ prepared. A hard timeout terminates the worker and the pool replaces it. Tasks
383
+ are never automatically retried: worker termination cannot roll back completed
384
+ external side effects. Client disconnect cancels queued/running work with the
385
+ same limitation. A full queue returns 503; request timeout returns 504; rejected
386
+ bodies return 400/408/413/415 as appropriate. Client error reporting and UI
387
+ Start/Ping events belong to other packages.
388
+
389
+ ## Development and verification
390
+
391
+ ```sh
392
+ npm ci
393
+ npm test
394
+ ```
395
+
396
+ All maintained implementation, tests, and tools are Lango. `dist` contains
397
+ generated JavaScript and is excluded from Git. `src/test` holds test code and
398
+ fixtures. Tests cover configuration, XML groups/includes, JWT/auth, real HTTP,
399
+ worker failures/deadlines, events, graceful shutdown, and an npm archive installed
400
+ into a separate consumer that runs the standalone server and shuts down on SIGTERM.
401
+ The package publishes only production sources/build output and documentation.
402
+
403
+ Run the repository example after building and installing its local dependency:
404
+
405
+ ```sh
406
+ npm run build
407
+ npm install --prefix examples/application --ignore-scripts
408
+ export LANGO_JWT_KEY='replace-with-a-random-secret-of-at-least-32-characters'
409
+ npm start
410
+ ```
411
+
412
+ ```sh
413
+ curl http://127.0.0.1:3000/demo/echo \
414
+ -H 'Content-Type: application/json' \
415
+ -d '{"message":"Hello"}'
416
+ ```
417
+
418
+ Prepare a publishable archive with `npm pack`. Publishing is a separate release
419
+ step; no package is published by the build or test commands.
420
+
421
+
422
+ ## SQL database configuration
423
+
424
+ Database configuration is optional. Configure one database per server through
425
+ `deploy.xml` or the equivalent `Builder.configure({ database: ... })` map:
426
+
427
+ ```xml
428
+ <database type="sqlite" file="data/application.sqlite"/>
429
+ ```
430
+
431
+ ```xml
432
+ <database type="postgresql" connectionEnv="APP_DATABASE_URL"/>
433
+ ```
434
+
435
+ SQLite paths resolve against the application directory; missing parent directories
436
+ are created. SQLite uses foreign keys, WAL, and a 5000 ms busy timeout by default.
437
+ WAL initialization happens before workers are started. `busyTimeoutMs` customizes
438
+ lock waiting; it is not a timeout for arbitrary SQLite query execution. `:memory:`
439
+ is allowed only with one worker, since each connection would otherwise get a
440
+ different database. Worker replacement loses in-memory data.
441
+
442
+ For PostgreSQL, `connectionEnv` names an environment variable containing a
443
+ `postgresql://` or `postgres://` connection URL, including any required SSL options.
444
+ Credentials are resolved at configuration time and are not logged. Defaults are
445
+ `queryTimeoutMs: 5000` (PostgreSQL `statement_timeout`) and
446
+ `connectTimeoutSeconds: 5`. These limits can be set as database attributes or map
447
+ fields. Database startup failures prevent the HTTP listener from opening.
448
+
449
+ ```lango
450
+ builder.configure({
451
+ database: {
452
+ type: "postgresql"
453
+ connectionEnv: "APP_DATABASE_URL"
454
+ queryTimeoutMs: 5000
455
+ }
456
+ })
457
+ ```
458
+
459
+ Each request worker owns one persistent connection. The server creates a fresh
460
+ DB scope before Register/Validate and keeps it available to the handler. Request
461
+ gets a separate clean scope after the handler result is serialized. Scopes cannot
462
+ be reused after completion. Physical connections are released on shutdown; worker
463
+ replacement discards the old connection and creates a new one. If DB configuration
464
+ is absent, SQL fails with `DatabaseNotConfigured` instead of borrowing an unrelated
465
+ default adapter.
466
+
467
+ Application code uses Lango SQL rather than a driver API:
468
+
469
+ ```lango
470
+ findCustomer(input)
471
+ context db
472
+ row = SQL
473
+ select id, name from customer where id = :id
474
+ row.id = input.id
475
+ row.execute()
476
+ if row.next()
477
+ return {
478
+ id: row.id
479
+ name: row.name
480
+ }
481
+ return null
482
+ ```
483
+
484
+ **Build all SQL application modules with lango-js 0.1.13 or newer.** SQL and
485
+ `start_trans()`, `commit_trans()`, `rollback_trans()`, `trans_state()` use the active
486
+ db context across separately compiled runtime copies. Promise callbacks that use
487
+ SQL should declare/capture db using the normal context capture rules.
488
+
489
+ Transactions are explicit. The server never implicitly commits a transaction.
490
+ An open transaction at successful scope completion is rolled back and reported as
491
+ an error; failure paths also roll back before connection reuse. Nested transactions
492
+ join the outer transaction and an inner rollback makes it rollback-only. PostgreSQL
493
+ failed-transaction state remains failed until rollback. A failing Request event
494
+ cannot roll back the already completed handler scope or change its prepared reply.
495
+ Previously committed writes are not undone by later serialization, token, network,
496
+ or event failures. Application-specific transactional guarantees remain explicit.
497
+
498
+ `:name` bindings are used for both engines. PostgreSQL positional binding conversion
499
+ preserves quotes, comments, dollar strings, and casts. Values are never interpolated
500
+ into SQL. Decimal parameters are exact text; use TEXT storage for exact decimals
501
+ in SQLite because its numeric affinity can convert values to floating point.
502
+ PostgreSQL numeric and int8 results remain strings by default. SQLite integers outside
503
+ the safe JavaScript integer range also return strings. Use SQL `RETURNING` for
504
+ portable generated-ID retrieval. SQL dialects and schema migrations are not translated.
505
+
506
+ PostgreSQL uses the standard pure JavaScript `pg` driver. A private helper thread
507
+ per request worker handles driver I/O while Lango SQL stays synchronous. This adds
508
+ no public API or worker configuration and requires no libpq headers, native compiler,
509
+ or pg-native installation. Closing or terminating the owner also releases its helper.
510
+
511
+ The database example uses SQL `RETURNING` and the same handler can run with either
512
+ engine. Its initial table creation is demonstration code; production migrations
513
+ should be managed by the application:
514
+
515
+ ```sh
516
+ npm run build
517
+ npm install --prefix examples/database --ignore-scripts
518
+ export LANGO_JWT_KEY='replace-with-a-random-secret-of-at-least-32-characters'
519
+ node dist/cli/server.mjs examples/database
520
+ ```
521
+
522
+ ```sh
523
+ curl http://127.0.0.1:3000/notes/save \
524
+ -H 'Content-Type: application/json' \
525
+ -d '{"message":"Stored through Lango SQL"}'
526
+ ```
527
+
528
+ `npm test` covers SQLite and a packed consumer with a SQL handler. To run the same
529
+ SQL/transaction suite plus PostgreSQL precision, timeout and connection-cleanup tests:
530
+
531
+ ```sh
532
+ LANGO_TEST_POSTGRES='postgresql://user:password@localhost/database' npm run test:postgres
533
+ ```
534
+
535
+ The tests create the `lango_server_items` table; use a dedicated test database. CI
536
+ runs SQLite first and PostgreSQL against an isolated PostgreSQL service.
537
+
538
+ ### Release order for this change
539
+
540
+ The server's development compiler dependency is now `^0.1.13`. Publish the prepared
541
+ lango-js 0.1.13 archive before running a fresh registry-based installation or CI,
542
+ then build/publish lango-server and rebuild application SQL modules. Local validation
543
+ uses the exact prepared compiler archive, without npm links; nothing is automatically
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.