@lango-project/lango-server 0.2.2 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +252 -29
- package/dist/.lango/runtime.mjs +16 -0
- package/dist/body_reader.mjs +15 -14
- package/dist/body_reader.mjs.map +1 -1
- package/dist/builder.mjs +26 -2
- package/dist/builder.mjs.map +1 -1
- package/dist/cli/.lango/runtime.mjs +16 -0
- package/dist/cli/body_reader.mjs +15 -14
- package/dist/cli/body_reader.mjs.map +1 -1
- package/dist/cli/client_identity.mjs +250 -0
- package/dist/cli/client_identity.mjs.map +1 -0
- package/dist/cli/database.mjs +23 -8
- package/dist/cli/database.mjs.map +1 -1
- package/dist/cli/database_scope.mjs +11 -0
- package/dist/cli/database_scope.mjs.map +1 -1
- package/dist/cli/endpoint.mjs +11 -7
- package/dist/cli/endpoint.mjs.map +1 -1
- package/dist/cli/longpoll_broker.mjs +9 -8
- package/dist/cli/longpoll_broker.mjs.map +1 -1
- package/dist/cli/longpoll_options.mjs +8 -7
- package/dist/cli/longpoll_options.mjs.map +1 -1
- package/dist/cli/longpoll_session.mjs +11 -10
- package/dist/cli/longpoll_session.mjs.map +1 -1
- package/dist/cli/middleware.mjs +1 -1
- package/dist/cli/middleware.mjs.map +1 -1
- package/dist/cli/options.mjs +41 -4
- package/dist/cli/options.mjs.map +1 -1
- package/dist/cli/origin.mjs +87 -0
- package/dist/cli/origin.mjs.map +1 -0
- package/dist/cli/policy.mjs +121 -0
- package/dist/cli/policy.mjs.map +1 -0
- package/dist/cli/postgres_adapter.mjs +15 -3
- package/dist/cli/postgres_adapter.mjs.map +1 -1
- package/dist/cli/routes.mjs +69 -18
- package/dist/cli/routes.mjs.map +1 -1
- package/dist/cli/server.mjs +88 -81
- package/dist/cli/server.mjs.map +1 -1
- package/dist/cli/static_files.mjs +5 -4
- package/dist/cli/static_files.mjs.map +1 -1
- package/dist/client_identity.mjs +250 -0
- package/dist/client_identity.mjs.map +1 -0
- package/dist/database.mjs +23 -8
- package/dist/database.mjs.map +1 -1
- package/dist/database_action.mjs +71 -0
- package/dist/database_action.mjs.map +1 -0
- package/dist/database_scope.mjs +11 -0
- package/dist/database_scope.mjs.map +1 -1
- package/dist/endpoint.mjs +11 -7
- package/dist/endpoint.mjs.map +1 -1
- package/dist/execution_failure.mjs +30 -0
- package/dist/execution_failure.mjs.map +1 -0
- package/dist/execution_identity.mjs +103 -0
- package/dist/execution_identity.mjs.map +1 -0
- package/dist/execution_log.mjs +47 -0
- package/dist/execution_log.mjs.map +1 -0
- package/dist/execution_runtime.mjs +201 -0
- package/dist/execution_runtime.mjs.map +1 -0
- package/dist/execution_worker.mjs +41 -0
- package/dist/execution_worker.mjs.map +1 -0
- package/dist/executor.mjs +384 -0
- package/dist/executor.mjs.map +1 -0
- package/dist/group.mjs +49 -16
- package/dist/group.mjs.map +1 -1
- package/dist/http_failure.mjs +9 -2
- package/dist/http_failure.mjs.map +1 -1
- package/dist/job_configuration.mjs +37 -0
- package/dist/job_configuration.mjs.map +1 -0
- package/dist/job_context.mjs +61 -0
- package/dist/job_context.mjs.map +1 -0
- package/dist/library.mjs +31 -0
- package/dist/library.mjs.map +1 -1
- package/dist/longpoll_broker.mjs +9 -8
- package/dist/longpoll_broker.mjs.map +1 -1
- package/dist/longpoll_options.mjs +8 -7
- package/dist/longpoll_options.mjs.map +1 -1
- package/dist/longpoll_session.mjs +11 -10
- package/dist/longpoll_session.mjs.map +1 -1
- package/dist/middleware.mjs +1 -1
- package/dist/middleware.mjs.map +1 -1
- package/dist/module_loader.mjs +44 -0
- package/dist/module_loader.mjs.map +1 -0
- package/dist/options.mjs +41 -4
- package/dist/options.mjs.map +1 -1
- package/dist/origin.mjs +87 -0
- package/dist/origin.mjs.map +1 -0
- package/dist/policy.mjs +121 -0
- package/dist/policy.mjs.map +1 -0
- package/dist/postgres_adapter.mjs +15 -3
- package/dist/postgres_adapter.mjs.map +1 -1
- package/dist/postgres_worker.mjs +82 -19
- package/dist/postgres_worker.mjs.map +1 -1
- package/dist/queue_provider.mjs +52 -0
- package/dist/queue_provider.mjs.map +1 -0
- package/dist/response.mjs +1 -1
- package/dist/response.mjs.map +1 -1
- package/dist/route_info.mjs +1 -1
- package/dist/route_info.mjs.map +1 -1
- package/dist/routes.mjs +69 -18
- package/dist/routes.mjs.map +1 -1
- package/dist/runtime.mjs +287 -132
- package/dist/runtime.mjs.map +1 -1
- package/dist/server.mjs +88 -81
- package/dist/server.mjs.map +1 -1
- package/dist/server_context.mjs +21 -9
- package/dist/server_context.mjs.map +1 -1
- package/dist/static_files.mjs +5 -4
- package/dist/static_files.mjs.map +1 -1
- package/dist/token.mjs +34 -7
- package/dist/token.mjs.map +1 -1
- package/dist/tokens.mjs +11 -2
- package/dist/tokens.mjs.map +1 -1
- package/dist/worker.mjs +7 -6
- package/dist/worker.mjs.map +1 -1
- package/docs/jobs.md +123 -0
- package/docs/security.md +420 -0
- package/examples/security/README.md +160 -0
- package/examples/security/deploy.xml +12 -0
- package/examples/security/handlers.lango +610 -0
- package/examples/security/package.json +19 -0
- package/examples/security/passwords.lango +61 -0
- package/examples/security/routes.xml +14 -0
- package/examples/security/schema.lango +91 -0
- package/examples/security/setup.lango +30 -0
- package/package.json +14 -6
- package/src/builder.lango +22 -0
- package/src/client_identity.lango +184 -0
- package/src/database.lango +15 -4
- package/src/database_action.lango +30 -0
- package/src/database_scope.lango +7 -0
- package/src/endpoint.lango +12 -5
- package/src/execution_failure.lango +14 -0
- package/src/execution_identity.lango +71 -0
- package/src/execution_log.lango +28 -0
- package/src/execution_runtime.lango +135 -0
- package/src/execution_worker.lango +32 -0
- package/src/executor.lango +284 -0
- package/src/group.lango +36 -21
- package/src/http_failure.lango +9 -5
- package/src/job_configuration.lango +29 -0
- package/src/job_context.lango +44 -0
- package/src/library.lango +21 -0
- package/src/longpoll_options.lango +11 -5
- package/src/middleware.lango +1 -1
- package/src/module_loader.lango +25 -0
- package/src/options.lango +41 -2
- package/src/origin.lango +56 -0
- package/src/policy.lango +84 -0
- package/src/postgres_adapter.lango +12 -0
- package/src/postgres_worker.lango +54 -3
- package/src/queue_provider.lango +30 -0
- package/src/response.lango +1 -1
- package/src/route_info.lango +2 -0
- package/src/routes.lango +74 -15
- package/src/runtime.lango +173 -94
- package/src/server.lango +9 -2
- package/src/server_context.lango +10 -2
- package/src/token.lango +26 -5
- package/src/tokens.lango +10 -3
package/dist/server.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./trace\"\n trace(message)\n responseLog(id, method, path, status)\nimport \"./longpoll_broker\"\n class LongpollBroker\nimport \"./longpoll_session\"\n class LongpollSession\nimport \"./database\"\n prepareDatabase(settings)\nimport \"./error_details\"\n errorDetails(error)\nimport js \"node:http\" as http\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js \"node:crypto\" as crypto\nimport js \"piscina\" as piscina\nimport js global process\nimport js global Promise\nimport js global Date\nimport js global Math\nimport js global Object\nimport js global Reflect\nimport js global AbortController\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./options\"\n deployment(directory)\nimport \"./routes\"\n class Routes\nimport \"./body_reader\"\n class BodyReader\nimport \"./static_files\"\n class StaticFiles\n\nexport main(args)\n\nexport class Server(path, definition = null)\n methods\n start()\n close()\n publish(path, key, data)\n cursor(path, key)\n\nServer(path, definition = null)\n if path != null\n directory = path\n routes = new Routes(directory)\n routes.xml(pathJoin(directory, \"routes.xml\"))\n definition = {\n settings: deployment(directory)\n routes: routes.definitions()\n events: routes.events()\n middlewares: routes.middlewares()\n }\n if definition == null\n throw \"Use Server(directory) or Builder.build()\"\n @definition = from_json(to_json(definition))\n @broker = new LongpollBroker(@definition.settings, @definition.routes)\n @polls = Object/create(null)\n @state = \"new\"\n @connections = []\n @server = null\n @pool = null\n @starting = null\n @closing = null\n @waiting = []\n @active = 0\n @tasks = Object/create(null)\n @ready = Promise/withResolvers()\n @readyIds = []\n @destroying = false\n @static = null\n\npathJoin(directory, file)\n return path/join(directory, file)\n\nServer:publish(path, key, data)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.publish(path, key, data)\n\nServer:cursor(path, key)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.cursor(path, key)\n\nServer:start()\n if @state != \"new\"\n return Promise/reject(\"Server can only be started once\")\n @state = \"starting\"\n @starting = launch()\n return @starting\n\nServer:launch()\n settings = @definition.settings\n trace(\"Server starting: ${settings.root}; workers=${settings.workers}\")\n if settings.static != null\n try\n @static = new StaticFiles(settings.static)\n catch error\n @state = \"closed\"\n return Promise/reject(error)\n return chain @broker.open()\n then(ignored)\n capture settings\n return prepareDatabase(settings.database)\n then(ignored)\n capture path\n capture modules\n capture settings\n resolver = modules/createRequire(path/join(settings.root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @pool = new piscina/Piscina({\n filename: path/join(path/dirname(entry), \"worker.mjs\")\n name: \"execute\"\n minThreads: settings.workers\n maxThreads: settings.workers\n maxQueue: settings.maxQueue\n concurrentTasksPerWorker: 1\n closeTimeout: settings.shutdownTimeoutMs\n workerData: @definition\n })\n pool = @pool\n pool.on(\"message\", (message)\n messageReceived(message)\n )\n pool.on(\"error\", (error)\n @ready.reject(error)\n context log\n log.err(\"Worker pool error: ${errorDetails(error)}\")\n )\n return startupDeadline(@ready.promise, settings.startupTimeoutMs)\n then(ignored)\n capture settings\n if @state != \"starting\"\n throw \"Server closed during startup\"\n server = new http/Server((req, res)\n receive(req, res)\n )\n @server = server\n server.on(\"connection\", (socket)\n connected(socket)\n )\n server.headersTimeout = settings.bodyTimeoutMs\n server.requestTimeout = settings.bodyTimeoutMs\n listening = new Promise((resolve, reject)\n capture server\n capture settings\n server.once(\"error\", reject)\n server.listen(settings.port, settings.host, ()\n capture server\n capture resolve\n capture reject\n server.removeListener(\"error\", reject)\n if @state != \"starting\"\n reject(\"Server closed during startup\")\n return null\n @state = \"running\"\n address = server.address()\n resolve({\n host: address.address\n port: address.port\n })\n )\n )\n return listening\n catch(error)\n @broker.close()\n @state = \"closed\"\n return chain destroyPool()\n then(ignored)\n capture error\n throw error\n\nstartupDeadline(pending, timeout)\n expired = Promise/withResolvers()\n expire = ()\n capture expired\n expired.reject(\"Worker startup timed out\")\n timer = setTimeout(expire, timeout)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n\nServer:messageReceived(message)\n if message.kind == \"longpoll\"\n brokerMessage(message)\n return null\n if message.kind == \"ready\"\n if !@readyIds.includes(message.threadId)\n @readyIds.add(message.threadId)\n if @readyIds.length >= @definition.settings.workers\n @ready.resolve(null)\n return null\n if !(message.id in @tasks)\n return null\n record = @tasks[message.id]\n if message.kind == \"prepared\"\n record.result = message.result\n record.logIdentity = message.logIdentity\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"event\"\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"handler\" and record.result == null\n resetDeadline(record, record.deadline - Date/now())\n return null\n\nServer:resetDeadline(record, duration)\n clearTimeout(record.timer)\n if record.result == null\n duration = Math/min(duration, record.deadline - Date/now())\n expired = ()\n capture record\n expire(record)\n record.timer = setTimeout(expired, Math/max(1, duration))\n return null\n\nServer:connected(socket)\n record = {\n socket: socket\n active: 0\n }\n @connections.add(record)\n socket.once(\"close\", ()\n capture record\n index = @connections.indexOf(record)\n if index >= 0\n @connections.splice(index, 1)\n )\n return null\n\nServer:trackResponse(req, res)\n target = req.url.split(\"?\")[0]\n for @connections as record\n if record.socket == req.socket\n record.active = record.active + 1\n state = {\n done: false\n }\n complete = ()\n capture record\n capture state\n capture req\n capture res\n capture target\n if state.done\n return null\n state.done = true\n if res.writableFinished\n responseLog(res.langoRequestId, req.method, target, res.statusCode)\n else\n trace(\"HTTP ${req.method} ${target} connection closed before response completed\")\n record.active = record.active - 1\n if @state == \"closing\" and record.active == 0\n record.socket.end()\n return null\n res.once(\"finish\", complete)\n res.once(\"close\", complete)\n return null\n return null\n\nServer:receive(req, res)\n trackResponse(req, res)\n req.on(\"error\", (error)\n return null\n )\n if @state != \"running\"\n return rejectHttp(req, res, 503, \"Unavailable\")\n trace(\"HTTP ${req.method} ${req.url.split('?')[0]}\")\n if @static != null and (req.method == \"GET\" or req.method == \"HEAD\")\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n return @static.receive(req, res, failed)\n if req.method != \"POST\"\n allowed = \"POST\"\n if @static != null\n allowed = \"GET, HEAD, POST\"\n res.setHeader(\"Allow\", allowed)\n return rejectHttp(req, res, 405, \"MethodNotAllowed\")\n if req.url.includes(\"?\") or req.url.includes(\"#\") or req.url.includes(\"\\\\\")\n return rejectHttp(req, res, 400, \"InvalidPath\")\n type = req.headers[\"content-type\"]\n media = \"\"\n if is_string(type)\n parts = type.split(\";\")\n media = parts[0].trim()\n if media.toLowerCase() != \"application/json\"\n return rejectHttp(req, res, 415, \"JsonRequired\")\n settings = @definition.settings\n if @active >= settings.workers and @waiting.length >= settings.maxQueue\n return rejectHttp(req, res, 503, \"QueueFull\")\n complete = (body)\n capture req\n capture res\n submit(req, res, body)\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n reader = new BodyReader(req, res, settings, complete, failed)\n reader.start()\n return null\n\nServer:submit(req, res, body)\n pending = null\n route = @broker.route(req.url)\n if route == null\n pending = dispatch(req, res, body)\n else\n pending = longpoll(req, res, body, route)\n return chain pending\n then(result)\n capture res\n send(res, result)\n return null\n catch(error)\n capture res\n capture req\n context log\n log.err(\"HTTP ${req.method} ${req.url.split('?')[0]} request failed: ${errorDetails(error)}\")\n send(res, failure(500, \"InternalServerError\"))\n return null\n\nServer:longpoll(req, res, body, route)\n if Object/keys(@polls).length >= @definition.settings.redis.maxPendingPolls\n return Promise/resolve(failure(503, \"PollLimit\"))\n authorize = (token, result)\n capture req\n capture res\n capture body\n return dispatch(req, res, body, true, token, result)\n session = new LongpollSession(@broker, route, authorize, body)\n id = crypto/randomUUID()\n @polls[id] = session\n disconnected = ()\n capture session\n session.cancel()\n res.once(\"close\", disconnected)\n return chain session.run()\n finally\n capture res\n capture disconnected\n capture id\n res.removeListener(\"close\", disconnected)\n Reflect/deleteProperty(@polls, id)\n\nServer:brokerMessage(message)\n port = message.port\n pending = null\n try\n switch message.operation\n case \"publish\"\n pending = publish(message.path, message.key, message.data)\n case \"cursor\"\n pending = cursor(message.path, message.key)\n else\n pending = Promise/reject(\"Unknown longpoll operation\")\n catch error\n pending = Promise/reject(error)\n return chain pending\n then(value)\n capture port\n brokerReply(port, {\n ok: true\n value: value\n })\n catch(error)\n capture port\n brokerReply(port, {\n ok: false\n })\n finally\n capture port\n port.close()\n\nServer:dispatch(req, res, body, authorize = false, token = null, pollResult = null)\n settings = @definition.settings\n if @state != \"running\" or (@active >= settings.workers and @waiting.length >= settings.maxQueue)\n return Promise/resolve(failure(503, \"Unavailable\"))\n id = crypto/randomUUID()\n res.langoRequestId = id\n trace(\"[${id}] Queued request ${req.method} ${req.url}\")\n record = {\n id: id\n task: {\n authorize: authorize\n pollResult: pollResult\n body: body\n request: {\n id: id\n method: req.method\n path: req.url\n headers: Object/assign({}, req.headers)\n remoteAddress: req.socket.remoteAddress\n }\n }\n completed: Promise/withResolvers()\n controller: new AbortController()\n started: false\n result: null\n expired: false\n deadline: Date/now() + settings.requestTimeoutMs\n timer: null\n }\n if token != null\n record.task.request.headers.authorization = \"Bearer ${token}\"\n @tasks[id] = record\n resetDeadline(record, settings.requestTimeoutMs)\n @waiting.add(record)\n disconnected = ()\n capture res\n capture record\n if !res.writableEnded\n cancel(record)\n res.once(\"close\", disconnected)\n pump()\n return chain record.completed.promise\n catch(error)\n capture record\n if record.expired\n return failure(504, \"RequestTimeout\")\n return failure(500, \"InternalServerError\")\n finally\n capture res\n capture disconnected\n res.removeListener(\"close\", disconnected)\n\nServer:expire(record)\n record.expired = true\n cancel(record)\n return null\n\nServer:cancel(record)\n if !(record.id in @tasks)\n return null\n if record.started\n record.controller.abort()\n else\n index = @waiting.indexOf(record)\n if index >= 0\n @waiting.splice(index, 1)\n finish(record, null, \"Request cancelled\")\n return null\n\nServer:pump()\n loop while !@destroying and @waiting.length > 0 and @active < @definition.settings.workers\n record = @waiting.shift()\n record.started = true\n @active = @active + 1\n trace(\"[${record.id}] Dispatching to worker\")\n pending = @pool.run(record.task, {\n signal: record.controller.signal\n })\n settle(record, pending)\n return null\n\nServer:settle(record, pending)\n return chain pending\n then(result)\n capture record\n finish(record, result, null)\n return null\n catch(error)\n capture record\n if record.result != null\n context log\n log.err(\"${record.logIdentity} Request event interrupted; preserving prepared result\")\n finish(record, record.result, error)\n return null\n finally\n @active = @active - 1\n pump()\n\nServer:finish(record, result, error)\n clearTimeout(record.timer)\n Reflect/deleteProperty(@tasks, record.id)\n if result != null\n record.completed.resolve(result)\n else\n record.completed.reject(error)\n return null\n\nServer:close()\n if @closing != null\n return @closing\n previous = @state\n @state = \"closing\"\n @shutdownDeadline = Date/now() + @definition.settings.shutdownTimeoutMs\n if previous == \"new\" or previous == \"closed\"\n @state = \"closed\"\n @closing = Promise/resolve(null)\n return @closing\n @ready.reject(\"Server closed during startup\")\n @closing = stop()\n return @closing\n\nServer:stop()\n for @connections as record\n if record.active == 0\n record.socket.destroy()\n for @polls as id: session\n session.cancel()\n drained = new Promise((resolve)\n server = @server\n if server == null or !server.listening\n resolve(null)\n else\n server.close(()\n capture resolve\n resolve(null)\n )\n )\n expired = Promise/withResolvers()\n force = ()\n capture expired\n @destroying = true\n for @waiting as record\n finish(record, null, \"Server closed\")\n @waiting = []\n if @server != null\n @server.closeAllConnections()\n expired.reject(\"Server shutdown timed out\")\n timer = setTimeout(force, @definition.settings.shutdownTimeoutMs)\n return chain Promise/race([drained, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n return destroyPool()\n finally\n @broker.close()\n @state = \"closed\"\n\nServer:destroyPool()\n @destroying = true\n if @pool == null\n return Promise/resolve(null)\n pool = @pool\n pending = Promise/resolve(null)\n if @definition.settings.database != null and @state == \"closing\" and @active == 0\n remaining = @shutdownDeadline - Date/now()\n if remaining > 0\n tasks = []\n for range(@definition.settings.workers) as index\n tasks.add(pool.run({\n close: true\n }))\n pending = startupDeadline(Promise/all(tasks), remaining)\n return chain pending\n finally\n capture pool\n return pool.destroy()\n\nServer:send(res, result)\n trace(\"HTTP response status=${result.status}\")\n if @state == \"closing\"\n result.headers.connection = \"close\"\n return write(res, result)\n\nfailure(status, code)\n return {\n status: status\n headers: {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n body: to_json({\n error: code\n })\n }\n\nwrite(res, result)\n if res.destroyed or res.writableEnded\n return null\n try\n res.writeHead(result.status, result.headers)\n res.end(result.body)\n catch error\n context log\n log.err(\"[${res.langoRequestId}] Response write failed: ${errorDetails(error)}\")\n res.destroy()\n return null\n\nrejectHttp(req, res, status, code)\n res.setHeader(\"Connection\", \"close\")\n res.once(\"finish\", ()\n capture req\n req.destroy()\n )\n req.resume()\n return write(res, failure(status, code))\n\nmain(args)\n directory = null\n verbose = false\n for args as arg\n if arg == \"--verbose\"\n verbose = true\n else\n if arg.startsWith(\"--\") or directory != null\n throw \"Usage: lango-server <application-directory> [--verbose]\"\n directory = arg\n if directory == null\n throw \"Usage: lango-server <application-directory> [--verbose]\"\n if verbose\n process.env.LANGO_VERBOSE = \"1\"\n trace(\"Loading server configuration: ${directory}\")\n server = new Server(directory)\n stop = ()\n capture server\n return chain server.close()\n catch(error)\n context log\n log.err(\"Server shutdown failed\")\n process.exitCode = 1\n process.once(\"SIGTERM\", stop)\n process.once(\"SIGINT\", stop)\n return chain server.start()\n then(address)\n context log\n log.info(\"Listening on ${address.host}:${address.port}\")\n return null\n catch(error)\n capture stop\n process.removeListener(\"SIGTERM\", stop)\n process.removeListener(\"SIGINT\", stop)\n throw error\n\nbrokerReply(port, message)\n try\n port.postMessage(message)\n catch error\n return null\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;AAqGA;;;;;;;;;;;;;;;;;AAiYA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;AAYA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./policy\"\n resolvePolicies(routes, registry)\nimport \"./trace\"\n trace(message)\n responseLog(id, method, path, status)\nimport \"./longpoll_broker\"\n class LongpollBroker\nimport \"./longpoll_session\"\n class LongpollSession\nimport \"./database\"\n prepareDatabase(settings, root = null, client = null)\nimport \"./error_details\"\n errorDetails(error)\nimport js \"node:http\" as http\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js \"node:crypto\" as crypto\nimport js \"piscina\" as piscina\nimport js global process\nimport js global Promise\nimport js global Date\nimport js global Math\nimport js global Object\nimport js global Reflect\nimport js global AbortController\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./options\"\n deployment(directory)\nimport \"./routes\"\n class Routes\nimport \"./body_reader\"\n class BodyReader\nimport \"./static_files\"\n class StaticFiles\n\nexport main(args)\n\nexport class Server(path, definition = null)\n methods\n start()\n close()\n publish(path, key, data)\n cursor(path, key)\n\nServer(path, definition = null)\n if path != null\n directory = path\n routes = new Routes(directory)\n routes.xml(pathJoin(directory, \"routes.xml\"))\n definition = {\n settings: deployment(directory)\n routes: routes.definitions()\n jobs: routes.jobs()\n events: routes.events()\n middlewares: routes.middlewares()\n }\n if definition == null\n throw \"Use Server(directory) or Builder.build()\"\n @definition = from_json(to_json(definition))\n settings = @definition.settings\n resolvePolicies(@definition.routes, settings.policies)\n if @definition.jobs != null\n resolvePolicies(@definition.jobs, settings.policies)\n @broker = new LongpollBroker(@definition.settings, @definition.routes)\n @polls = Object/create(null)\n @state = \"new\"\n @connections = []\n @server = null\n @pool = null\n @starting = null\n @closing = null\n @waiting = []\n @active = 0\n @tasks = Object/create(null)\n @ready = Promise/withResolvers()\n @readyIds = []\n @destroying = false\n @static = null\n\npathJoin(directory, file)\n return path/join(directory, file)\n\nServer:publish(path, key, data)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.publish(path, key, data)\n\nServer:cursor(path, key)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.cursor(path, key)\n\nServer:start()\n if @state != \"new\"\n return Promise/reject(\"Server can only be started once\")\n @state = \"starting\"\n @starting = launch()\n return @starting\n\nServer:launch()\n settings = @definition.settings\n trace(\"Server starting: ${settings.root}; workers=${settings.workers}\")\n if settings.static != null\n try\n @static = new StaticFiles(settings.static)\n catch error\n @state = \"closed\"\n return Promise/reject(error)\n return chain @broker.open()\n then(ignored)\n capture settings\n return prepareDatabase(settings.database, settings.root, settings.client)\n then(ignored)\n capture path\n capture modules\n capture settings\n resolver = modules/createRequire(path/join(settings.root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @pool = new piscina/Piscina({\n filename: path/join(path/dirname(entry), \"worker.mjs\")\n name: \"execute\"\n minThreads: settings.workers\n maxThreads: settings.workers\n maxQueue: settings.maxQueue\n concurrentTasksPerWorker: 1\n closeTimeout: settings.shutdownTimeoutMs\n workerData: @definition\n })\n pool = @pool\n pool.on(\"message\", (message)\n messageReceived(message)\n )\n pool.on(\"error\", (error)\n @ready.reject(error)\n context log\n log.err(\"Worker pool error: ${errorDetails(error)}\")\n )\n return startupDeadline(@ready.promise, settings.startupTimeoutMs)\n then(ignored)\n capture settings\n if @state != \"starting\"\n throw \"Server closed during startup\"\n server = new http/Server((req, res)\n receive(req, res)\n )\n @server = server\n server.on(\"connection\", (socket)\n connected(socket)\n )\n server.headersTimeout = settings.bodyTimeoutMs\n server.requestTimeout = settings.bodyTimeoutMs\n listening = new Promise((resolve, reject)\n capture server\n capture settings\n server.once(\"error\", reject)\n server.listen(settings.port, settings.host, ()\n capture server\n capture resolve\n capture reject\n server.removeListener(\"error\", reject)\n if @state != \"starting\"\n reject(\"Server closed during startup\")\n return null\n @state = \"running\"\n address = server.address()\n resolve({\n host: address.address\n port: address.port\n })\n )\n )\n return listening\n catch(error)\n @broker.close()\n @state = \"closed\"\n return chain destroyPool()\n then(ignored)\n capture error\n throw error\n\nstartupDeadline(pending, timeout)\n expired = Promise/withResolvers()\n expire = ()\n capture expired\n expired.reject(\"Worker startup timed out\")\n timer = setTimeout(expire, timeout)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n\nServer:messageReceived(message)\n if message.kind == \"longpoll\"\n brokerMessage(message)\n return null\n if message.kind == \"ready\"\n if !@readyIds.includes(message.threadId)\n @readyIds.add(message.threadId)\n if @readyIds.length >= @definition.settings.workers\n @ready.resolve(null)\n return null\n if !(message.id in @tasks)\n return null\n record = @tasks[message.id]\n if message.kind == \"prepared\"\n record.result = message.result\n record.logIdentity = message.logIdentity\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"event\"\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"handler\" and record.result == null\n resetDeadline(record, record.deadline - Date/now())\n return null\n\nServer:resetDeadline(record, duration)\n clearTimeout(record.timer)\n if record.result == null\n duration = Math/min(duration, record.deadline - Date/now())\n expired = ()\n capture record\n expire(record)\n record.timer = setTimeout(expired, Math/max(1, duration))\n return null\n\nServer:connected(socket)\n record = {\n socket: socket\n active: 0\n }\n @connections.add(record)\n socket.once(\"close\", ()\n capture record\n index = @connections.indexOf(record)\n if index >= 0\n @connections.splice(index, 1)\n )\n return null\n\nServer:trackResponse(req, res)\n target = req.url.split(\"?\")[0]\n for @connections as record\n if record.socket == req.socket\n record.active = record.active + 1\n state = {\n done: false\n }\n complete = ()\n capture record\n capture state\n capture req\n capture res\n capture target\n if state.done\n return null\n state.done = true\n if res.writableFinished\n responseLog(res.langoRequestId, req.method, target, res.statusCode)\n else\n trace(\"HTTP ${req.method} ${target} connection closed before response completed\")\n record.active = record.active - 1\n if @state == \"closing\" and record.active == 0\n record.socket.end()\n return null\n res.once(\"finish\", complete)\n res.once(\"close\", complete)\n return null\n return null\n\nServer:receive(req, res)\n trackResponse(req, res)\n req.on(\"error\", (error)\n return null\n )\n if @state != \"running\"\n return rejectHttp(req, res, 503, \"Unavailable\")\n trace(\"HTTP ${req.method} ${req.url.split('?')[0]}\")\n if @static != null and (req.method == \"GET\" or req.method == \"HEAD\")\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n return @static.receive(req, res, failed)\n if req.method != \"POST\"\n allowed = \"POST\"\n if @static != null\n allowed = \"GET, HEAD, POST\"\n res.setHeader(\"Allow\", allowed)\n return rejectHttp(req, res, 405, \"MethodNotAllowed\")\n if req.url.includes(\"?\") or req.url.includes(\"#\") or req.url.includes(\"\\\\\")\n return rejectHttp(req, res, 400, \"InvalidPath\")\n type = req.headers[\"content-type\"]\n media = \"\"\n if is_string(type)\n parts = type.split(\";\")\n media = parts[0].trim()\n if media.toLowerCase() != \"application/json\"\n return rejectHttp(req, res, 415, \"JsonRequired\")\n settings = @definition.settings\n if @active >= settings.workers and @waiting.length >= settings.maxQueue\n return rejectHttp(req, res, 503, \"QueueFull\")\n complete = (body)\n capture req\n capture res\n submit(req, res, body)\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n reader = new BodyReader(req, res, settings, complete, failed)\n reader.start()\n return null\n\nServer:submit(req, res, body)\n pending = null\n route = @broker.route(req.url)\n if route == null\n pending = dispatch(req, res, body)\n else\n pending = longpoll(req, res, body, route)\n return chain pending\n then(result)\n capture res\n send(res, result)\n return null\n catch(error)\n capture res\n capture req\n context log\n log.err(\"HTTP ${req.method} ${req.url.split('?')[0]} request failed: ${errorDetails(error)}\")\n send(res, failure(500, \"InternalServerError\"))\n return null\n\nServer:longpoll(req, res, body, route)\n if Object/keys(@polls).length >= @definition.settings.redis.maxPendingPolls\n return Promise/resolve(failure(503, \"PollLimit\"))\n authorize = (token, result)\n capture req\n capture res\n capture body\n return dispatch(req, res, body, true, token, result)\n session = new LongpollSession(@broker, route, authorize, body)\n id = crypto/randomUUID()\n @polls[id] = session\n disconnected = ()\n capture session\n session.cancel()\n res.once(\"close\", disconnected)\n return chain session.run()\n finally\n capture res\n capture disconnected\n capture id\n res.removeListener(\"close\", disconnected)\n Reflect/deleteProperty(@polls, id)\n\nServer:brokerMessage(message)\n port = message.port\n pending = null\n try\n switch message.operation\n case \"publish\"\n pending = publish(message.path, message.key, message.data)\n case \"cursor\"\n pending = cursor(message.path, message.key)\n else\n pending = Promise/reject(\"Unknown longpoll operation\")\n catch error\n pending = Promise/reject(error)\n return chain pending\n then(value)\n capture port\n brokerReply(port, {\n ok: true\n value: value\n })\n catch(error)\n capture port\n brokerReply(port, {\n ok: false\n })\n finally\n capture port\n port.close()\n\nServer:dispatch(req, res, body, authorize = false, token = null, pollResult = null)\n settings = @definition.settings\n if @state != \"running\" or (@active >= settings.workers and @waiting.length >= settings.maxQueue)\n return Promise/resolve(failure(503, \"Unavailable\"))\n id = crypto/randomUUID()\n res.langoRequestId = id\n trace(\"[${id}] Queued request ${req.method} ${req.url}\")\n record = {\n id: id\n task: {\n authorize: authorize\n pollResult: pollResult\n body: body\n request: {\n id: id\n method: req.method\n path: req.url\n headers: Object/assign({}, req.headers)\n remoteAddress: req.socket.remoteAddress\n }\n }\n completed: Promise/withResolvers()\n controller: new AbortController()\n started: false\n result: null\n expired: false\n deadline: Date/now() + settings.requestTimeoutMs\n timer: null\n }\n if token != null\n record.task.request.headers.authorization = \"Bearer ${token}\"\n @tasks[id] = record\n resetDeadline(record, settings.requestTimeoutMs)\n @waiting.add(record)\n disconnected = ()\n capture res\n capture record\n if !res.writableEnded\n cancel(record)\n res.once(\"close\", disconnected)\n pump()\n return chain record.completed.promise\n catch(error)\n capture record\n if record.expired\n return failure(504, \"RequestTimeout\")\n return failure(500, \"InternalServerError\")\n finally\n capture res\n capture disconnected\n res.removeListener(\"close\", disconnected)\n\nServer:expire(record)\n record.expired = true\n cancel(record)\n return null\n\nServer:cancel(record)\n if !(record.id in @tasks)\n return null\n if record.started\n record.controller.abort()\n else\n index = @waiting.indexOf(record)\n if index >= 0\n @waiting.splice(index, 1)\n finish(record, null, \"Request cancelled\")\n return null\n\nServer:pump()\n loop while !@destroying and @waiting.length > 0 and @active < @definition.settings.workers\n record = @waiting.shift()\n record.started = true\n @active = @active + 1\n trace(\"[${record.id}] Dispatching to worker\")\n pending = @pool.run(record.task, {\n signal: record.controller.signal\n })\n settle(record, pending)\n return null\n\nServer:settle(record, pending)\n return chain pending\n then(result)\n capture record\n finish(record, result, null)\n return null\n catch(error)\n capture record\n if record.result != null\n context log\n log.err(\"${record.logIdentity} Request event interrupted; preserving prepared result\")\n finish(record, record.result, error)\n return null\n finally\n @active = @active - 1\n pump()\n\nServer:finish(record, result, error)\n clearTimeout(record.timer)\n Reflect/deleteProperty(@tasks, record.id)\n if result != null\n record.completed.resolve(result)\n else\n record.completed.reject(error)\n return null\n\nServer:close()\n if @closing != null\n return @closing\n previous = @state\n @state = \"closing\"\n @shutdownDeadline = Date/now() + @definition.settings.shutdownTimeoutMs\n if previous == \"new\" or previous == \"closed\"\n @state = \"closed\"\n @closing = Promise/resolve(null)\n return @closing\n @ready.reject(\"Server closed during startup\")\n @closing = stop()\n return @closing\n\nServer:stop()\n for @connections as record\n if record.active == 0\n record.socket.destroy()\n for @polls as id: session\n session.cancel()\n drained = new Promise((resolve)\n server = @server\n if server == null or !server.listening\n resolve(null)\n else\n server.close(()\n capture resolve\n resolve(null)\n )\n )\n expired = Promise/withResolvers()\n force = ()\n capture expired\n @destroying = true\n for @waiting as record\n finish(record, null, \"Server closed\")\n @waiting = []\n if @server != null\n @server.closeAllConnections()\n expired.reject(\"Server shutdown timed out\")\n timer = setTimeout(force, @definition.settings.shutdownTimeoutMs)\n return chain Promise/race([drained, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n return destroyPool()\n finally\n @broker.close()\n @state = \"closed\"\n\nServer:destroyPool()\n @destroying = true\n if @pool == null\n return Promise/resolve(null)\n pool = @pool\n pending = Promise/resolve(null)\n if @definition.settings.database != null and @state == \"closing\" and @active == 0\n remaining = @shutdownDeadline - Date/now()\n if remaining > 0\n tasks = []\n for range(@definition.settings.workers) as index\n tasks.add(pool.run({\n close: true\n }))\n pending = startupDeadline(Promise/all(tasks), remaining)\n return chain pending\n finally\n capture pool\n return pool.destroy()\n\nServer:send(res, result)\n trace(\"HTTP response status=${result.status}\")\n if @state == \"closing\"\n result.headers.connection = \"close\"\n return write(res, result)\n\nfailure(status, code)\n return {\n status: status\n headers: {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n body: to_json({\n error: code\n })\n }\n\nwrite(res, result)\n if res.destroyed or res.writableEnded\n return null\n try\n res.writeHead(result.status, result.headers)\n res.end(result.body)\n catch error\n context log\n log.err(\"[${res.langoRequestId}] Response write failed: ${errorDetails(error)}\")\n res.destroy()\n return null\n\nrejectHttp(req, res, status, code)\n res.setHeader(\"Connection\", \"close\")\n res.once(\"finish\", ()\n capture req\n req.destroy()\n )\n req.resume()\n return write(res, failure(status, code))\n\nmain(args)\n directory = null\n verbose = false\n for args as arg\n if arg == \"--verbose\"\n verbose = true\n else\n if arg.startsWith(\"--\") or directory != null\n throw \"Usage: lango-server <application-directory> [--verbose]\"\n directory = arg\n if directory == null\n throw \"Usage: lango-server <application-directory> [--verbose]\"\n if verbose\n process.env.LANGO_VERBOSE = \"1\"\n trace(\"Loading server configuration: ${directory}\")\n server = new Server(directory)\n stop = ()\n capture server\n return chain server.close()\n catch(error)\n context log\n log.err(\"Server shutdown failed\")\n process.exitCode = 1\n process.once(\"SIGTERM\", stop)\n process.once(\"SIGINT\", stop)\n return chain server.start()\n then(address)\n context log\n log.info(\"Listening on ${address.host}:${address.port}\")\n return null\n catch(error)\n capture stop\n process.removeListener(\"SIGTERM\", stop)\n process.removeListener(\"SIGINT\", stop)\n throw error\n\nbrokerReply(port, message)\n try\n port.postMessage(message)\n catch error\n return null\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA;;;;;;;;AAqGA;;;;;;;;;;;;;;;;;AAiYA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;AAYA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;"}
|
package/dist/server_context.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import * as threads from "node:worker_threads";
|
|
|
3
3
|
import {
|
|
4
4
|
hostGlobal as __hostGlobal,
|
|
5
5
|
hostGlobalCall as __hostGlobalCall,
|
|
6
|
+
bindContexts as __bindContexts,
|
|
6
7
|
fromJson as __fromJson,
|
|
7
8
|
toJson as __toJson,
|
|
8
9
|
requireBoolean as __requireBoolean,
|
|
@@ -16,14 +17,25 @@ import {
|
|
|
16
17
|
export class ServerContext {
|
|
17
18
|
#routes;
|
|
18
19
|
#refresh;
|
|
19
|
-
|
|
20
|
+
#rotate;
|
|
21
|
+
constructor(definitions = null, refresh = null, rotate = null) {
|
|
20
22
|
definitions = __boundary(definitions);
|
|
21
23
|
refresh = __boundary(refresh);
|
|
24
|
+
rotate = __boundary(rotate);
|
|
22
25
|
if (__requireBoolean(definitions === null)) {
|
|
23
26
|
definitions = [];
|
|
24
27
|
}
|
|
25
28
|
this.#routes = routeInfo(definitions);
|
|
26
29
|
this.#refresh = refresh;
|
|
30
|
+
this.#rotate = rotate;
|
|
31
|
+
}
|
|
32
|
+
rotateClient() {
|
|
33
|
+
if (__requireBoolean(__normalize(this.#rotate) === null)) {
|
|
34
|
+
throw "Managed client identity is unavailable";
|
|
35
|
+
}
|
|
36
|
+
let rotate = __normalize(this.#rotate);
|
|
37
|
+
return __call(rotate, );
|
|
38
|
+
return null;
|
|
27
39
|
}
|
|
28
40
|
refreshTokens(tokens) {
|
|
29
41
|
__requireArity(arguments.length, [0], "refreshTokens");
|
|
@@ -64,10 +76,10 @@ function invoke(operation, path, key, data) {
|
|
|
64
76
|
let channel = new threads.MessageChannel();
|
|
65
77
|
let port = __normalize(channel.port1);
|
|
66
78
|
let remote = __normalize(channel.port2);
|
|
67
|
-
let pending = new (__hostGlobal(["Promise"]))(__withArity((resolve, reject) => {
|
|
79
|
+
let pending = new (__hostGlobal(["Promise"]))(__withArity(__bindContexts((resolve, reject) => {
|
|
68
80
|
resolve = __boundary(resolve);
|
|
69
81
|
reject = __boundary(reject);
|
|
70
|
-
__normalize(port.once("message", __withArity((message) => {
|
|
82
|
+
__normalize(port.once("message", __withArity(__bindContexts((message) => {
|
|
71
83
|
message = __boundary(message);
|
|
72
84
|
if (__requireBoolean(__normalize(message.ok))) {
|
|
73
85
|
__call(resolve, __normalize(message.value));
|
|
@@ -75,14 +87,14 @@ function invoke(operation, path, key, data) {
|
|
|
75
87
|
__call(reject, "Longpoll operation failed");
|
|
76
88
|
}
|
|
77
89
|
return null;
|
|
78
|
-
}, [0], "closure")));
|
|
90
|
+
}), [0], "closure")));
|
|
79
91
|
return null;
|
|
80
|
-
}, [0, 1], "closure"));
|
|
92
|
+
}), [0, 1], "closure"));
|
|
81
93
|
let expired = __normalize(__hostGlobal(["Promise"]).withResolvers());
|
|
82
|
-
let fail = () => {
|
|
94
|
+
let fail = __bindContexts(() => {
|
|
83
95
|
__normalize(expired.reject("Longpoll operation timed out"));
|
|
84
96
|
return null;
|
|
85
|
-
};
|
|
97
|
+
});
|
|
86
98
|
let timer = __hostGlobalCall(["setTimeout"], fail, 4000);
|
|
87
99
|
try {
|
|
88
100
|
__normalize(threads.parentPort.postMessage({ kind: "longpoll", operation: operation, path: path, key: key, data: __fromJson(__toJson(data)), port: remote }, [remote]));
|
|
@@ -91,11 +103,11 @@ function invoke(operation, path, key, data) {
|
|
|
91
103
|
__hostGlobalCall(["clearTimeout"], timer);
|
|
92
104
|
throw error;
|
|
93
105
|
}
|
|
94
|
-
return __normalize(__hostGlobal(["Promise"]).race([pending, __normalize(expired.promise)])).finally(() => {
|
|
106
|
+
return __normalize(__hostGlobal(["Promise"]).race([pending, __normalize(expired.promise)])).finally(__bindContexts(() => {
|
|
95
107
|
__hostGlobalCall(["clearTimeout"], timer);
|
|
96
108
|
__normalize(port.close());
|
|
97
109
|
return null;
|
|
98
|
-
});
|
|
110
|
+
}));
|
|
99
111
|
return null;
|
|
100
112
|
}
|
|
101
113
|
//# sourceMappingURL=server_context.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server_context.mjs","sources":["server_context.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./route_info\"\n routeInfo(definitions)\n\nexport class ServerContext(definitions = null, refresh = null)\n methods\n publish(path, key, data)\n cursor(path, key)\n routes()\n refreshTokens(tokens)\n\nServerContext(definitions = null, refresh = null)\n if definitions == null\n definitions = []\n @routes = routeInfo(definitions)\n @refresh = refresh\n\nServerContext:refreshTokens(tokens)\n if @refresh == null\n throw \"Token refresh is unavailable\"\n refresh = @refresh\n return refresh(tokens)\n\nServerContext:routes()\n return from_json(to_json(@routes))\n\nServerContext:publish(path, key, data)\n return invoke(\"publish\", path, key, data)\n\nServerContext:cursor(path, key)\n return invoke(\"cursor\", path, key, null)\n\ninvoke(operation, path, key, data)\n channel = new threads/MessageChannel()\n port = channel.port1\n remote = channel.port2\n pending = new Promise((resolve, reject)\n capture port\n port.once(\"message\", (message)\n capture resolve\n capture reject\n if message.ok\n resolve(message.value)\n else\n reject(\"Longpoll operation failed\")\n )\n )\n expired = Promise/withResolvers()\n fail = ()\n capture expired\n expired.reject(\"Longpoll operation timed out\")\n timer = setTimeout(fail, 4000)\n try\n threads/parentPort/postMessage({\n kind: \"longpoll\"\n operation: operation\n path: path\n key: key\n data: from_json(to_json(data))\n port: remote\n }, [remote])\n catch error\n port.close()\n clearTimeout(timer)\n throw error\n return chain Promise/race([pending, expired.promise])\n finally\n capture port\n capture timer\n clearTimeout(timer)\n port.close()\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"server_context.mjs","sources":["server_context.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./route_info\"\n routeInfo(definitions)\n\nexport class ServerContext(definitions = null, refresh = null, rotate = null)\n methods\n publish(path, key, data)\n cursor(path, key)\n routes()\n refreshTokens(tokens)\n rotateClient()\n\nServerContext(definitions = null, refresh = null, rotate = null)\n if definitions == null\n definitions = []\n @routes = routeInfo(definitions)\n @refresh = refresh\n @rotate = rotate\n\nServerContext:rotateClient()\n if @rotate == null\n throw \"Managed client identity is unavailable\"\n rotate = @rotate\n return rotate()\n\nServerContext:refreshTokens(tokens)\n if @refresh == null\n throw \"Token refresh is unavailable\"\n refresh = @refresh\n return refresh(tokens)\n\nServerContext:routes()\n return from_json(to_json(@routes))\n\nServerContext:publish(path, key, data)\n return invoke(\"publish\", path, key, data)\n\nServerContext:cursor(path, key)\n return invoke(\"cursor\", path, key, null)\n\ninvoke(operation, path, key, data)\n channel = new threads/MessageChannel()\n port = channel.port1\n remote = channel.port2\n pending = new Promise((resolve, reject)\n capture port\n port.once(\"message\", (message)\n capture resolve\n capture reject\n if message.ok\n resolve(message.value)\n else\n reject(\"Longpoll operation failed\")\n )\n )\n expired = Promise/withResolvers()\n fail = ()\n capture expired\n expired.reject(\"Longpoll operation timed out\")\n timer = setTimeout(fail, 4000)\n try\n threads/parentPort/postMessage({\n kind: \"longpoll\"\n operation: operation\n path: path\n key: key\n data: from_json(to_json(data))\n port: remote\n }, [remote])\n catch error\n port.close()\n clearTimeout(timer)\n throw error\n return chain Promise/race([pending, expired.promise])\n finally\n capture port\n capture timer\n clearTimeout(timer)\n port.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/static_files.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import * as files from "serve-static";
|
|
|
5
5
|
import {
|
|
6
6
|
hostGlobal as __hostGlobal,
|
|
7
7
|
hostGlobalCall as __hostGlobalCall,
|
|
8
|
+
bindContexts as __bindContexts,
|
|
8
9
|
isNumber as __isNumber,
|
|
9
10
|
isString as __isString,
|
|
10
11
|
isBool as __isBool,
|
|
@@ -79,11 +80,11 @@ export class StaticFiles {
|
|
|
79
80
|
}
|
|
80
81
|
}
|
|
81
82
|
}
|
|
82
|
-
let done = __withArity((error) => {
|
|
83
|
+
let done = __withArity(__bindContexts((error) => {
|
|
83
84
|
error = __boundary(error);
|
|
84
85
|
this.#failure(req, res, failed, error, decoded);
|
|
85
86
|
return null;
|
|
86
|
-
}, [0], "closure");
|
|
87
|
+
}), [0], "closure");
|
|
87
88
|
let serve = __normalize(this.#serve);
|
|
88
89
|
if (__requireBoolean(runtime)) {
|
|
89
90
|
serve = __normalize(this.#runtime);
|
|
@@ -125,11 +126,11 @@ export class StaticFiles {
|
|
|
125
126
|
}
|
|
126
127
|
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(status === 404) && __requireBoolean(pathname !== null)) && __requireBoolean(__normalize(this.#settings.fallback) !== null)) && __requireBoolean(!__requireBoolean(__normalize(pathname.startsWith("/.lango"))))) && __requireBoolean(__normalize(path.posix.extname(pathname)) === "")) && __requireBoolean(acceptsHTML(req.headers.accept)))) {
|
|
127
128
|
req.url = `/${__normalize(this.#settings.fallback)}`;
|
|
128
|
-
let done = __withArity((error) => {
|
|
129
|
+
let done = __withArity(__bindContexts((error) => {
|
|
129
130
|
error = __boundary(error);
|
|
130
131
|
this.#failure(req, res, failed, error);
|
|
131
132
|
return null;
|
|
132
|
-
}, [0], "closure");
|
|
133
|
+
}), [0], "closure");
|
|
133
134
|
let serve = __normalize(this.#serve);
|
|
134
135
|
__call(serve, req, res, done);
|
|
135
136
|
return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import \"./trace\"\n trace(message)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"serve-static\" as files\nimport js global RegExp\nimport js global decodeURIComponent\nimport js global String\n\nexport staticOptions(root, spec)\nexport class StaticFiles(settings)\n methods\n receive(req, res, failed)\n\nstaticOptions(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"static must be a map\"\n allowed = [\"path\", \"directory\", \"index\", \"fallback\", \"runtime\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown static option: ${key}\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n pattern = new RegExp(\"^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$\")\n if !is_string(mount) or !pattern.test(mount)\n throw \"Static path must be an absolute URL prefix\"\n if mount != \"/\" and mount.endsWith(\"/\")\n mount = mount.slice(0, -1)\n if !is_string(spec.directory) or spec.directory.trim() == \"\"\n throw \"Static directory is required\"\n index = spec.index\n if index == null\n index = \"index.html\"\n if !is_string(index) or index == \"\" or index.startsWith(\".\") or index.includes(\"/\") or index.includes(\"\\\\\")\n throw \"Static index must be a file name\"\n fallback = spec.fallback\n if fallback != null and (!is_string(fallback) or fallback == \"\" or fallback.startsWith(\".\") or fallback.includes(\"/\") or fallback.includes(\"\\\\\"))\n throw \"Static fallback must be a file name\"\n runtime = spec.runtime\n if runtime == null or runtime == \"false\"\n runtime = false\n if runtime == \"true\"\n runtime = true\n if !is_bool(runtime)\n throw \"Static runtime must be boolean\"\n return {\n path: mount\n directory: path/resolve(root, spec.directory)\n index: index\n fallback: fallback\n runtime: runtime\n }\n\nStaticFiles(settings)\n @settings = settings\n if !fs/statSync(settings.directory).isDirectory()\n throw \"Static directory must be a directory\"\n if settings.fallback != null and !fs/statSync(path/join(settings.directory, settings.fallback)).isFile()\n throw \"Static fallback must be a file\"\n @serve = files/default(settings.directory, {\n index: settings.index\n dotfiles: \"deny\"\n fallthrough: false\n redirect: false\n })\n @runtime = files/default(settings.directory, {\n index: false\n dotfiles: \"allow\"\n fallthrough: false\n redirect: false\n })\n\nStaticFiles:receive(req, res, failed)\n mount = @settings.path\n url = req.url\n pathname = url.split(\"?\")[0]\n if mount != \"/\" and pathname != mount and !pathname.startsWith(\"${mount}/\")\n failed(404, \"NotFound\")\n return null\n if mount != \"/\"\n req.url = url.slice(mount.length)\n if req.url == \"\" or req.url.startsWith(\"?\")\n req.url = \"/${req.url}\"\n local = req.url.split(\"?\")[0]\n decoded = null\n try\n decoded = decodeURIComponent(local)\n catch error\n failed(400, \"InvalidPath\")\n return null\n if decoded.includes(\"\\\\\") or decoded.includes(String/fromCharCode(0))\n failed(400, \"InvalidPath\")\n return null\n segments = decoded.split(\"/\")\n runtime = false\n for segments as index: segment\n if segment.startsWith(\".\")\n if index == 1 and segment == \".lango\" and @settings.runtime\n runtime = true\n else\n failed(403, \"Forbidden\")\n return null\n done = (error)\n capture req\n capture res\n capture failed\n capture decoded\n failure(req, res, failed, error, decoded)\n serve = @serve\n if runtime\n serve = @runtime\n trace(\"Static ${req.method} ${pathname}: directory=${@settings.directory}; index=${@settings.index}; runtime=${runtime}\")\n serve(req, res, done)\n return null\n\nStaticFiles:failure(req, res, failed, error, pathname = null)\n if res.headersSent\n res.destroy()\n return null\n status = 404\n code = \"NotFound\"\n if error != null\n switch error.status\n case 400\n status = 400\n code = \"InvalidPath\"\n case 403\n status = 403\n code = \"Forbidden\"\n case 416\n status = 416\n code = \"RangeNotSatisfiable\"\n case 404\n status = 404\n else\n status = 500\n code = \"InternalServerError\"\n if status == 404 and pathname != null and @settings.fallback != null and !pathname.startsWith(\"/.lango\") and path/posix/extname(pathname) == \"\" and acceptsHTML(req.headers.accept)\n req.url = \"/${@settings.fallback}\"\n done = (error)\n capture req\n capture res\n capture failed\n failure(req, res, failed, error)\n serve = @serve\n serve(req, res, done)\n return null\n failed(status, code)\n return null\n\nacceptsHTML(value)\n if !is_string(value)\n return false\n zero = new RegExp(\"^q\\\\s*=\\\\s*0(?:\\\\.0*)?$\", \"i\")\n for value.split(\",\") as range\n parts = range.split(\";\")\n media = parts[0]\n type = media.trim().toLowerCase()\n if type == \"text/html\" or type == \"application/xhtml+xml\"\n allowed = true\n for parts.slice(1) as parameter\n if zero.test(parameter.trim())\n allowed = false\n if allowed\n return true\n return false\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import \"./trace\"\n trace(message)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"serve-static\" as files\nimport js global RegExp\nimport js global decodeURIComponent\nimport js global String\n\nexport staticOptions(root, spec)\nexport class StaticFiles(settings)\n methods\n receive(req, res, failed)\n\nstaticOptions(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"static must be a map\"\n allowed = [\"path\", \"directory\", \"index\", \"fallback\", \"runtime\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown static option: ${key}\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n pattern = new RegExp(\"^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$\")\n if !is_string(mount) or !pattern.test(mount)\n throw \"Static path must be an absolute URL prefix\"\n if mount != \"/\" and mount.endsWith(\"/\")\n mount = mount.slice(0, -1)\n if !is_string(spec.directory) or spec.directory.trim() == \"\"\n throw \"Static directory is required\"\n index = spec.index\n if index == null\n index = \"index.html\"\n if !is_string(index) or index == \"\" or index.startsWith(\".\") or index.includes(\"/\") or index.includes(\"\\\\\")\n throw \"Static index must be a file name\"\n fallback = spec.fallback\n if fallback != null and (!is_string(fallback) or fallback == \"\" or fallback.startsWith(\".\") or fallback.includes(\"/\") or fallback.includes(\"\\\\\"))\n throw \"Static fallback must be a file name\"\n runtime = spec.runtime\n if runtime == null or runtime == \"false\"\n runtime = false\n if runtime == \"true\"\n runtime = true\n if !is_bool(runtime)\n throw \"Static runtime must be boolean\"\n return {\n path: mount\n directory: path/resolve(root, spec.directory)\n index: index\n fallback: fallback\n runtime: runtime\n }\n\nStaticFiles(settings)\n @settings = settings\n if !fs/statSync(settings.directory).isDirectory()\n throw \"Static directory must be a directory\"\n if settings.fallback != null and !fs/statSync(path/join(settings.directory, settings.fallback)).isFile()\n throw \"Static fallback must be a file\"\n @serve = files/default(settings.directory, {\n index: settings.index\n dotfiles: \"deny\"\n fallthrough: false\n redirect: false\n })\n @runtime = files/default(settings.directory, {\n index: false\n dotfiles: \"allow\"\n fallthrough: false\n redirect: false\n })\n\nStaticFiles:receive(req, res, failed)\n mount = @settings.path\n url = req.url\n pathname = url.split(\"?\")[0]\n if mount != \"/\" and pathname != mount and !pathname.startsWith(\"${mount}/\")\n failed(404, \"NotFound\")\n return null\n if mount != \"/\"\n req.url = url.slice(mount.length)\n if req.url == \"\" or req.url.startsWith(\"?\")\n req.url = \"/${req.url}\"\n local = req.url.split(\"?\")[0]\n decoded = null\n try\n decoded = decodeURIComponent(local)\n catch error\n failed(400, \"InvalidPath\")\n return null\n if decoded.includes(\"\\\\\") or decoded.includes(String/fromCharCode(0))\n failed(400, \"InvalidPath\")\n return null\n segments = decoded.split(\"/\")\n runtime = false\n for segments as index: segment\n if segment.startsWith(\".\")\n if index == 1 and segment == \".lango\" and @settings.runtime\n runtime = true\n else\n failed(403, \"Forbidden\")\n return null\n done = (error)\n capture req\n capture res\n capture failed\n capture decoded\n failure(req, res, failed, error, decoded)\n serve = @serve\n if runtime\n serve = @runtime\n trace(\"Static ${req.method} ${pathname}: directory=${@settings.directory}; index=${@settings.index}; runtime=${runtime}\")\n serve(req, res, done)\n return null\n\nStaticFiles:failure(req, res, failed, error, pathname = null)\n if res.headersSent\n res.destroy()\n return null\n status = 404\n code = \"NotFound\"\n if error != null\n switch error.status\n case 400\n status = 400\n code = \"InvalidPath\"\n case 403\n status = 403\n code = \"Forbidden\"\n case 416\n status = 416\n code = \"RangeNotSatisfiable\"\n case 404\n status = 404\n else\n status = 500\n code = \"InternalServerError\"\n if status == 404 and pathname != null and @settings.fallback != null and !pathname.startsWith(\"/.lango\") and path/posix/extname(pathname) == \"\" and acceptsHTML(req.headers.accept)\n req.url = \"/${@settings.fallback}\"\n done = (error)\n capture req\n capture res\n capture failed\n failure(req, res, failed, error)\n serve = @serve\n serve(req, res, done)\n return null\n failed(status, code)\n return null\n\nacceptsHTML(value)\n if !is_string(value)\n return false\n zero = new RegExp(\"^q\\\\s*=\\\\s*0(?:\\\\.0*)?$\", \"i\")\n for value.split(\",\") as range\n parts = range.split(\";\")\n media = parts[0]\n type = media.trim().toLowerCase()\n if type == \"text/html\" or type == \"application/xhtml+xml\"\n allowed = true\n for parts.slice(1) as parameter\n if zero.test(parameter.trim())\n allowed = false\n if allowed\n return true\n return false\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2IA;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/token.mjs
CHANGED
|
@@ -45,15 +45,15 @@ export class Token {
|
|
|
45
45
|
return __normalize(this.#expiresAt);
|
|
46
46
|
return null;
|
|
47
47
|
}
|
|
48
|
-
|
|
49
|
-
__requireArity(arguments.length, [0], "
|
|
48
|
+
addPolicy(permission) {
|
|
49
|
+
__requireArity(arguments.length, [0], "addPolicy");
|
|
50
50
|
permission = __boundary(permission);
|
|
51
51
|
this.#writable();
|
|
52
52
|
if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(permission))) || __requireBoolean(__normalize(permission.trim()) === "")) || __requireBoolean(__normalize(permission.includes(","))))) {
|
|
53
53
|
throw "Permission must be a nonempty name without commas";
|
|
54
54
|
}
|
|
55
55
|
permission = __normalize(permission.trim());
|
|
56
|
-
if (__requireBoolean(!__requireBoolean(this.
|
|
56
|
+
if (__requireBoolean(!__requireBoolean(this.hasPolicy(permission)))) {
|
|
57
57
|
if (__requireBoolean(__normalize(this.#auth) === "")) {
|
|
58
58
|
this.#auth = permission;
|
|
59
59
|
} else {
|
|
@@ -63,14 +63,14 @@ export class Token {
|
|
|
63
63
|
return this;
|
|
64
64
|
return null;
|
|
65
65
|
}
|
|
66
|
-
|
|
66
|
+
clearPolicies() {
|
|
67
67
|
this.#writable();
|
|
68
68
|
this.#auth = "";
|
|
69
69
|
return this;
|
|
70
70
|
return null;
|
|
71
71
|
}
|
|
72
|
-
|
|
73
|
-
__requireArity(arguments.length, [0], "
|
|
72
|
+
hasPolicy(permission) {
|
|
73
|
+
__requireArity(arguments.length, [0], "hasPolicy");
|
|
74
74
|
permission = __boundary(permission);
|
|
75
75
|
for (const name of __normalize(this.#auth.split(","))) {
|
|
76
76
|
if (__requireBoolean(__normalize(name.trim()) === permission)) {
|
|
@@ -80,6 +80,33 @@ export class Token {
|
|
|
80
80
|
return false;
|
|
81
81
|
return null;
|
|
82
82
|
}
|
|
83
|
+
get policies() {
|
|
84
|
+
let result = [];
|
|
85
|
+
for (const name of __normalize(this.#auth.split(","))) {
|
|
86
|
+
let value = __normalize(name.trim());
|
|
87
|
+
if (__requireBoolean(value !== "")) {
|
|
88
|
+
result.push(value);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return result;
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
AddAuth(permission) {
|
|
95
|
+
__requireArity(arguments.length, [0], "AddAuth");
|
|
96
|
+
permission = __boundary(permission);
|
|
97
|
+
return this.addPolicy(permission);
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
hasAuth(permission) {
|
|
101
|
+
__requireArity(arguments.length, [0], "hasAuth");
|
|
102
|
+
permission = __boundary(permission);
|
|
103
|
+
return this.hasPolicy(permission);
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
clearAuth() {
|
|
107
|
+
return this.clearPolicies();
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
83
110
|
get(name) {
|
|
84
111
|
__requireArity(arguments.length, [0], "get");
|
|
85
112
|
name = __boundary(name);
|
|
@@ -94,7 +121,7 @@ export class Token {
|
|
|
94
121
|
name = __boundary(name);
|
|
95
122
|
value = __boundary(value);
|
|
96
123
|
this.#writable();
|
|
97
|
-
if (__requireBoolean(contains(["clientId", "auth", "iat", "exp", "iss", "aud", "validatedAt", "nbf", "__proto__", "constructor", "prototype"], name))) {
|
|
124
|
+
if (__requireBoolean(contains(["clientProof", "clientId", "auth", "iat", "exp", "iss", "aud", "validatedAt", "nbf", "__proto__", "constructor", "prototype"], name))) {
|
|
98
125
|
throw `Reserved token field: ${name}`;
|
|
99
126
|
}
|
|
100
127
|
this.#claims[name] = __fromJson(__toJson(value));
|
package/dist/token.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token.mjs","sources":["token.lango"],"sourcesContent":["import \"./options\"\n contains(items, value)\nimport js global Object\n\nexport class Token(claims, readonly = false)\n properties\n clientId?\n auth?\n expiresAt?\n methods\n AddAuth(permission)\n clearAuth()\n hasAuth(permission)\n get(name)\n set(name, value)\n snapshot()\n renew()\n renewalRequested()\n\nToken(claims, readonly = false)\n @claims = from_json(to_json(claims))\n @readonly = readonly\n @renew = false\n @clientId = claims.clientId\n @auth = claims.auth\n @expiresAt = claims.exp\n Object/freeze(@this)\n\nToken:clientId?\n return @clientId\n\nToken:auth?\n return @auth\n\nToken:expiresAt?\n return @expiresAt\n\nToken:
|
|
1
|
+
{"version":3,"file":"token.mjs","sources":["token.lango"],"sourcesContent":["import \"./options\"\n contains(items, value)\nimport js global Object\n\nexport class Token(claims, readonly = false)\n properties\n clientId?\n auth?\n policies?\n expiresAt?\n methods\n addPolicy(permission)\n hasPolicy(permission)\n clearPolicies()\n AddAuth(permission)\n clearAuth()\n hasAuth(permission)\n get(name)\n set(name, value)\n snapshot()\n renew()\n renewalRequested()\n\nToken(claims, readonly = false)\n @claims = from_json(to_json(claims))\n @readonly = readonly\n @renew = false\n @clientId = claims.clientId\n @auth = claims.auth\n @expiresAt = claims.exp\n Object/freeze(@this)\n\nToken:clientId?\n return @clientId\n\nToken:auth?\n return @auth\n\nToken:expiresAt?\n return @expiresAt\n\nToken:addPolicy(permission)\n writable()\n if !is_string(permission) or permission.trim() == \"\" or permission.includes(\",\")\n throw \"Permission must be a nonempty name without commas\"\n permission = permission.trim()\n if !hasPolicy(permission)\n if @auth == \"\"\n @auth = permission\n else\n @auth = \"${@auth}, ${permission}\"\n return @this\n\nToken:clearPolicies()\n writable()\n @auth = \"\"\n return @this\n\nToken:hasPolicy(permission)\n for @auth.split(\",\") as name\n if name.trim() == permission\n return true\n return false\n\nToken:policies?\n result = []\n for @auth.split(\",\") as name\n value = name.trim()\n if value != \"\"\n result.add(value)\n return result\n\nToken:AddAuth(permission)\n return addPolicy(permission)\n\nToken:hasAuth(permission)\n return hasPolicy(permission)\n\nToken:clearAuth()\n return clearPolicies()\n\nToken:get(name)\n if !Object/hasOwn(@claims, name)\n return null\n return from_json(to_json(@claims[name]))\n\nToken:set(name, value)\n writable()\n if contains([\"clientProof\", \"clientId\", \"auth\", \"iat\", \"exp\", \"iss\", \"aud\", \"validatedAt\", \"nbf\", \"__proto__\", \"constructor\", \"prototype\"], name)\n throw \"Reserved token field: ${name}\"\n @claims[name] = from_json(to_json(value))\n return @this\n\nToken:snapshot()\n claims = from_json(to_json(@claims))\n if @clientId != claims.clientId or @expiresAt != claims.exp or !is_string(@auth)\n throw \"Token identity and expiry cannot be changed\"\n claims.auth = @auth\n return claims\n\nToken:renew()\n writable()\n @renew = true\n return @this\n\nToken:renewalRequested()\n return @renew\n\nToken:writable()\n if @readonly\n throw \"Token is read-only during this event\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/tokens.mjs
CHANGED
|
@@ -24,10 +24,19 @@ export class Tokens {
|
|
|
24
24
|
settings = __boundary(settings);
|
|
25
25
|
this.#settings = settings;
|
|
26
26
|
}
|
|
27
|
-
create() {
|
|
27
|
+
create(clientId = null) {
|
|
28
|
+
clientId = __boundary(clientId);
|
|
29
|
+
if (__requireBoolean(clientId === null)) {
|
|
30
|
+
clientId = __normalize(crypto.randomUUID());
|
|
31
|
+
} else {
|
|
32
|
+
let pattern = new (__hostGlobal(["RegExp"]))("^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$");
|
|
33
|
+
if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(clientId))) || __requireBoolean(!__requireBoolean(__normalize(pattern.test(clientId)))))) {
|
|
34
|
+
throw "Invalid server clientId";
|
|
35
|
+
}
|
|
36
|
+
}
|
|
28
37
|
let settings = __normalize(this.#settings);
|
|
29
38
|
let now = __normalize(__hostGlobal(["Math"]).floor(__finite(__normalize(__hostGlobal(["Date"]).now()) / 1000)));
|
|
30
|
-
return { clientId:
|
|
39
|
+
return { clientId: clientId, auth: "", iat: now, exp: __numericAdd(now, __normalize(settings.ttlSeconds)), iss: __normalize(settings.issuer), aud: __normalize(settings.audience), validatedAt: __normalize(__hostGlobal(["Date"]).now()) };
|
|
31
40
|
return null;
|
|
32
41
|
}
|
|
33
42
|
read(header) {
|
package/dist/tokens.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokens.mjs","sources":["tokens.lango"],"sourcesContent":["import js \"jsonwebtoken\" as jwt\nimport js \"node:crypto\" as crypto\nimport js global Object\nimport js global Date\nimport js global Math\nimport js global Number\n\nexport class Tokens(settings)\n methods\n read(header)\n sign(claims)\n create()\n renew(claims)\n\nTokens(settings)\n @settings = settings\n\nTokens:create()\n settings = @settings\n now = Math/floor(Date/now() / 1000)\n return {\n clientId:
|
|
1
|
+
{"version":3,"file":"tokens.mjs","sources":["tokens.lango"],"sourcesContent":["import js \"jsonwebtoken\" as jwt\nimport js \"node:crypto\" as crypto\nimport js global Object\nimport js global Date\nimport js global Math\nimport js global Number\nimport js global RegExp\n\nexport class Tokens(settings)\n methods\n read(header)\n sign(claims)\n create(clientId = null)\n renew(claims)\n\nTokens(settings)\n @settings = settings\n\nTokens:create(clientId = null)\n if clientId == null\n clientId = crypto/randomUUID()\n else\n pattern = new RegExp(\"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$\")\n if !is_string(clientId) or !pattern.test(clientId)\n throw \"Invalid server clientId\"\n settings = @settings\n now = Math/floor(Date/now() / 1000)\n return {\n clientId: clientId\n auth: \"\"\n iat: now\n exp: now + settings.ttlSeconds\n iss: settings.issuer\n aud: settings.audience\n validatedAt: Date/now()\n }\n\nTokens:read(header)\n settings = @settings\n if !is_string(header) or header.length > 16384 or header.slice(0, 7).toLowerCase() != \"bearer \" or header.length == 7\n throw \"InvalidToken\"\n encoded = header.slice(7)\n decoded = jwt/default/decode(encoded, {\n complete: true\n })\n if !is_object(decoded) or !is_object(decoded.header)\n throw \"InvalidToken\"\n head = decoded.header\n if head.alg != \"HS256\" or head.typ != \"JWT\" or !is_string(head.kid) or head.crit != null or head.b64 != null\n throw \"InvalidToken\"\n keys = settings.keys\n if !Object/hasOwn(keys, head.kid)\n throw \"InvalidToken\"\n claims = jwt/default/verify(encoded, keys[head.kid], {\n algorithms: [\"HS256\"]\n issuer: settings.issuer\n audience: settings.audience\n })\n if !is_object(claims) or !is_string(claims.clientId) or claims.clientId == \"\" or !is_string(claims.auth)\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.iat) or !Number/isSafeInteger(claims.exp) or claims.exp <= claims.iat or claims.exp - claims.iat > settings.ttlSeconds or claims.iat * 1000 > Date/now()\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.validatedAt) or claims.validatedAt < 0 or claims.validatedAt > Date/now()\n throw \"InvalidToken\"\n return claims\n\nTokens:renew(claims)\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n updated = from_json(to_json(claims))\n now = Math/floor(Date/now() / 1000)\n updated.iat = now\n updated.exp = now + @settings.ttlSeconds\n return updated\n\nTokens:sign(claims)\n settings = @settings\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n keys = settings.keys\n return jwt/default/sign(claims, keys[settings.activeKeyId], {\n algorithm: \"HS256\"\n header: {\n typ: \"JWT\"\n kid: settings.activeKeyId\n }\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/worker.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import * as threads from "node:worker_threads";
|
|
|
3
3
|
import {
|
|
4
4
|
hostGlobal as __hostGlobal,
|
|
5
5
|
hostGlobalCall as __hostGlobalCall,
|
|
6
|
+
bindContexts as __bindContexts,
|
|
6
7
|
requireBoolean as __requireBoolean,
|
|
7
8
|
normalize as __normalize,
|
|
8
9
|
boundary as __boundary,
|
|
@@ -15,13 +16,13 @@ let runtime = new Runtime(__normalize(threads.workerData));
|
|
|
15
16
|
export let execute = initialize();
|
|
16
17
|
function initialize() {
|
|
17
18
|
__normalize(__hostGlobal(["process"]).setSourceMapsEnabled(true));
|
|
18
|
-
return __normalize(runtime.preload()).then(__withArity((ignored) => {
|
|
19
|
+
return __normalize(runtime.preload()).then(__withArity(__bindContexts((ignored) => {
|
|
19
20
|
ignored = __boundary(ignored);
|
|
20
21
|
__normalize(threads.parentPort.postMessage({ kind: "ready", threadId: __normalize(threads.threadId) }));
|
|
21
22
|
registerCleanup();
|
|
22
23
|
return workerHandler();
|
|
23
24
|
return null;
|
|
24
|
-
}, [0], "closure"));
|
|
25
|
+
}), [0], "closure"));
|
|
25
26
|
return null;
|
|
26
27
|
}
|
|
27
28
|
|
|
@@ -31,11 +32,11 @@ function run(task) {
|
|
|
31
32
|
let pending;
|
|
32
33
|
if (__requireBoolean(__normalize(task.close) === true)) {
|
|
33
34
|
__normalize(runtime.close());
|
|
34
|
-
pending = new (__hostGlobal(["Promise"]))(__withArity((resolve) => {
|
|
35
|
+
pending = new (__hostGlobal(["Promise"]))(__withArity(__bindContexts((resolve) => {
|
|
35
36
|
resolve = __boundary(resolve);
|
|
36
37
|
__hostGlobalCall(["setTimeout"], resolve, 10);
|
|
37
38
|
return null;
|
|
38
|
-
}, [0], "closure"));
|
|
39
|
+
}), [0], "closure"));
|
|
39
40
|
return pending;
|
|
40
41
|
}
|
|
41
42
|
return __normalize(runtime.handle(task));
|
|
@@ -48,10 +49,10 @@ function workerHandler() {
|
|
|
48
49
|
}
|
|
49
50
|
|
|
50
51
|
function registerCleanup() {
|
|
51
|
-
__normalize(__hostGlobal(["process"]).once("exit", () => {
|
|
52
|
+
__normalize(__hostGlobal(["process"]).once("exit", __bindContexts(() => {
|
|
52
53
|
__normalize(runtime.close());
|
|
53
54
|
return null;
|
|
54
|
-
}));
|
|
55
|
+
})));
|
|
55
56
|
return null;
|
|
56
57
|
return null;
|
|
57
58
|
}
|
package/dist/worker.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker.mjs","sources":["worker.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global process\nimport js global setTimeout\nimport \"./runtime\"\n class Runtime\n\nexport global execute\n\nglobal runtime = new Runtime(threads.workerData)\nglobal execute = initialize()\n\ninitialize()\n global runtime\n process.setSourceMapsEnabled(true)\n return chain runtime.preload()\n then(ignored)\n capture threads\n threads/parentPort/postMessage({\n kind: \"ready\"\n threadId: threads.threadId\n })\n registerCleanup()\n return workerHandler()\n\nrun(task)\n global runtime\n if task.close == true\n runtime.close()\n pending = new Promise((resolve)\n setTimeout(resolve, 10)\n )\n return pending\n return runtime.handle(task)\n\nworkerHandler()\n return run\n\nregisterCleanup()\n process.once(\"exit\", ()\n global runtime\n runtime.close()\n )\n return null\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"worker.mjs","sources":["worker.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global process\nimport js global setTimeout\nimport \"./runtime\"\n class Runtime\n\nexport global execute\n\nglobal runtime = new Runtime(threads.workerData)\nglobal execute = initialize()\n\ninitialize()\n global runtime\n process.setSourceMapsEnabled(true)\n return chain runtime.preload()\n then(ignored)\n capture threads\n threads/parentPort/postMessage({\n kind: \"ready\"\n threadId: threads.threadId\n })\n registerCleanup()\n return workerHandler()\n\nrun(task)\n global runtime\n if task.close == true\n runtime.close()\n pending = new Promise((resolve)\n setTimeout(resolve, 10)\n )\n return pending\n return runtime.handle(task)\n\nworkerHandler()\n return run\n\nregisterCleanup()\n process.once(\"exit\", ()\n global runtime\n runtime.close()\n )\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;AASA;;AACA;AAEA;;;;;;;;;;;;AAaA;;;;;;;;;;;;;;;;;AAUA;;;;;AAGA;;;;;;;;;"}
|
package/docs/jobs.md
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# Internal job configuration
|
|
2
|
+
|
|
3
|
+
Server can describe internal job targets without exposing them over HTTP. Execution and queue integration belong to Lango Boss; Server has no dependency on that package.
|
|
4
|
+
|
|
5
|
+
```xml
|
|
6
|
+
<routes>
|
|
7
|
+
<job path="/reports/create"
|
|
8
|
+
module="@app/reports"
|
|
9
|
+
handler="createReport"
|
|
10
|
+
queue="reports"
|
|
11
|
+
policy="login"/>
|
|
12
|
+
</routes>
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Job targets require exact paths, a module, an exported handler name, and a queue name. Path parameters and wildcards are not supported for job targets. Duplicate job paths are rejected. Job and HTTP paths are separate namespaces.
|
|
16
|
+
|
|
17
|
+
Groups and npm route includes work as for endpoints. Jobs inherit group module, policy, and password freshness settings. Unknown attributes and nonempty job elements are rejected. `job` is reserved and cannot be registered as a custom HTTP middleware.
|
|
18
|
+
|
|
19
|
+
Programmatic configuration supports `builder.job(spec)` and `group.job(spec)`. Both return the receiving builder/group. Declaring a job does not start a worker or invoke its handler.
|
|
20
|
+
|
|
21
|
+
The package exports two synchronous configuration readers:
|
|
22
|
+
|
|
23
|
+
- `readDatabaseConfiguration(directory)` reads the application's `deploy.xml` and returns its normalized database settings, or null when no database is configured. Relative SQLite paths and PostgreSQL environment variables use the same rules as Server.
|
|
24
|
+
- `readJobRoutes(directory)` returns resolved internal job targets, including inherited policies and centrally configured password freshness requirements. It rejects unknown policies when a policy registry is present.
|
|
25
|
+
|
|
26
|
+
These readers do not start HTTP or open database connections. They validate JWT section structure but do not resolve JWT environment secrets or read signing-key files; HTTP deployment continues to resolve and validate those credentials normally. They still parse deployment XML and resolve modules from the application directory. A module's handler export is checked during execution preparation, not by these configuration readers.
|
|
27
|
+
|
|
28
|
+
The database reader returns a connection URL that may contain credentials. Treat its result as internal configuration and do not serialize or log it.
|
|
29
|
+
|
|
30
|
+
## HTTP-free executor
|
|
31
|
+
|
|
32
|
+
`new server/Executor(directory, settings)` prepares a separate worker pool for registered internal jobs. It reads the same database and job route configuration as the application, without starting an HTTP listener, JWT service, browser identity restoration, or HTTP lifecycle events.
|
|
33
|
+
|
|
34
|
+
```lango
|
|
35
|
+
import js "@lango-project/lango-server" as server
|
|
36
|
+
|
|
37
|
+
createExecutor(directory)
|
|
38
|
+
return new server/Executor(directory, {
|
|
39
|
+
identity: {
|
|
40
|
+
module: "@app/identity"
|
|
41
|
+
handler: "resolveExecutionIdentity"
|
|
42
|
+
}
|
|
43
|
+
workers: 2
|
|
44
|
+
maxQueue: 64
|
|
45
|
+
timeoutMs: 900000
|
|
46
|
+
startupTimeoutMs: 30000
|
|
47
|
+
shutdownTimeoutMs: 30000
|
|
48
|
+
})
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
`identity` is mandatory. Its exported function and every registered job handler are loaded before `start()` resolves. Worker count, queue capacity, and timeouts are independent of HTTP settings. All timeouts are milliseconds; `timeoutMs` includes time waiting in the executor's local queue. Closing stops admission, drains accepted work within the shutdown limit, and releases the pool. A second start is rejected; repeated close is safe.
|
|
52
|
+
|
|
53
|
+
`start()`, `execute(task)`, `authorize(task)`, and `close()` return Promises. The executor does not connect to pg-boss, retry jobs, create schedules, or automatically wrap a handler in a database transaction. Those responsibilities remain with the queue integration and application.
|
|
54
|
+
|
|
55
|
+
`execute(task, options)` additionally accepts an optional native `signal` (AbortSignal) and a positive `timeoutMs` override for this attempt. The override replaces the executor's default deadline; Boss uses trusted claimed-job expiration metadata. An already-aborted or subsequently aborted signal rejects with `ExecutionAborted` and `permanent: false`, and removes the signal listener when execution settles. Aborting a running task terminates its local worker; aborting queued work prevents its invocation.
|
|
56
|
+
|
|
57
|
+
### Trusted execution task
|
|
58
|
+
|
|
59
|
+
```lango
|
|
60
|
+
task = {
|
|
61
|
+
id: "job-id"
|
|
62
|
+
path: "/reports/create"
|
|
63
|
+
input: {
|
|
64
|
+
reportType: "daily"
|
|
65
|
+
}
|
|
66
|
+
attempt: 1
|
|
67
|
+
source: {
|
|
68
|
+
kind: "user"
|
|
69
|
+
clientId: "client-id"
|
|
70
|
+
userId: "user-id"
|
|
71
|
+
grantId: "grant-id"
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Only trusted host code may construct this envelope. Never forward an HTTP request body as an execution task. The eventual queue producer must derive `source` from trusted context; it must not accept identity or module selectors from job input.
|
|
77
|
+
|
|
78
|
+
`id` and a registered exact `path` are required. `input` must be a JSON map; `attempt` defaults to 1. Unknown task fields are rejected. The module, handler, queue, policy, and password freshness requirements come exclusively from the registered target.
|
|
79
|
+
|
|
80
|
+
A user source requires `clientId`. `userId` and `grantId` identify the original authenticated principal when present. An anonymous source omits them. Identity references are nonempty strings. A system source has only `kind: "system"` and `identity: "job_user"`; browser identity fields cannot be mixed into it. JWT, cookie, and client proof fields are rejected.
|
|
81
|
+
|
|
82
|
+
### Live identity provider
|
|
83
|
+
|
|
84
|
+
Each attempt invokes the configured provider once, in its database and job/log scope, before invoking the handler. Its argument is a map with:
|
|
85
|
+
|
|
86
|
+
- `source`: the trusted source references above.
|
|
87
|
+
- `route`: readonly `path`, `queue`, `policy`, and `reauthSeconds` metadata.
|
|
88
|
+
|
|
89
|
+
For a user source, return a map containing the same `clientId`, `userId`, and `grantId` references, a `policies` array, and optionally the real `authenticatedAt` timestamp in milliseconds. For a system source, return the matching `identity` profile and its explicit `policies`, without browser identity fields. Profile configuration and current permissions belong to application code; there is no implicit system administrator.
|
|
90
|
+
|
|
91
|
+
The provider must read current bans, revocations, grants, and permissions from the application's live data. Returning null or false rejects execution permanently. A provider exception is a temporary execution failure. A controlled rejection can use `job.reject(code)`. Missing provider exports fail preparation; an unknown profile must be rejected by the provider before a handler runs.
|
|
92
|
+
|
|
93
|
+
`authorize(task, options)` performs the same live identity, policy, and freshness checks as execution, then resolves with null without invoking the target handler or queue factory. It accepts the same task format and deadline/cancellation options. The identity provider sees `job.checking? == true` during this preflight and false during execution; it must apply the same authorization rules in both cases. Lango Boss uses this operation to validate scheduled system profiles before activating cron. Preflight success does not cache authority or grant future execution: every actual attempt is checked again.
|
|
94
|
+
|
|
95
|
+
Server verifies that identity references match the source, checks the target's current policy, and enforces its password freshness requirement. It never substitutes the current time for `authenticatedAt`, extends a browser JWT, creates a login challenge, or changes identity to the operator requesting a retry.
|
|
96
|
+
|
|
97
|
+
The resulting `context token` is readonly and exists only for the attempt. It supports normal token readers such as `get`, `hasPolicy`, and `policies?`. It is not a signed browser token and has no browser expiry or renewal lifecycle. HTTP applications can reuse the same application identity service; the executor does not replace or implicitly invoke the HTTP Validate event.
|
|
98
|
+
|
|
99
|
+
### Handler scope and outcomes
|
|
100
|
+
|
|
101
|
+
Handlers have a SQL database scope, a readonly execution token, a job context, and a log context. These contexts also reach nested Lango callbacks. HTTP request/response contexts are absent.
|
|
102
|
+
|
|
103
|
+
`context job` exposes readonly `id?`, `path?`, `queue?`, `attempt?`, `checking?`, and a copied `source?`. `job.reject("InvalidReport")` throws a controlled permanent rejection. Job log messages include job ID, path, queue, attempt, and source identity references. Input data and tokens are not automatically included in logs.
|
|
104
|
+
|
|
105
|
+
On success, `execute(task)` resolves with the serialized handler output. `false`, null, and objects containing fields such as `status: 401` are ordinary successful values. Cyclic or otherwise unsupported output is an execution failure. Open transactions are rolled back and rejected as `UnclosedTransaction`; explicit application commits remain committed even if later work fails.
|
|
106
|
+
|
|
107
|
+
On failure, `execute(task)` rejects with an Error. Controlled rejection codes, `IdentityRejected`, `IdentityChanged`, `Forbidden`, and `ReauthenticationRequired` have `permanent: true`. Handler/provider exceptions have `code: "ExecutionFailed"` and `permanent: false`; a deadline has `code: "ExecutionTimeout"` and `permanent: false`. Startup, admission, pool, and worker-crash errors also reject; callers must not infer success from a missing result or from a missing HTTP status.
|
|
108
|
+
|
|
109
|
+
Attempt deadlines abort the pool task and terminate blocking local code. The pool can replace a crashed or aborted worker. Pending database transactions are released when its connection closes; committed writes and external side effects cannot be undone. The executor provides no exactly-once guarantee.
|
|
110
|
+
|
|
111
|
+
## Queue provider integration
|
|
112
|
+
|
|
113
|
+
`withDatabase(directory, action)` opens the application's configured database, invokes `action()` in a SQL/context scope, waits for its return value or Promise, and closes the scope and connection. Lango callbacks inherit that scope. It does not start a transaction automatically: use normal SQL transaction functions when needed. Returning with an open transaction rolls it back and rejects with `UnclosedTransaction`; an exception also releases pending work. It creates no HTTP, token, or job scope, and should only be called by trusted host integration code. Boss uses it for atomic schedule reconciliation outside a handler.
|
|
114
|
+
|
|
115
|
+
`builder.provideQueue(spec)` registers a single trusted factory with `module`, `handler`, and optional JSON-map `options`. The module resolves from the application directory; its handler export is checked before listening. Duplicate provider registration and unknown fields are rejected. Boss uses this hook; Server does not import Boss.
|
|
116
|
+
|
|
117
|
+
The factory runs in the current database/token scope and returns a synchronous sender. Server supplies it as `context queue` before HTTP Register, Validate, middleware, and handler execution. Request events receive a new sender bound to their own audit database scope. A factory error fails handler preparation; an audit factory error is logged while preserving the prepared HTTP response.
|
|
118
|
+
|
|
119
|
+
Executor settings accept the same `queueProvider` descriptor. The factory runs after live identity and target authorization have succeeded and before the job handler runs. Nested Lango callbacks inherit the sender with the rest of their context.
|
|
120
|
+
|
|
121
|
+
The internal PostgreSQL scope exposes `db.invoke(spec, input)` for trusted integration code. The descriptor selects an application module and exported handler. Its asynchronous handler receives a native `executeSql(text, parameters)` adapter and the input, while application code waits synchronously through the existing database worker bridge. The adapter executes on the SQL scope's existing PostgreSQL client, including its current transaction; no second pool connection is substituted.
|
|
122
|
+
|
|
123
|
+
Database extensions must not open/close the client or issue their own transaction boundaries. The caller owns begin/commit/rollback. SQL errors mark the transaction failed even if an extension catches them. Extension lookup/application errors do not, by themselves, make a healthy client unusable. Closed scopes and non-PostgreSQL adapters reject invocation. Do not obtain extension descriptors from untrusted input.
|