@lango-project/lango-server 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +22 -3
  2. package/dist/body_reader.mjs.map +1 -1
  3. package/dist/builder.mjs +26 -2
  4. package/dist/builder.mjs.map +1 -1
  5. package/dist/cli/server.mjs +3 -835
  6. package/dist/cli/server.mjs.map +1 -1
  7. package/dist/client_identity.mjs.map +1 -1
  8. package/dist/database.mjs.map +1 -1
  9. package/dist/database_action.mjs +71 -0
  10. package/dist/database_action.mjs.map +1 -0
  11. package/dist/database_options.mjs.map +1 -1
  12. package/dist/database_scope.mjs +11 -0
  13. package/dist/database_scope.mjs.map +1 -1
  14. package/dist/endpoint.mjs.map +1 -1
  15. package/dist/error_details.mjs.map +1 -1
  16. package/dist/execution_failure.mjs +30 -0
  17. package/dist/execution_failure.mjs.map +1 -0
  18. package/dist/execution_identity.mjs +103 -0
  19. package/dist/execution_identity.mjs.map +1 -0
  20. package/dist/execution_log.mjs +47 -0
  21. package/dist/execution_log.mjs.map +1 -0
  22. package/dist/execution_runtime.mjs +201 -0
  23. package/dist/execution_runtime.mjs.map +1 -0
  24. package/dist/execution_worker.mjs +41 -0
  25. package/dist/execution_worker.mjs.map +1 -0
  26. package/dist/executor.mjs +384 -0
  27. package/dist/executor.mjs.map +1 -0
  28. package/dist/group.mjs +15 -0
  29. package/dist/group.mjs.map +1 -1
  30. package/dist/http_failure.mjs.map +1 -1
  31. package/dist/job_configuration.mjs +37 -0
  32. package/dist/job_configuration.mjs.map +1 -0
  33. package/dist/job_context.mjs +61 -0
  34. package/dist/job_context.mjs.map +1 -0
  35. package/dist/library.mjs +31 -0
  36. package/dist/library.mjs.map +1 -1
  37. package/dist/longpoll_broker.mjs.map +1 -1
  38. package/dist/longpoll_options.mjs.map +1 -1
  39. package/dist/longpoll_session.mjs.map +1 -1
  40. package/dist/middleware.mjs +1 -1
  41. package/dist/middleware.mjs.map +1 -1
  42. package/dist/module_loader.mjs +44 -0
  43. package/dist/module_loader.mjs.map +1 -0
  44. package/dist/options.mjs +12 -1
  45. package/dist/options.mjs.map +1 -1
  46. package/dist/origin.mjs.map +1 -1
  47. package/dist/policy.mjs.map +1 -1
  48. package/dist/postgres_adapter.mjs +12 -1
  49. package/dist/postgres_adapter.mjs.map +1 -1
  50. package/dist/postgres_worker.mjs +67 -5
  51. package/dist/postgres_worker.mjs.map +1 -1
  52. package/dist/queue_provider.mjs +52 -0
  53. package/dist/queue_provider.mjs.map +1 -0
  54. package/dist/request_identity.mjs.map +1 -1
  55. package/dist/response.mjs.map +1 -1
  56. package/dist/route_info.mjs.map +1 -1
  57. package/dist/route_pattern.mjs.map +1 -1
  58. package/dist/routes.mjs +36 -1
  59. package/dist/routes.mjs.map +1 -1
  60. package/dist/runtime.mjs +65 -25
  61. package/dist/runtime.mjs.map +1 -1
  62. package/dist/server.mjs +4 -1
  63. package/dist/server.mjs.map +1 -1
  64. package/dist/server_context.mjs.map +1 -1
  65. package/dist/sqlite_adapter.mjs.map +1 -1
  66. package/dist/static_files.mjs.map +1 -1
  67. package/dist/token.mjs.map +1 -1
  68. package/dist/tokens.mjs.map +1 -1
  69. package/dist/trace.mjs.map +1 -1
  70. package/dist/worker.mjs.map +1 -1
  71. package/docs/jobs.md +123 -0
  72. package/examples/security/package.json +1 -1
  73. package/package.json +10 -6
  74. package/src/builder.lango +22 -0
  75. package/src/database_action.lango +30 -0
  76. package/src/database_scope.lango +7 -0
  77. package/src/execution_failure.lango +14 -0
  78. package/src/execution_identity.lango +71 -0
  79. package/src/execution_log.lango +28 -0
  80. package/src/execution_runtime.lango +135 -0
  81. package/src/execution_worker.lango +32 -0
  82. package/src/executor.lango +284 -0
  83. package/src/group.lango +11 -0
  84. package/src/job_configuration.lango +29 -0
  85. package/src/job_context.lango +44 -0
  86. package/src/library.lango +21 -0
  87. package/src/middleware.lango +1 -1
  88. package/src/module_loader.lango +25 -0
  89. package/src/options.lango +7 -1
  90. package/src/postgres_adapter.lango +12 -0
  91. package/src/postgres_worker.lango +54 -3
  92. package/src/queue_provider.lango +30 -0
  93. package/src/routes.lango +44 -0
  94. package/src/runtime.lango +45 -17
  95. package/src/server.lango +3 -0
  96. package/dist/cli/.lango/bignumber.mjs +0 -3119
  97. package/dist/cli/.lango/localization.mjs +0 -108
  98. package/dist/cli/.lango/runtime.mjs +0 -725
  99. package/dist/cli/.lango/vendor/i18next.LICENSE +0 -21
  100. package/dist/cli/.lango/vendor/i18next.mjs +0 -2434
  101. package/dist/cli/.lango/xmldom/conventions.js +0 -429
  102. package/dist/cli/.lango/xmldom/dom-parser.js +0 -591
  103. package/dist/cli/.lango/xmldom/dom.js +0 -3759
  104. package/dist/cli/.lango/xmldom/entities.js +0 -2171
  105. package/dist/cli/.lango/xmldom/errors.js +0 -205
  106. package/dist/cli/.lango/xmldom/grammar.js +0 -559
  107. package/dist/cli/.lango/xmldom/index.js +0 -41
  108. package/dist/cli/.lango/xmldom/package.json +0 -1
  109. package/dist/cli/.lango/xmldom/sax.js +0 -983
  110. package/dist/cli/.lango/xmldom.LICENSE.md +0 -8
  111. package/dist/cli/body_reader.mjs +0 -180
  112. package/dist/cli/body_reader.mjs.map +0 -1
  113. package/dist/cli/client_identity.mjs +0 -250
  114. package/dist/cli/client_identity.mjs.map +0 -1
  115. package/dist/cli/database.mjs +0 -116
  116. package/dist/cli/database.mjs.map +0 -1
  117. package/dist/cli/database_options.mjs +0 -83
  118. package/dist/cli/database_options.mjs.map +0 -1
  119. package/dist/cli/database_scope.mjs +0 -82
  120. package/dist/cli/database_scope.mjs.map +0 -1
  121. package/dist/cli/endpoint.mjs +0 -50
  122. package/dist/cli/endpoint.mjs.map +0 -1
  123. package/dist/cli/error_details.mjs +0 -45
  124. package/dist/cli/error_details.mjs.map +0 -1
  125. package/dist/cli/longpoll_broker.mjs +0 -215
  126. package/dist/cli/longpoll_broker.mjs.map +0 -1
  127. package/dist/cli/longpoll_options.mjs +0 -103
  128. package/dist/cli/longpoll_options.mjs.map +0 -1
  129. package/dist/cli/longpoll_session.mjs +0 -136
  130. package/dist/cli/longpoll_session.mjs.map +0 -1
  131. package/dist/cli/middleware.mjs +0 -25
  132. package/dist/cli/middleware.mjs.map +0 -1
  133. package/dist/cli/options.mjs +0 -203
  134. package/dist/cli/options.mjs.map +0 -1
  135. package/dist/cli/origin.mjs +0 -87
  136. package/dist/cli/origin.mjs.map +0 -1
  137. package/dist/cli/policy.mjs +0 -121
  138. package/dist/cli/policy.mjs.map +0 -1
  139. package/dist/cli/postgres_adapter.mjs +0 -167
  140. package/dist/cli/postgres_adapter.mjs.map +0 -1
  141. package/dist/cli/route_pattern.mjs +0 -129
  142. package/dist/cli/route_pattern.mjs.map +0 -1
  143. package/dist/cli/routes.mjs +0 -325
  144. package/dist/cli/routes.mjs.map +0 -1
  145. package/dist/cli/sqlite_adapter.mjs +0 -163
  146. package/dist/cli/sqlite_adapter.mjs.map +0 -1
  147. package/dist/cli/static_files.mjs +0 -224
  148. package/dist/cli/static_files.mjs.map +0 -1
  149. package/dist/cli/trace.mjs +0 -53
  150. package/dist/cli/trace.mjs.map +0 -1
@@ -1 +1 @@
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 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 @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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA;;;;;;;;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":"","x_lango_build":{"fingerprint":"de62ec88f0ec0c1235f608ebf68a0e8fbac4703b820109cf2afb7e5a649217d1","outputHash":"6b6f36fe1077a8d61a692cb806bc036070d08a4f5cbfa63494d0ef1fa764b92c","mapHash":"b81357c91558d8cbb05368d0cf2fa638f64d45381b8f8ca53ef1dfce717c0ead"}}
@@ -1 +1 @@
1
- {"version":3,"file":"client_identity.mjs","sources":["client_identity.lango"],"sourcesContent":["import js \"node:crypto\" as crypto\nimport js global Date\nimport js global Object\nimport js global Number\nimport js global RegExp\nimport js global Buffer\n\nexport clientOptions(spec, database, origin)\nexport class ClientIdentity(settings, database)\n methods\n initialize()\n begin(claims, tokens)\n publish(identity, claims, response, tokens)\n\nclientOptions(spec, database, origin)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Client configuration must be an object\"\n for Object/keys(spec) as name\n if name != \"maxAgeSeconds\"\n throw \"Unknown client option: ${name}\"\n if database == null\n throw \"Managed client identity requires a database\"\n if database.type == \"sqlite\" and database.file == \":memory:\"\n throw \"Managed client identity requires persistent database storage\"\n if origin == null or !origin.required or !origin.url.startsWith(\"https:\")\n throw \"Managed client identity requires a required HTTPS origin\"\n lifetime = spec.maxAgeSeconds\n if lifetime == null\n lifetime = 2592000\n if is_string(lifetime)\n lifetime = Number(lifetime)\n if !Number/isSafeInteger(lifetime) or lifetime < 1 or lifetime > 31536000\n throw \"Client maxAgeSeconds must be between 1 and 31536000\"\n return {\n maxAgeSeconds: lifetime\n }\n\nClientIdentity(settings, database)\n @settings = settings\n @database = database\n\nClientIdentity:initialize()\n context db = @database.scope()\n try\n start_trans()\n if db.parameterStyle == \"postgresql\"\n lock = SQL\n select pg_advisory_xact_lock(1818324591, 1)\n lock.execute()\n row = SQL\n create table if not exists _lango_clients (\n client_id text primary key,\n secret_hash text not null unique,\n expires_at bigint not null\n )\n row.execute()\n commit_trans()\n finally\n db.finish()\n return null\n\nClientIdentity:begin(claims, tokens)\n context response\n value = readCookie()\n if value == null and claims != null\n response.reject(401, \"ClientProofRequired\")\n hash = null\n row = null\n if value == null\n value = clientSecret()\n claims = tokens.create()\n hash = clientDigest(value)\n claims.clientProof = hash\n return {\n claims: claims\n value: value\n hash: hash\n fresh: true\n restored: false\n rotate: false\n closed: false\n }\n hash = clientDigest(value)\n row = SQL\n select client_id from _lango_clients where secret_hash = :hash and expires_at > :now\n row.hash = hash\n row.now = Date/now()\n row.execute()\n if !row.next()\n response.reject(401, \"ClientCookieRejected\")\n restored = claims == null\n if restored\n claims = tokens.create(row.client_id)\n claims.clientProof = hash\n if claims.clientId != row.client_id or !sameProof(claims.clientProof, hash)\n response.reject(401, \"ClientProofRequired\")\n return {\n claims: claims\n value: value\n hash: hash\n fresh: false\n restored: restored\n rotate: false\n closed: false\n }\n\nClientIdentity:publish(identity, claims, response, tokens)\n value = identity.value\n if identity.rotate\n value = clientSecret()\n hash = clientDigest(value)\n claims.clientProof = hash\n encoded = tokens.sign(claims)\n context db = @database.scope()\n row = null\n try\n if identity.fresh\n row = SQL\n insert into _lango_clients (client_id, secret_hash, expires_at)\n values (:id, :hash, :expires)\n row.id = claims.clientId\n row.hash = hash\n row.expires = Date/now() + @settings.maxAgeSeconds * 1000\n row.execute()\n else\n row = SQL\n update _lango_clients set secret_hash = :replacement, expires_at = :expires\n where client_id = :id and secret_hash = :previous and expires_at > :now\n returning client_id\n row.id = claims.clientId\n row.previous = identity.hash\n row.replacement = hash\n row.now = Date/now()\n row.expires = Date/now() + @settings.maxAgeSeconds * 1000\n row.execute()\n if !row.next()\n response.reject(401, \"ClientProofRequired\")\n response.header(\"Set-Cookie\", \"__Host-lango-client=${value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=${@settings.maxAgeSeconds}\")\n finally\n db.finish()\n identity.closed = true\n return encoded\n\nreadCookie()\n context request\n context response\n headers = request.headers\n header = headers.cookie\n if header == null\n return null\n if !is_string(header) or header.length > 8192\n response.reject(400, \"InvalidCookie\")\n found = null\n for header.split(\";\") as part\n pair = part.trim()\n index = pair.indexOf(\"=\")\n if index >= 0 and pair.slice(0, index) == \"__Host-lango-client\"\n if found != null\n response.reject(400, \"InvalidCookie\")\n found = pair.slice(index + 1)\n if found != null\n pattern = new RegExp(\"^[a-f0-9]{64}$\")\n if !pattern.test(found)\n response.reject(400, \"InvalidCookie\")\n return found\n\nclientSecret()\n bytes = crypto/randomBytes(32)\n return bytes.toString(\"hex\")\n\nclientDigest(value)\n hash = crypto/createHash(\"sha256\")\n hash.update(value)\n return hash.digest(\"hex\")\n\nsameProof(left, right)\n pattern = new RegExp(\"^[a-f0-9]{64}$\")\n if !is_string(left) or !pattern.test(left)\n return false\n first = Buffer/from(left, \"hex\")\n second = Buffer/from(right, \"hex\")\n return crypto/timingSafeEqual(first, second)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;AAIA;;;;;;;;;AAKA;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"client_identity.mjs","sources":["client_identity.lango"],"sourcesContent":["import js \"node:crypto\" as crypto\nimport js global Date\nimport js global Object\nimport js global Number\nimport js global RegExp\nimport js global Buffer\n\nexport clientOptions(spec, database, origin)\nexport class ClientIdentity(settings, database)\n methods\n initialize()\n begin(claims, tokens)\n publish(identity, claims, response, tokens)\n\nclientOptions(spec, database, origin)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Client configuration must be an object\"\n for Object/keys(spec) as name\n if name != \"maxAgeSeconds\"\n throw \"Unknown client option: ${name}\"\n if database == null\n throw \"Managed client identity requires a database\"\n if database.type == \"sqlite\" and database.file == \":memory:\"\n throw \"Managed client identity requires persistent database storage\"\n if origin == null or !origin.required or !origin.url.startsWith(\"https:\")\n throw \"Managed client identity requires a required HTTPS origin\"\n lifetime = spec.maxAgeSeconds\n if lifetime == null\n lifetime = 2592000\n if is_string(lifetime)\n lifetime = Number(lifetime)\n if !Number/isSafeInteger(lifetime) or lifetime < 1 or lifetime > 31536000\n throw \"Client maxAgeSeconds must be between 1 and 31536000\"\n return {\n maxAgeSeconds: lifetime\n }\n\nClientIdentity(settings, database)\n @settings = settings\n @database = database\n\nClientIdentity:initialize()\n context db = @database.scope()\n try\n start_trans()\n if db.parameterStyle == \"postgresql\"\n lock = SQL\n select pg_advisory_xact_lock(1818324591, 1)\n lock.execute()\n row = SQL\n create table if not exists _lango_clients (\n client_id text primary key,\n secret_hash text not null unique,\n expires_at bigint not null\n )\n row.execute()\n commit_trans()\n finally\n db.finish()\n return null\n\nClientIdentity:begin(claims, tokens)\n context response\n value = readCookie()\n if value == null and claims != null\n response.reject(401, \"ClientProofRequired\")\n hash = null\n row = null\n if value == null\n value = clientSecret()\n claims = tokens.create()\n hash = clientDigest(value)\n claims.clientProof = hash\n return {\n claims: claims\n value: value\n hash: hash\n fresh: true\n restored: false\n rotate: false\n closed: false\n }\n hash = clientDigest(value)\n row = SQL\n select client_id from _lango_clients where secret_hash = :hash and expires_at > :now\n row.hash = hash\n row.now = Date/now()\n row.execute()\n if !row.next()\n response.reject(401, \"ClientCookieRejected\")\n restored = claims == null\n if restored\n claims = tokens.create(row.client_id)\n claims.clientProof = hash\n if claims.clientId != row.client_id or !sameProof(claims.clientProof, hash)\n response.reject(401, \"ClientProofRequired\")\n return {\n claims: claims\n value: value\n hash: hash\n fresh: false\n restored: restored\n rotate: false\n closed: false\n }\n\nClientIdentity:publish(identity, claims, response, tokens)\n value = identity.value\n if identity.rotate\n value = clientSecret()\n hash = clientDigest(value)\n claims.clientProof = hash\n encoded = tokens.sign(claims)\n context db = @database.scope()\n row = null\n try\n if identity.fresh\n row = SQL\n insert into _lango_clients (client_id, secret_hash, expires_at)\n values (:id, :hash, :expires)\n row.id = claims.clientId\n row.hash = hash\n row.expires = Date/now() + @settings.maxAgeSeconds * 1000\n row.execute()\n else\n row = SQL\n update _lango_clients set secret_hash = :replacement, expires_at = :expires\n where client_id = :id and secret_hash = :previous and expires_at > :now\n returning client_id\n row.id = claims.clientId\n row.previous = identity.hash\n row.replacement = hash\n row.now = Date/now()\n row.expires = Date/now() + @settings.maxAgeSeconds * 1000\n row.execute()\n if !row.next()\n response.reject(401, \"ClientProofRequired\")\n response.header(\"Set-Cookie\", \"__Host-lango-client=${value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=${@settings.maxAgeSeconds}\")\n finally\n db.finish()\n identity.closed = true\n return encoded\n\nreadCookie()\n context request\n context response\n headers = request.headers\n header = headers.cookie\n if header == null\n return null\n if !is_string(header) or header.length > 8192\n response.reject(400, \"InvalidCookie\")\n found = null\n for header.split(\";\") as part\n pair = part.trim()\n index = pair.indexOf(\"=\")\n if index >= 0 and pair.slice(0, index) == \"__Host-lango-client\"\n if found != null\n response.reject(400, \"InvalidCookie\")\n found = pair.slice(index + 1)\n if found != null\n pattern = new RegExp(\"^[a-f0-9]{64}$\")\n if !pattern.test(found)\n response.reject(400, \"InvalidCookie\")\n return found\n\nclientSecret()\n bytes = crypto/randomBytes(32)\n return bytes.toString(\"hex\")\n\nclientDigest(value)\n hash = crypto/createHash(\"sha256\")\n hash.update(value)\n return hash.digest(\"hex\")\n\nsameProof(left, right)\n pattern = new RegExp(\"^[a-f0-9]{64}$\")\n if !is_string(left) or !pattern.test(left)\n return false\n first = Buffer/from(left, \"hex\")\n second = Buffer/from(right, \"hex\")\n return crypto/timingSafeEqual(first, second)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;AAIA;;;;;;;;;AAKA;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"39e33b1699569551a2b65fa66cac03a1136cddcb710042ba600d85563151c227","outputHash":"6fa4c393c85359193e41814354b0497eb2e70330969e459682dffc9b3524c853","mapHash":"59af2402d3c4dc1288b158bc0eeca43a346e651b8d743e4f296b8a8b64b4bcba"}}
@@ -1 +1 @@
1
- {"version":3,"file":"database.mjs","sources":["database.lango"],"sourcesContent":["import \"./client_identity\"\n class ClientIdentity\nimport js global Promise\nimport \"./database_scope\"\n class DatabaseScope\nimport \"./sqlite_adapter\"\n class SqliteAdapter\nimport \"./postgres_adapter\"\n class PostgresAdapter\n\nexport prepareDatabase(settings, root = null, client = null)\n\nexport class Database(settings, root = null)\n methods\n open()\n scope()\n close()\n\nDatabase(settings, root = null)\n @root = root\n @settings = settings\n @adapter = null\n\nDatabase:open()\n if @settings == null\n return Promise/resolve(null)\n name = \"node:sqlite\"\n if @settings.type == \"postgresql\"\n name = \"node:worker_threads\"\n return chain import_module(name)\n then(mod)\n if @settings.type == \"sqlite\"\n @adapter = new SqliteAdapter(mod, @settings)\n else\n @adapter = new PostgresAdapter(mod, @settings, @root)\n context db = scope()\n try\n query = SQL\n select 1\n query.execute()\n finally\n db.finish()\n return null\n catch(error)\n context log\n log.err(\"Database startup failed: ${error}\")\n close()\n throw \"Database startup failed; check configuration, compiler version and driver installation\"\n\nDatabase:scope()\n if @adapter == null\n return null\n return new DatabaseScope(@adapter)\n\nDatabase:close()\n if @adapter != null\n @adapter.close()\n @adapter = null\n return null\n\nprepareDatabase(settings, root = null, client = null)\n if settings == null\n return Promise/resolve(null)\n if client == null and (settings.type != \"sqlite\" or settings.file == \":memory:\")\n return Promise/resolve(null)\n database = new Database(settings, root)\n return chain database.open()\n then(ignored)\n capture database\n capture client\n if client != null\n identity = new ClientIdentity(client, database)\n identity.initialize()\n return null\n finally\n capture database\n database.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"database.mjs","sources":["database.lango"],"sourcesContent":["import \"./client_identity\"\n class ClientIdentity\nimport js global Promise\nimport \"./database_scope\"\n class DatabaseScope\nimport \"./sqlite_adapter\"\n class SqliteAdapter\nimport \"./postgres_adapter\"\n class PostgresAdapter\n\nexport prepareDatabase(settings, root = null, client = null)\n\nexport class Database(settings, root = null)\n methods\n open()\n scope()\n close()\n\nDatabase(settings, root = null)\n @root = root\n @settings = settings\n @adapter = null\n\nDatabase:open()\n if @settings == null\n return Promise/resolve(null)\n name = \"node:sqlite\"\n if @settings.type == \"postgresql\"\n name = \"node:worker_threads\"\n return chain import_module(name)\n then(mod)\n if @settings.type == \"sqlite\"\n @adapter = new SqliteAdapter(mod, @settings)\n else\n @adapter = new PostgresAdapter(mod, @settings, @root)\n context db = scope()\n try\n query = SQL\n select 1\n query.execute()\n finally\n db.finish()\n return null\n catch(error)\n context log\n log.err(\"Database startup failed: ${error}\")\n close()\n throw \"Database startup failed; check configuration, compiler version and driver installation\"\n\nDatabase:scope()\n if @adapter == null\n return null\n return new DatabaseScope(@adapter)\n\nDatabase:close()\n if @adapter != null\n @adapter.close()\n @adapter = null\n return null\n\nprepareDatabase(settings, root = null, client = null)\n if settings == null\n return Promise/resolve(null)\n if client == null and (settings.type != \"sqlite\" or settings.file == \":memory:\")\n return Promise/resolve(null)\n database = new Database(settings, root)\n return chain database.open()\n then(ignored)\n capture database\n capture client\n if client != null\n identity = new ClientIdentity(client, database)\n identity.initialize()\n return null\n finally\n capture database\n database.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"d6d7f3491aa14ab670541d06dbbcf73f6c7a663600fe5b74f877eb283a6dbebd","outputHash":"ad3db2b9a18feb34fd580438120cab8a663f03da82ee871f4581de800a0cf3fd","mapHash":"cf9dbae30a6362ca76f7cb4bb230e0add08a76a9b71f8166da8c9dd79a6225b5"}}
@@ -0,0 +1,71 @@
1
+ import { Database } from "./database.mjs";
2
+ import { readDatabaseConfiguration } from "./job_configuration.mjs";
3
+ import * as path from "node:path";
4
+ import {
5
+ hostGlobal as __hostGlobal,
6
+ contextGet as __contextGet,
7
+ contextSet as __contextSet,
8
+ contextRestore as __contextRestore,
9
+ bindContexts as __bindContexts,
10
+ requireBoolean as __requireBoolean,
11
+ normalize as __normalize,
12
+ call as __call,
13
+ boundary as __boundary,
14
+ requireArity as __requireArity,
15
+ withArity as __withArity,
16
+ } from "./.lango/runtime.mjs";
17
+
18
+ export function withDatabase(directory, action) {
19
+ __requireArity(arguments.length, [0, 1], "withDatabase");
20
+ directory = __boundary(directory);
21
+ action = __boundary(action);
22
+ let root = __normalize(path.resolve(directory));
23
+ let database = new Database(readDatabaseConfiguration(root), root);
24
+ return __normalize(database.open()).then(__withArity(__bindContexts((ignored) => {
25
+ const __contextScope = [];
26
+ try {
27
+ ignored = __boundary(ignored);
28
+ __contextScope.push(__contextSet("db", __normalize(database.scope())));
29
+ return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(__bindContexts((ignored) => {
30
+ const __contextScope = [];
31
+ try {
32
+ ignored = __boundary(ignored);
33
+ return __call(action, );
34
+ return null;
35
+ } finally {
36
+ __contextRestore(__contextScope);
37
+ }
38
+ }), [0], "closure")).then(__withArity(__bindContexts((result) => {
39
+ const __contextScope = [];
40
+ try {
41
+ result = __boundary(result);
42
+ if (__requireBoolean(__requireBoolean(__contextGet("db") !== null) && __requireBoolean(__normalize(__contextGet("db").finish())))) {
43
+ throw "UnclosedTransaction";
44
+ }
45
+ return result;
46
+ return null;
47
+ } finally {
48
+ __contextRestore(__contextScope);
49
+ }
50
+ }), [0], "closure")).finally(__bindContexts(() => {
51
+ const __contextScope = [];
52
+ try {
53
+ if (__requireBoolean(__contextGet("db") !== null)) {
54
+ __normalize(__contextGet("db").finish());
55
+ }
56
+ return null;
57
+ } finally {
58
+ __contextRestore(__contextScope);
59
+ }
60
+ }));
61
+ return null;
62
+ } finally {
63
+ __contextRestore(__contextScope);
64
+ }
65
+ }), [0], "closure")).finally(__bindContexts(() => {
66
+ __normalize(database.close());
67
+ return null;
68
+ }));
69
+ return null;
70
+ }
71
+ //# sourceMappingURL=database_action.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database_action.mjs","sources":["database_action.lango"],"sourcesContent":["import \"./database\"\n class Database\nimport \"./job_configuration\"\n readDatabaseConfiguration(directory)\nimport js \"node:path\" as path\nimport js global Promise\n\nexport withDatabase(directory, action)\n\nwithDatabase(directory, action)\n root = path/resolve(directory)\n database = new Database(readDatabaseConfiguration(root), root)\n return chain database.open()\n then(ignored)\n capture database\n context db = database.scope()\n return chain Promise/resolve(null)\n then(ignored)\n capture action\n return action()\n then(result)\n if db != null and db.finish()\n throw \"UnclosedTransaction\"\n return result\n finally\n if db != null\n db.finish()\n finally\n capture database\n database.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"3952d87106ed76c5b950ba919ac5e38585b59d863a548f094da985df289651cc","outputHash":"a2c872c070872ff53b384885090707be0fe6f526300130cfabcb3b4e6c7412e3","mapHash":"52031f084526db823d4fe34aa9b5c7a78566646b741693f53a5f1f5d03f9a63a"}}
@@ -1 +1 @@
1
- {"version":3,"file":"database_options.mjs","sources":["database_options.lango"],"sourcesContent":["import js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport databaseOptions(root, spec, workers)\n\ndatabaseOptions(root, spec, workers)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Database configuration must be a map\"\n allowed = []\n switch spec.type\n case \"sqlite\"\n allowed = [\"type\", \"file\", \"busyTimeoutMs\"]\n case \"postgresql\"\n allowed = [\"type\", \"connectionEnv\", \"queryTimeoutMs\", \"connectTimeoutSeconds\"]\n else\n throw \"Database type must be sqlite or postgresql\"\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown database option: ${key}\"\n if spec.type == \"sqlite\"\n if !is_string(spec.file) or spec.file == \"\"\n throw \"SQLite database file is required\"\n file = spec.file\n if file == \":memory:\" and workers != 1\n throw \"An in-memory SQLite database requires exactly one worker\"\n if file != \":memory:\"\n file = path/resolve(root, file)\n return {\n type: \"sqlite\"\n file: file\n busyTimeoutMs: positive(spec.busyTimeoutMs, 5000)\n }\n name = spec.connectionEnv\n if !is_string(name) or name == \"\" or !Object/hasOwn(process.env, name)\n throw \"PostgreSQL connectionEnv must name an existing environment variable\"\n connection = process.env[name]\n if !is_string(connection) or (!connection.startsWith(\"postgresql://\") and !connection.startsWith(\"postgres://\"))\n throw \"PostgreSQL connectionEnv must contain a PostgreSQL connection URL\"\n return {\n type: \"postgresql\"\n connection: connection\n queryTimeoutMs: positive(spec.queryTimeoutMs, 5000)\n connectTimeoutSeconds: positive(spec.connectTimeoutSeconds, 5)\n }\n\npositive(value, fallback)\n if value == null\n return fallback\n if is_string(value)\n value = Number(value)\n if !Number/isSafeInteger(value) or value < 1 or value > 2147483647\n throw \"Database timeout must be a positive integer within the timer limit\"\n return value\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"database_options.mjs","sources":["database_options.lango"],"sourcesContent":["import js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport databaseOptions(root, spec, workers)\n\ndatabaseOptions(root, spec, workers)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Database configuration must be a map\"\n allowed = []\n switch spec.type\n case \"sqlite\"\n allowed = [\"type\", \"file\", \"busyTimeoutMs\"]\n case \"postgresql\"\n allowed = [\"type\", \"connectionEnv\", \"queryTimeoutMs\", \"connectTimeoutSeconds\"]\n else\n throw \"Database type must be sqlite or postgresql\"\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown database option: ${key}\"\n if spec.type == \"sqlite\"\n if !is_string(spec.file) or spec.file == \"\"\n throw \"SQLite database file is required\"\n file = spec.file\n if file == \":memory:\" and workers != 1\n throw \"An in-memory SQLite database requires exactly one worker\"\n if file != \":memory:\"\n file = path/resolve(root, file)\n return {\n type: \"sqlite\"\n file: file\n busyTimeoutMs: positive(spec.busyTimeoutMs, 5000)\n }\n name = spec.connectionEnv\n if !is_string(name) or name == \"\" or !Object/hasOwn(process.env, name)\n throw \"PostgreSQL connectionEnv must name an existing environment variable\"\n connection = process.env[name]\n if !is_string(connection) or (!connection.startsWith(\"postgresql://\") and !connection.startsWith(\"postgres://\"))\n throw \"PostgreSQL connectionEnv must contain a PostgreSQL connection URL\"\n return {\n type: \"postgresql\"\n connection: connection\n queryTimeoutMs: positive(spec.queryTimeoutMs, 5000)\n connectTimeoutSeconds: positive(spec.connectTimeoutSeconds, 5)\n }\n\npositive(value, fallback)\n if value == null\n return fallback\n if is_string(value)\n value = Number(value)\n if !Number/isSafeInteger(value) or value < 1 or value > 2147483647\n throw \"Database timeout must be a positive integer within the timer limit\"\n return value\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"3a6b3dfcf8ae5f0e5f4f767f22b625c8fc2c99bdebb08df4257971c365036db0","outputHash":"57558a28568c8d59d0e4d77d6254601e655cdfc2230f1ab01acfd3475ba698e9","mapHash":"c82d1dc145002785804fefefd9d8981beb984b8c33c7b71abc1e68a919605afe"}}
@@ -28,6 +28,17 @@ export class DatabaseScope {
28
28
  return __normalize(this.#adapter.execute(sql, parameters));
29
29
  return null;
30
30
  }
31
+ invoke(spec, input) {
32
+ __requireArity(arguments.length, [0, 1], "invoke");
33
+ spec = __boundary(spec);
34
+ input = __boundary(input);
35
+ this.#requireOpen();
36
+ if (__requireBoolean(__normalize(this.parameterStyle) !== "postgresql")) {
37
+ throw "Database extensions require PostgreSQL";
38
+ }
39
+ return __normalize(this.#adapter.invoke(spec, input));
40
+ return null;
41
+ }
31
42
  begin() {
32
43
  this.#requireOpen();
33
44
  return __normalize(this.#adapter.begin());
@@ -1 +1 @@
1
- {"version":3,"file":"database_scope.mjs","sources":["database_scope.lango"],"sourcesContent":["import js global Error\nimport js global Object\nimport js global process\n\nexport class DatabaseScope(adapter)\n properties\n parameterStyle\n methods\n execute(sql, parameters)\n begin()\n commit()\n rollback()\n transactionState()\n finish()\n\nDatabaseScope(adapter)\n @adapter = adapter\n @closed = false\n @parameterStyle = adapter.parameterStyle\n\nDatabaseScope:execute(sql, parameters)\n requireOpen()\n return @adapter.execute(sql, parameters)\n\nDatabaseScope:begin()\n requireOpen()\n return @adapter.begin()\n\nDatabaseScope:commit()\n requireOpen()\n return @adapter.commit()\n\nDatabaseScope:rollback()\n requireOpen()\n return @adapter.rollback()\n\nDatabaseScope:transactionState()\n requireOpen()\n return @adapter.transactionState()\n\nDatabaseScope:requireOpen()\n if @closed\n throw new Error(\"DatabaseScopeClosed\")\n return null\n\nDatabaseScope:finish()\n if @closed\n return false\n @closed = true\n dirty = false\n try\n loop while @adapter.transactionState() != null\n dirty = true\n @adapter.rollback()\n catch error\n context log\n log.err(\"Database cleanup failed; retiring worker\")\n process.exit(1)\n return dirty\n"],"names":[],"mappings":";;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"database_scope.mjs","sources":["database_scope.lango"],"sourcesContent":["import js global Error\nimport js global Object\nimport js global process\n\nexport class DatabaseScope(adapter)\n properties\n parameterStyle\n methods\n execute(sql, parameters)\n invoke(spec, input)\n begin()\n commit()\n rollback()\n transactionState()\n finish()\n\nDatabaseScope(adapter)\n @adapter = adapter\n @closed = false\n @parameterStyle = adapter.parameterStyle\n\nDatabaseScope:execute(sql, parameters)\n requireOpen()\n return @adapter.execute(sql, parameters)\n\nDatabaseScope:invoke(spec, input)\n requireOpen()\n if @parameterStyle != \"postgresql\"\n throw \"Database extensions require PostgreSQL\"\n return @adapter.invoke(spec, input)\n\nDatabaseScope:begin()\n requireOpen()\n return @adapter.begin()\n\nDatabaseScope:commit()\n requireOpen()\n return @adapter.commit()\n\nDatabaseScope:rollback()\n requireOpen()\n return @adapter.rollback()\n\nDatabaseScope:transactionState()\n requireOpen()\n return @adapter.transactionState()\n\nDatabaseScope:requireOpen()\n if @closed\n throw new Error(\"DatabaseScopeClosed\")\n return null\n\nDatabaseScope:finish()\n if @closed\n return false\n @closed = true\n dirty = false\n try\n loop while @adapter.transactionState() != null\n dirty = true\n @adapter.rollback()\n catch error\n context log\n log.err(\"Database cleanup failed; retiring worker\")\n process.exit(1)\n return dirty\n"],"names":[],"mappings":";;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"24678d1eedc77e4ba68a3cb7b492dc0b067121976eef53288ca90dede6c0d64d","outputHash":"f7f8c6ce5bfcac35c174d43f2ec8d4eff86de246c23a38080d405780a7dd4568","mapHash":"d377c4efb750308a3c550ebe61a53c57a420d77b9d5f8337e4f91d5bfbf6f213"}}
@@ -1 +1 @@
1
- {"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["import \"./policy\"\n policyOptions(spec)\nimport \"./route_pattern\"\n routePattern(path)\nimport \"./middleware\"\n middlewareName(name)\n\nexport class Endpoint(spec)\n properties\n path\n module\n handler\n auth\n policy\n reauthSeconds\n reauthExplicit\n legacyAuth\n middleware\n\nEndpoint(spec)\n routePattern(spec.path)\n for [\"module\", \"handler\"] as key\n if !is_string(spec[key]) or spec[key] == \"\"\n throw \"Endpoint requires ${key}\"\n @path = spec.path\n @module = spec.module\n @handler = spec.handler\n @middleware = spec.middleware\n if @middleware != null\n middlewareName(@middleware)\n selected = policyOptions(spec)\n @policy = selected.name\n @auth = selected.name\n @reauthSeconds = selected.reauthSeconds\n @reauthExplicit = selected.explicit\n @legacyAuth = selected.legacy\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["import \"./policy\"\n policyOptions(spec)\nimport \"./route_pattern\"\n routePattern(path)\nimport \"./middleware\"\n middlewareName(name)\n\nexport class Endpoint(spec)\n properties\n path\n module\n handler\n auth\n policy\n reauthSeconds\n reauthExplicit\n legacyAuth\n middleware\n\nEndpoint(spec)\n routePattern(spec.path)\n for [\"module\", \"handler\"] as key\n if !is_string(spec[key]) or spec[key] == \"\"\n throw \"Endpoint requires ${key}\"\n @path = spec.path\n @module = spec.module\n @handler = spec.handler\n @middleware = spec.middleware\n if @middleware != null\n middlewareName(@middleware)\n selected = policyOptions(spec)\n @policy = selected.name\n @auth = selected.name\n @reauthSeconds = selected.reauthSeconds\n @reauthExplicit = selected.explicit\n @legacyAuth = selected.legacy\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"64c587ae02cd691106a0fb4709752665ea4aa1d3481903804b66c7ee27ef4c13","outputHash":"d6b25f561f031eb3fafa39ec0cc7836c2e15aeccb4a00433f6a64c96cea07f30","mapHash":"730ee2cb10af9bacd9ccd7ad49fbec0712b0a1bcfde307bcc98a09cd18cb7293"}}
@@ -1 +1 @@
1
- {"version":3,"file":"error_details.mjs","sources":["error_details.lango"],"sourcesContent":["export errorDetails(error)\nexport errorMessage(error)\n\nerrorDetails(error)\n if is_object(error)\n if is_string(error.stack) and error.stack != \"\"\n return error.stack\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n\n\nerrorMessage(error)\n if is_object(error)\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n"],"names":[],"mappings":";;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"error_details.mjs","sources":["error_details.lango"],"sourcesContent":["export errorDetails(error)\nexport errorMessage(error)\n\nerrorDetails(error)\n if is_object(error)\n if is_string(error.stack) and error.stack != \"\"\n return error.stack\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n\n\nerrorMessage(error)\n if is_object(error)\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n"],"names":[],"mappings":";;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"56260c44066373eae7cb4ea0d7f520d5bed136bc75dc7373c4b550034731a35b","outputHash":"88d565014463c929f62d84e67c35e583032b7ab2e8a633759ef9ede2180152a8","mapHash":"1f0d3f5239b5e47e933b07849c9a6bc636fd17ca6e440713c7e269e31271c1d1"}}
@@ -0,0 +1,30 @@
1
+ import {
2
+ hostGlobal as __hostGlobal,
3
+ isNumber as __isNumber,
4
+ isString as __isString,
5
+ isBool as __isBool,
6
+ isObject as __isObject,
7
+ isArray as __isArray,
8
+ requireBoolean as __requireBoolean,
9
+ normalize as __normalize,
10
+ boundary as __boundary,
11
+ requireArity as __requireArity,
12
+ } from "./.lango/runtime.mjs";
13
+
14
+ export class ExecutionFailure {
15
+ #code;
16
+ constructor(code) {
17
+ __requireArity(arguments.length, [0], "constructor");
18
+ code = __boundary(code);
19
+ let pattern = new (__hostGlobal(["RegExp"]))("^[A-Za-z][A-Za-z0-9_]{0,63}$");
20
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(code))) || __requireBoolean(!__requireBoolean(__normalize(pattern.test(code)))))) {
21
+ throw "Execution rejection requires an error code";
22
+ }
23
+ this.#code = code;
24
+ }
25
+ get code() {
26
+ return __normalize(this.#code);
27
+ return null;
28
+ }
29
+ }
30
+ //# sourceMappingURL=execution_failure.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execution_failure.mjs","sources":["execution_failure.lango"],"sourcesContent":["import js global RegExp\n\nexport class ExecutionFailure(code)\n properties\n code?\n\nExecutionFailure(code)\n pattern = new RegExp(\"^[A-Za-z][A-Za-z0-9_]{0,63}$\")\n if !is_string(code) or !pattern.test(code)\n throw \"Execution rejection requires an error code\"\n @code = code\n\nExecutionFailure:code?\n return @code\n"],"names":[],"mappings":";;;;;;;;;;;;;AAEA;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"687ab9370e500e1bc0630490c2fcac4dc34f78ddb861a5567c8c8562d3cfbcba","outputHash":"8e3b16aea405b4b3a7459f50aea1d5429b0e8dc402c8fa7cc9a0e38242e305bc","mapHash":"f842e3513be81b8eade958f7e7dc11ab91e2ffdade0b95b421ea014ef2c17441"}}
@@ -0,0 +1,103 @@
1
+ import { ExecutionFailure } from "./execution_failure.mjs";
2
+ import { Token } from "./token.mjs";
3
+ import {
4
+ hostGlobal as __hostGlobal,
5
+ fromJson as __fromJson,
6
+ toJson as __toJson,
7
+ isNumber as __isNumber,
8
+ isString as __isString,
9
+ isBool as __isBool,
10
+ isObject as __isObject,
11
+ isArray as __isArray,
12
+ entries as __entries,
13
+ requireBoolean as __requireBoolean,
14
+ normalize as __normalize,
15
+ finite as __finite,
16
+ boundary as __boundary,
17
+ requireArity as __requireArity,
18
+ } from "./.lango/runtime.mjs";
19
+
20
+ export function executionSource(source) {
21
+ __requireArity(arguments.length, [0], "executionSource");
22
+ source = __boundary(source);
23
+ if (__requireBoolean(__requireBoolean(__requireBoolean(source === null) || __requireBoolean(!__requireBoolean(__isObject(source)))) || __requireBoolean(__isArray(source)))) {
24
+ throw "Execution source must be a map";
25
+ }
26
+ let allowed = ["kind", "clientId", "userId", "grantId", "identity"];
27
+ for (const [key, value] of __entries(source)) {
28
+ if (__requireBoolean(!__requireBoolean(__normalize(allowed.includes(key))))) {
29
+ throw `Unknown execution source field: ${key}`;
30
+ }
31
+ if (__requireBoolean(__requireBoolean(key !== "kind") && __requireBoolean(__requireBoolean(!__requireBoolean(__isString(value))) || __requireBoolean(__normalize(value.trim()) === "")))) {
32
+ throw "Execution source references must be nonempty strings";
33
+ }
34
+ }
35
+ if (__normalize(source.kind) === "user") {
36
+ if (__requireBoolean(__requireBoolean(__normalize(source.clientId) === null) || __requireBoolean(__normalize(source.identity) !== null))) {
37
+ throw "User execution source requires clientId and cannot select a system identity";
38
+ }
39
+ } else if (__normalize(source.kind) === "system") {
40
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__normalize(source.identity) === null) || __requireBoolean(__normalize(source.clientId) !== null)) || __requireBoolean(__normalize(source.userId) !== null)) || __requireBoolean(__normalize(source.grantId) !== null))) {
41
+ throw "System execution source requires only a configured identity";
42
+ }
43
+ } else {
44
+ throw "Execution source kind must be user or system";
45
+ }
46
+ return __fromJson(__toJson(source));
47
+ return null;
48
+ }
49
+
50
+ export function executionToken(identity, source, route) {
51
+ __requireArity(arguments.length, [0, 1, 2], "executionToken");
52
+ identity = __boundary(identity);
53
+ source = __boundary(source);
54
+ route = __boundary(route);
55
+ if (__requireBoolean(__requireBoolean(identity === null) || __requireBoolean(identity === false))) {
56
+ throw new ExecutionFailure("IdentityRejected");
57
+ }
58
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(identity))) || __requireBoolean(__isArray(identity)))) {
59
+ throw "Identity provider must return a map or null";
60
+ }
61
+ let allowed = ["clientId", "userId", "grantId", "identity", "policies", "authenticatedAt"];
62
+ for (const [key, value] of __entries(identity)) {
63
+ if (__requireBoolean(!__requireBoolean(__normalize(allowed.includes(key))))) {
64
+ throw `Unknown execution identity field: ${key}`;
65
+ }
66
+ }
67
+ if (__requireBoolean(!__requireBoolean(__isArray(__normalize(identity.policies))))) {
68
+ throw "Execution identity requires a policies array";
69
+ }
70
+ if (__requireBoolean(__normalize(source.kind) === "user")) {
71
+ for (const key of ["clientId", "userId", "grantId"]) {
72
+ if (__requireBoolean(__normalize(identity[key]) !== __normalize(source[key]))) {
73
+ throw new ExecutionFailure("IdentityChanged");
74
+ }
75
+ }
76
+ if (__requireBoolean(__normalize(identity.identity) !== null)) {
77
+ throw new ExecutionFailure("IdentityChanged");
78
+ }
79
+ } else {
80
+ if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__normalize(identity.identity) !== __normalize(source.identity)) || __requireBoolean(__normalize(identity.clientId) !== null)) || __requireBoolean(__normalize(identity.userId) !== null)) || __requireBoolean(__normalize(identity.grantId) !== null))) {
81
+ throw new ExecutionFailure("IdentityChanged");
82
+ }
83
+ }
84
+ let now = __normalize(__hostGlobal(["Date"]).now());
85
+ let stamp = __normalize(identity.authenticatedAt);
86
+ if (__requireBoolean(__requireBoolean(stamp !== null) && __requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(stamp)))) || __requireBoolean(stamp < 0)) || __requireBoolean(stamp > now)))) {
87
+ throw "Execution identity authenticatedAt must be a real past timestamp";
88
+ }
89
+ let claims = { clientId: __normalize(identity.clientId), userId: __normalize(identity.userId), grantId: __normalize(identity.grantId), identity: __normalize(identity.identity), auth: "", authenticatedAt: stamp };
90
+ let token = new Token(claims);
91
+ for (const policy of __normalize(identity.policies)) {
92
+ __normalize(token.addPolicy(policy));
93
+ }
94
+ if (__requireBoolean(__requireBoolean(__normalize(route.policy) !== "anonymous") && __requireBoolean(!__requireBoolean(__normalize(token.hasPolicy(__normalize(route.policy))))))) {
95
+ throw new ExecutionFailure("Forbidden");
96
+ }
97
+ if (__requireBoolean(__requireBoolean(__normalize(route.reauthSeconds) > 0) && __requireBoolean(__requireBoolean(stamp === null) || __requireBoolean(__finite(now - stamp) >= __finite(__normalize(route.reauthSeconds) * 1000))))) {
98
+ throw new ExecutionFailure("ReauthenticationRequired");
99
+ }
100
+ return new Token(__normalize(token.snapshot()), true);
101
+ return null;
102
+ }
103
+ //# sourceMappingURL=execution_identity.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execution_identity.mjs","sources":["execution_identity.lango"],"sourcesContent":["import \"./execution_failure\"\n class ExecutionFailure\nimport \"./token\"\n class Token\nimport js global Object\nimport js global Date\nimport js global Number\n\nexport executionSource(source)\nexport executionToken(identity, source, route)\n\nexecutionSource(source)\n if source == null or !is_object(source) or is_array(source)\n throw \"Execution source must be a map\"\n allowed = [\"kind\", \"clientId\", \"userId\", \"grantId\", \"identity\"]\n for source as key: value\n if !allowed.includes(key)\n throw \"Unknown execution source field: ${key}\"\n if key != \"kind\" and (!is_string(value) or value.trim() == \"\")\n throw \"Execution source references must be nonempty strings\"\n switch source.kind\n case \"user\"\n if source.clientId == null or source.identity != null\n throw \"User execution source requires clientId and cannot select a system identity\"\n case \"system\"\n if source.identity == null or source.clientId != null or source.userId != null or source.grantId != null\n throw \"System execution source requires only a configured identity\"\n else\n throw \"Execution source kind must be user or system\"\n return from_json(to_json(source))\n\nexecutionToken(identity, source, route)\n if identity == null or identity == false\n throw new ExecutionFailure(\"IdentityRejected\")\n if !is_object(identity) or is_array(identity)\n throw \"Identity provider must return a map or null\"\n allowed = [\"clientId\", \"userId\", \"grantId\", \"identity\", \"policies\", \"authenticatedAt\"]\n for identity as key: value\n if !allowed.includes(key)\n throw \"Unknown execution identity field: ${key}\"\n if !is_array(identity.policies)\n throw \"Execution identity requires a policies array\"\n if source.kind == \"user\"\n for [\"clientId\", \"userId\", \"grantId\"] as key\n if identity[key] != source[key]\n throw new ExecutionFailure(\"IdentityChanged\")\n if identity.identity != null\n throw new ExecutionFailure(\"IdentityChanged\")\n else\n if identity.identity != source.identity or identity.clientId != null or identity.userId != null or identity.grantId != null\n throw new ExecutionFailure(\"IdentityChanged\")\n now = Date/now()\n stamp = identity.authenticatedAt\n if stamp != null and (!Number/isSafeInteger(stamp) or stamp < 0 or stamp > now)\n throw \"Execution identity authenticatedAt must be a real past timestamp\"\n claims = {\n clientId: identity.clientId\n userId: identity.userId\n grantId: identity.grantId\n identity: identity.identity\n auth: \"\"\n authenticatedAt: stamp\n }\n token = new Token(claims)\n for identity.policies as policy\n token.addPolicy(policy)\n if route.policy != \"anonymous\" and !token.hasPolicy(route.policy)\n throw new ExecutionFailure(\"Forbidden\")\n if route.reauthSeconds > 0 and (stamp == null or now - stamp >= route.reauthSeconds * 1000)\n throw new ExecutionFailure(\"ReauthenticationRequired\")\n return new Token(token.snapshot(), true)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"cf0795373ad6c34a72d271100dfaf590afca3ca806c80364a6585d42343208e2","outputHash":"a92291f310b0ce8a20887c1ed6b7540f0c500087cee7b20c965e266badbb3970","mapHash":"fd10c9ca0d5301225a58a49739b967cc9499137330ae49cfd598ddf1aad4865a"}}
@@ -0,0 +1,47 @@
1
+ import {
2
+ normalize as __normalize,
3
+ boundary as __boundary,
4
+ requireArity as __requireArity,
5
+ } from "./.lango/runtime.mjs";
6
+
7
+ export class ExecutionLog {
8
+ #sink;
9
+ #prefix;
10
+ constructor(sink, job) {
11
+ __requireArity(arguments.length, [0, 1], "constructor");
12
+ sink = __boundary(sink);
13
+ job = __boundary(job);
14
+ this.#sink = sink;
15
+ let source = __normalize(job.source);
16
+ this.#prefix = `[jobId=${__normalize(job.id)}] path=${__normalize(job.path)} queue=${__normalize(job.queue)} attempt=${__normalize(job.attempt)} clientId=${__normalize(source.clientId)} userId=${__normalize(source.userId)} grantId=${__normalize(source.grantId)} identity=${__normalize(source.identity)}`;
17
+ }
18
+ get verbose() {
19
+ return __normalize(this.#sink.verbose);
20
+ return null;
21
+ }
22
+ debug(message) {
23
+ __requireArity(arguments.length, [0], "debug");
24
+ message = __boundary(message);
25
+ return __normalize(this.#sink.debug(`${__normalize(this.#prefix)} ${message}`));
26
+ return null;
27
+ }
28
+ info(message) {
29
+ __requireArity(arguments.length, [0], "info");
30
+ message = __boundary(message);
31
+ return __normalize(this.#sink.info(`${__normalize(this.#prefix)} ${message}`));
32
+ return null;
33
+ }
34
+ warn(message) {
35
+ __requireArity(arguments.length, [0], "warn");
36
+ message = __boundary(message);
37
+ return __normalize(this.#sink.warn(`${__normalize(this.#prefix)} ${message}`));
38
+ return null;
39
+ }
40
+ err(message) {
41
+ __requireArity(arguments.length, [0], "err");
42
+ message = __boundary(message);
43
+ return __normalize(this.#sink.err(`${__normalize(this.#prefix)} ${message}`));
44
+ return null;
45
+ }
46
+ }
47
+ //# sourceMappingURL=execution_log.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execution_log.mjs","sources":["execution_log.lango"],"sourcesContent":["export class ExecutionLog(sink, job)\n properties\n verbose?\n methods\n debug(message)\n info(message)\n warn(message)\n err(message)\n\nExecutionLog(sink, job)\n @sink = sink\n source = job.source?\n @prefix = \"[jobId=${job.id?}] path=${job.path?} queue=${job.queue?} attempt=${job.attempt?} clientId=${source.clientId} userId=${source.userId} grantId=${source.grantId} identity=${source.identity}\"\n\nExecutionLog:verbose?\n return @sink.verbose?\n\nExecutionLog:debug(message)\n return @sink.debug(\"${@prefix} ${message}\")\n\nExecutionLog:info(message)\n return @sink.info(\"${@prefix} ${message}\")\n\nExecutionLog:warn(message)\n return @sink.warn(\"${@prefix} ${message}\")\n\nExecutionLog:err(message)\n return @sink.err(\"${@prefix} ${message}\")\n"],"names":[],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"49cdc4b54921b4fb073637bd35128178261c8bfadc2326ab3bfb188a78138694","outputHash":"8e0aee8ae0a2311c18e302e463856e0636d2b81adc4eb9c9173baa7776151fa8","mapHash":"7e959f03f4d42947c9cfd1a215828cca2e59b70920b2b40d3d057a552a9319db"}}