@lango-project/lango-server 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +710 -2
  4. package/dist/.lango/bignumber.mjs +3119 -0
  5. package/dist/.lango/runtime.mjs +683 -0
  6. package/dist/.lango/xmldom/conventions.js +429 -0
  7. package/dist/.lango/xmldom/dom-parser.js +591 -0
  8. package/dist/.lango/xmldom/dom.js +3759 -0
  9. package/dist/.lango/xmldom/entities.js +2171 -0
  10. package/dist/.lango/xmldom/errors.js +205 -0
  11. package/dist/.lango/xmldom/grammar.js +559 -0
  12. package/dist/.lango/xmldom/index.js +41 -0
  13. package/dist/.lango/xmldom/package.json +1 -0
  14. package/dist/.lango/xmldom/sax.js +983 -0
  15. package/dist/.lango/xmldom.LICENSE.md +8 -0
  16. package/dist/body_reader.mjs +179 -0
  17. package/dist/body_reader.mjs.map +1 -0
  18. package/dist/builder.mjs +84 -0
  19. package/dist/builder.mjs.map +1 -0
  20. package/dist/cli/.lango/bignumber.mjs +3119 -0
  21. package/dist/cli/.lango/runtime.mjs +683 -0
  22. package/dist/cli/.lango/xmldom/conventions.js +429 -0
  23. package/dist/cli/.lango/xmldom/dom-parser.js +591 -0
  24. package/dist/cli/.lango/xmldom/dom.js +3759 -0
  25. package/dist/cli/.lango/xmldom/entities.js +2171 -0
  26. package/dist/cli/.lango/xmldom/errors.js +205 -0
  27. package/dist/cli/.lango/xmldom/grammar.js +559 -0
  28. package/dist/cli/.lango/xmldom/index.js +41 -0
  29. package/dist/cli/.lango/xmldom/package.json +1 -0
  30. package/dist/cli/.lango/xmldom/sax.js +983 -0
  31. package/dist/cli/.lango/xmldom.LICENSE.md +8 -0
  32. package/dist/cli/body_reader.mjs +179 -0
  33. package/dist/cli/body_reader.mjs.map +1 -0
  34. package/dist/cli/database.mjs +101 -0
  35. package/dist/cli/database.mjs.map +1 -0
  36. package/dist/cli/database_options.mjs +83 -0
  37. package/dist/cli/database_options.mjs.map +1 -0
  38. package/dist/cli/database_scope.mjs +82 -0
  39. package/dist/cli/database_scope.mjs.map +1 -0
  40. package/dist/cli/endpoint.mjs +50 -0
  41. package/dist/cli/endpoint.mjs.map +1 -0
  42. package/dist/cli/longpoll_broker.mjs +214 -0
  43. package/dist/cli/longpoll_broker.mjs.map +1 -0
  44. package/dist/cli/longpoll_options.mjs +102 -0
  45. package/dist/cli/longpoll_options.mjs.map +1 -0
  46. package/dist/cli/longpoll_session.mjs +135 -0
  47. package/dist/cli/longpoll_session.mjs.map +1 -0
  48. package/dist/cli/middleware.mjs +25 -0
  49. package/dist/cli/middleware.mjs.map +1 -0
  50. package/dist/cli/options.mjs +177 -0
  51. package/dist/cli/options.mjs.map +1 -0
  52. package/dist/cli/postgres_adapter.mjs +166 -0
  53. package/dist/cli/postgres_adapter.mjs.map +1 -0
  54. package/dist/cli/routes.mjs +297 -0
  55. package/dist/cli/routes.mjs.map +1 -0
  56. package/dist/cli/server.mjs +792 -0
  57. package/dist/cli/server.mjs.map +1 -0
  58. package/dist/cli/sqlite_adapter.mjs +163 -0
  59. package/dist/cli/sqlite_adapter.mjs.map +1 -0
  60. package/dist/cli/static_files.mjs +125 -0
  61. package/dist/cli/static_files.mjs.map +1 -0
  62. package/dist/database.mjs +101 -0
  63. package/dist/database.mjs.map +1 -0
  64. package/dist/database_options.mjs +83 -0
  65. package/dist/database_options.mjs.map +1 -0
  66. package/dist/database_scope.mjs +82 -0
  67. package/dist/database_scope.mjs.map +1 -0
  68. package/dist/endpoint.mjs +50 -0
  69. package/dist/endpoint.mjs.map +1 -0
  70. package/dist/group.mjs +91 -0
  71. package/dist/group.mjs.map +1 -0
  72. package/dist/library.mjs +6 -0
  73. package/dist/library.mjs.map +1 -0
  74. package/dist/longpoll_broker.mjs +214 -0
  75. package/dist/longpoll_broker.mjs.map +1 -0
  76. package/dist/longpoll_options.mjs +102 -0
  77. package/dist/longpoll_options.mjs.map +1 -0
  78. package/dist/longpoll_session.mjs +135 -0
  79. package/dist/longpoll_session.mjs.map +1 -0
  80. package/dist/middleware.mjs +25 -0
  81. package/dist/middleware.mjs.map +1 -0
  82. package/dist/options.mjs +177 -0
  83. package/dist/options.mjs.map +1 -0
  84. package/dist/postgres_adapter.mjs +166 -0
  85. package/dist/postgres_adapter.mjs.map +1 -0
  86. package/dist/postgres_worker.mjs +119 -0
  87. package/dist/postgres_worker.mjs.map +1 -0
  88. package/dist/response.mjs +62 -0
  89. package/dist/response.mjs.map +1 -0
  90. package/dist/routes.mjs +297 -0
  91. package/dist/routes.mjs.map +1 -0
  92. package/dist/runtime.mjs +549 -0
  93. package/dist/runtime.mjs.map +1 -0
  94. package/dist/server.mjs +788 -0
  95. package/dist/server.mjs.map +1 -0
  96. package/dist/server_context.mjs +78 -0
  97. package/dist/server_context.mjs.map +1 -0
  98. package/dist/sqlite_adapter.mjs +163 -0
  99. package/dist/sqlite_adapter.mjs.map +1 -0
  100. package/dist/static_files.mjs +125 -0
  101. package/dist/static_files.mjs.map +1 -0
  102. package/dist/token.mjs +106 -0
  103. package/dist/token.mjs.map +1 -0
  104. package/dist/tokens.mjs +76 -0
  105. package/dist/tokens.mjs.map +1 -0
  106. package/dist/worker.mjs +57 -0
  107. package/dist/worker.mjs.map +1 -0
  108. package/package.json +44 -4
  109. package/src/body_reader.lango +113 -0
  110. package/src/builder.lango +64 -0
  111. package/src/database.lango +66 -0
  112. package/src/database_options.lango +57 -0
  113. package/src/database_scope.lango +59 -0
  114. package/src/endpoint.lango +30 -0
  115. package/src/group.lango +61 -0
  116. package/src/library.lango +10 -0
  117. package/src/longpoll.lua +61 -0
  118. package/src/longpoll_broker.lango +161 -0
  119. package/src/longpoll_options.lango +79 -0
  120. package/src/longpoll_session.lango +90 -0
  121. package/src/middleware.lango +10 -0
  122. package/src/options.lango +144 -0
  123. package/src/postgres_adapter.lango +138 -0
  124. package/src/postgres_worker.lango +114 -0
  125. package/src/response.lango +42 -0
  126. package/src/routes.lango +224 -0
  127. package/src/runtime.lango +382 -0
  128. package/src/server.lango +597 -0
  129. package/src/server_context.lango +58 -0
  130. package/src/sqlite_adapter.lango +127 -0
  131. package/src/static_files.lango +90 -0
  132. package/src/token.lango +70 -0
  133. package/src/tokens.lango +70 -0
  134. package/src/worker.lango +43 -0
@@ -0,0 +1,161 @@
1
+ import js "redis" as redis
2
+ import js "node:crypto" as crypto
3
+ import js "node:fs" as fs
4
+ import js "node:path" as path
5
+ import js "node:module" as modules
6
+ import js global Buffer
7
+ import js global Promise
8
+ import js global process
9
+ import js global JSON
10
+ import js global RegExp
11
+ import js global Object
12
+ import js global setTimeout
13
+ import js global clearTimeout
14
+
15
+ export class LongpollBroker(settings, routes)
16
+ methods
17
+ open()
18
+ close()
19
+ route(path)
20
+ publish(path, key, data)
21
+ cursor(path, key)
22
+ read(path, key, cursor)
23
+
24
+ LongpollBroker(settings, routes)
25
+ @routes = Object/create(null)
26
+ for routes as item
27
+ if item.kind == "longpoll"
28
+ @routes[item.path] = item
29
+ @settings = settings.redis
30
+ @client = null
31
+ @script = null
32
+ if Object/keys(@routes).length > 0 and @settings == null
33
+ throw "Longpoll routes require Redis configuration"
34
+ @root = settings.root
35
+
36
+ LongpollBroker:route(path)
37
+ if Object/hasOwn(@routes, path)
38
+ return @routes[path]
39
+ return null
40
+
41
+ LongpollBroker:open()
42
+ if Object/keys(@routes).length == 0
43
+ return Promise/resolve(null)
44
+ resolver = modules/createRequire(path/join(@root, "package.json"))
45
+ entry = resolver.resolve("@lango-project/lango-server")
46
+ @script = fs/readFileSync(path/join(path/dirname(entry), "../src/longpoll.lua"), "utf8")
47
+ config = @settings
48
+ name = config.connectionEnv
49
+ @client = redis/createClient({
50
+ url: process.env[name]
51
+ disableOfflineQueue: true
52
+ commandsQueueMaxLength: 2048
53
+ socket: {
54
+ connectTimeout: 2000
55
+ reconnectStrategy: 500
56
+ }
57
+ })
58
+ client = @client
59
+ client.on("error", (error)
60
+ return null
61
+ )
62
+ return bounded(client.connect(), 3000)
63
+
64
+ LongpollBroker:close()
65
+ if @client != null and @client.isOpen
66
+ @client.destroy()
67
+ return null
68
+
69
+ LongpollBroker:publish(path, key, data)
70
+ body = JSON/stringify(data)
71
+ if !is_string(body) or Buffer/byteLength(body) > 262144
72
+ return Promise/reject("Longpoll message must be JSON within 262144 bytes")
73
+ return execute("publish", path, key, null, body)
74
+
75
+ LongpollBroker:cursor(path, key)
76
+ return execute("cursor", path, key, null, "")
77
+
78
+ LongpollBroker:read(path, key, cursor)
79
+ return execute("read", path, key, cursor, "")
80
+
81
+ LongpollBroker:execute(operation, path, key, cursor, body)
82
+ item = route(path)
83
+ if item == null
84
+ return Promise/reject("Unknown longpoll path")
85
+ if !is_string(key) or key == "" or Buffer/byteLength(key) > 1024
86
+ return Promise/reject("Longpoll key must contain 1 to 1024 bytes")
87
+ if @client == null or !@client.isReady
88
+ return Promise/reject("RedisUnavailable")
89
+ hash = crypto/createHash("sha256")
90
+ hash.update(to_json([@settings.namespace, path, key]))
91
+ channel = hash.digest("hex")
92
+ prefix = "lango:longpoll:{${channel}}"
93
+ position = {
94
+ generation: ""
95
+ id: "0-0"
96
+ }
97
+ if cursor != null
98
+ position = decode(cursor, channel)
99
+ if position == null
100
+ return Promise/resolve({
101
+ resyncRequired: true
102
+ })
103
+ pending = @client.eval(@script, {
104
+ keys: ["${prefix}:stream", "${prefix}:meta"]
105
+ arguments: [operation, crypto/randomUUID(), "${item.retentionMs}", "${item.maxMessages}", position.generation, position.id, body]
106
+ })
107
+ return chain bounded(pending, 3000)
108
+ then(raw)
109
+ capture channel
110
+ capture operation
111
+ result = JSON/parse(raw)
112
+ if result.resyncRequired == true
113
+ return result
114
+ result.cursor = encode(channel, result.generation, result.id)
115
+ if operation != "read"
116
+ return result.cursor
117
+ messages = []
118
+ if is_array(result.messages)
119
+ for result.messages as message
120
+ messages.add({
121
+ id: encode(channel, result.generation, message.id)
122
+ data: JSON/parse(message.data)
123
+ })
124
+ return {
125
+ messages: messages
126
+ cursor: result.cursor
127
+ resyncRequired: false
128
+ }
129
+
130
+ encode(channel, generation, id)
131
+ buffer = Buffer/from(to_json([channel, generation, id]))
132
+ return buffer.toString("base64url")
133
+
134
+ decode(cursor, channel)
135
+ if !is_string(cursor) or cursor.length > 512
136
+ return null
137
+ try
138
+ buffer = Buffer/from(cursor, "base64url")
139
+ parts = from_json(buffer.toString("utf8"))
140
+ if !is_array(parts) or parts.length != 3 or parts[0] != channel or !is_string(parts[1]) or !is_string(parts[2])
141
+ return null
142
+ pattern = new RegExp("^(0|[1-9][0-9]{0,18})-(0|[1-9][0-9]{0,18})$")
143
+ if !pattern.test(parts[2]) or parts[2].length > 40
144
+ return null
145
+ return {
146
+ generation: parts[1]
147
+ id: parts[2]
148
+ }
149
+ catch error
150
+ return null
151
+
152
+ bounded(pending, ms)
153
+ expired = Promise/withResolvers()
154
+ fail = ()
155
+ capture expired
156
+ expired.reject("RedisUnavailable")
157
+ timer = setTimeout(fail, ms)
158
+ return chain Promise/race([pending, expired.promise])
159
+ finally
160
+ capture timer
161
+ clearTimeout(timer)
@@ -0,0 +1,79 @@
1
+ import js global Number
2
+ import js global Object
3
+ import js global process
4
+ import js global URL
5
+
6
+ export longpollOptions(spec)
7
+ export redisOptions(spec)
8
+
9
+ longpollOptions(spec)
10
+ result = {
11
+ kind: "longpoll"
12
+ path: spec.path
13
+ auth: "login"
14
+ waitTimeoutMs: 20000
15
+ retentionMs: 300000
16
+ maxMessages: 1000
17
+ fallback: null
18
+ }
19
+ for spec as key: value
20
+ if !Object/hasOwn(result, key) or key == "kind"
21
+ throw "Unknown longpoll option: ${key}"
22
+ result[key] = value
23
+ if result.auth == null
24
+ result.auth = "login"
25
+ validPath(result.path)
26
+ if !is_string(result.auth) or result.auth == "" or result.auth.includes(",")
27
+ throw "Longpoll auth must name one permission"
28
+ if result.fallback != null
29
+ validPath(result.fallback)
30
+ limits = {
31
+ waitTimeoutMs: 60000
32
+ retentionMs: 86400000
33
+ maxMessages: 10000
34
+ }
35
+ for limits as key: limit
36
+ if !is_number(result[key]) and !is_string(result[key])
37
+ throw "Invalid longpoll option: ${key}"
38
+ value = Number(result[key])
39
+ if !Number/isSafeInteger(value) or value < 1 or value > limit
40
+ throw "Invalid longpoll option: ${key}"
41
+ result[key] = value
42
+ return result
43
+
44
+ validPath(value)
45
+ if !is_string(value) or !value.startsWith("/") or value.includes("*") or value.includes("?") or value.includes("#") or value.includes("\\") or value.includes("//")
46
+ throw "Longpoll requires an exact absolute URL path"
47
+ return null
48
+
49
+ redisOptions(spec)
50
+ if spec == null
51
+ return null
52
+ if !is_object(spec) or is_array(spec)
53
+ throw "Redis configuration must be a map"
54
+ allowed = ["connectionEnv", "namespace", "maxPendingPolls"]
55
+ for spec as key: value
56
+ if !allowed.includes(key)
57
+ throw "Unknown Redis option: ${key}"
58
+ if !is_string(spec.connectionEnv) or spec.connectionEnv == "" or !is_string(spec.namespace) or spec.namespace == "" or spec.namespace.length > 128
59
+ throw "Redis requires connectionEnv and namespace"
60
+ name = spec.connectionEnv
61
+ value = process.env[name]
62
+ if !is_string(value) or value == ""
63
+ throw "Redis connection environment variable is missing"
64
+ url = new URL(value)
65
+ protocols = ["redis:", "rediss:"]
66
+ if !protocols.includes(url.protocol)
67
+ throw "Redis requires a redis:// or rediss:// URL"
68
+ maximum = 1024
69
+ if spec.maxPendingPolls != null
70
+ if !is_number(spec.maxPendingPolls) and !is_string(spec.maxPendingPolls)
71
+ throw "Invalid Redis maxPendingPolls"
72
+ maximum = Number(spec.maxPendingPolls)
73
+ if !Number/isSafeInteger(maximum) or maximum < 1 or maximum > 10000
74
+ throw "Invalid Redis maxPendingPolls"
75
+ return {
76
+ connectionEnv: spec.connectionEnv
77
+ namespace: spec.namespace
78
+ maxPendingPolls: maximum
79
+ }
@@ -0,0 +1,90 @@
1
+ import js global Promise
2
+ import js global Buffer
3
+ import js global Date
4
+ import js global Math
5
+ import js global setTimeout
6
+ import js global clearTimeout
7
+
8
+ export class LongpollSession(broker, route, authorize, body)
9
+ methods
10
+ run()
11
+ cancel()
12
+
13
+ LongpollSession(broker, route, authorize, body)
14
+ @broker = broker
15
+ @route = route
16
+ @authorize = authorize
17
+ @body = body
18
+ @cancelled = false
19
+ @timer = null
20
+ @sleep = null
21
+ @token = null
22
+ @deadline = 0
23
+ @input = null
24
+ @cursor = null
25
+
26
+ LongpollSession:cancel()
27
+ @cancelled = true
28
+ clearTimeout(@timer)
29
+ if @sleep != null
30
+ @sleep.resolve(null)
31
+ return null
32
+
33
+ LongpollSession:run()
34
+ try
35
+ @input = from_json(@body)
36
+ input = @input
37
+ if !is_object(input) or is_array(input) or !is_string(input.key) or input.key == "" or Buffer/byteLength(input.key) > 1024
38
+ return Promise/resolve(failure(400, "InvalidLongpollInput"))
39
+ if input.cursor != null and (!is_string(input.cursor) or input.cursor.length > 512)
40
+ return Promise/resolve(failure(400, "InvalidLongpollInput"))
41
+ @cursor = input.cursor
42
+ catch error
43
+ return Promise/resolve(failure(400, "InvalidJson"))
44
+ auth = @authorize
45
+ return chain auth(null, null)
46
+ then(result)
47
+ if result.status != 200
48
+ return result
49
+ @token = result.authorization
50
+ @deadline = Date/now() + @route.waitTimeoutMs
51
+ return poll()
52
+ catch(error)
53
+ return failure(503, "LongpollUnavailable")
54
+ finally
55
+ cancel()
56
+
57
+ LongpollSession:poll()
58
+ if @cancelled
59
+ return Promise/resolve(failure(503, "Unavailable"))
60
+ return chain @broker.read(@route.path, @input.key, @cursor)
61
+ then(batch)
62
+ if @cancelled
63
+ return failure(503, "Unavailable")
64
+ if batch.resyncRequired or batch.messages.length > 0 or Date/now() >= @deadline
65
+ if batch.resyncRequired
66
+ batch.fallback = @route.fallback
67
+ auth = @authorize
68
+ return auth(@token, batch)
69
+ @cursor = batch.cursor
70
+ @sleep = Promise/withResolvers()
71
+ sleep = @sleep
72
+ wake = ()
73
+ capture sleep
74
+ sleep.resolve(null)
75
+ @timer = setTimeout(wake, Math/min(250, Math/max(1, @deadline - Date/now())))
76
+ return chain sleep.promise
77
+ then(ignored)
78
+ return poll()
79
+
80
+ failure(status, code)
81
+ return {
82
+ status: status
83
+ headers: {
84
+ "content-type": "application/json; charset=utf-8"
85
+ "cache-control": "no-store"
86
+ }
87
+ body: to_json({
88
+ error: code
89
+ })
90
+ }
@@ -0,0 +1,10 @@
1
+ import js global RegExp
2
+
3
+ export middlewareName(name)
4
+
5
+ middlewareName(name)
6
+ reserved = ["routes", "endpoint", "longpoll", "group", "include", "event", "middleware"]
7
+ pattern = new RegExp("^[A-Za-z_][A-Za-z0-9_-]*$")
8
+ if !is_string(name) or !pattern.test(name) or reserved.includes(name)
9
+ throw "Invalid or reserved middleware name: ${name}"
10
+ return name
@@ -0,0 +1,144 @@
1
+ import "./longpoll_options"
2
+ redisOptions(spec)
3
+ import "./database_options"
4
+ databaseOptions(root, spec, workers)
5
+ import "./static_files"
6
+ staticOptions(root, spec)
7
+ import js "node:fs" as fs
8
+ import js "node:path" as path
9
+ import js global Object
10
+ import js global Number
11
+ import js global process
12
+
13
+ export contains(items, value)
14
+ export options(root, supplied = null)
15
+ export deployment(directory)
16
+ export attributes(tag, allowed)
17
+
18
+ attributes(tag, allowed)
19
+ for tag.attributes() as key: value
20
+ if !allowed.includes(key)
21
+ throw "Unknown ${tag.tag()} attribute: ${key}"
22
+ return null
23
+
24
+ options(root, supplied = null)
25
+ result = {
26
+ root: path/resolve(root)
27
+ host: "127.0.0.1"
28
+ port: 3000
29
+ workers: 2
30
+ maxQueue: 64
31
+ bodyLimit: 1048576
32
+ bodyTimeoutMs: 30000
33
+ requestTimeoutMs: 30000
34
+ eventTimeoutMs: 5000
35
+ startupTimeoutMs: 30000
36
+ shutdownTimeoutMs: 30000
37
+ issuer: "lango-server"
38
+ audience: "lango-client"
39
+ ttlSeconds: 900
40
+ key: null
41
+ keys: {}
42
+ activeKeyId: "current"
43
+ requestEvent: false
44
+ database: null
45
+ redis: null
46
+ static: null
47
+ }
48
+ if supplied != null
49
+ for supplied as key: value
50
+ if !Object/hasOwn(result, key) or key == "root"
51
+ throw "Unknown server option: ${key}"
52
+ result[key] = value
53
+ if !is_string(result.host) or result.host == ""
54
+ throw "Host must be a nonempty string"
55
+ for ["port", "workers", "maxQueue", "bodyLimit", "bodyTimeoutMs", "requestTimeoutMs", "eventTimeoutMs", "startupTimeoutMs", "shutdownTimeoutMs", "ttlSeconds"] as key
56
+ value = result[key]
57
+ if !is_number(value) or !Number/isSafeInteger(value) or value < 0
58
+ throw "Invalid server option: ${key}"
59
+ if key != "port" and key != "maxQueue" and value == 0
60
+ throw "Server option must be positive: ${key}"
61
+ if key.endsWith("Ms") and value > 2147483647
62
+ throw "Timeout exceeds timer limit: ${key}"
63
+ if result.port > 65535 or result.workers > 128 or result.ttlSeconds > 86400
64
+ throw "Server option exceeds supported limit"
65
+ if !is_bool(result.requestEvent)
66
+ throw "requestEvent must be boolean"
67
+ for ["issuer", "audience", "activeKeyId"] as key
68
+ if !is_string(result[key]) or result[key] == ""
69
+ throw "Missing JWT option: ${key}"
70
+ if !is_object(result.keys) or is_array(result.keys)
71
+ throw "JWT keys must be a map"
72
+ keys = Object/assign(Object/create(null), result.keys)
73
+ if result.key != null
74
+ keys[result.activeKeyId] = result.key
75
+ if !Object/hasOwn(keys, result.activeKeyId)
76
+ throw "JWT signing key is required"
77
+ for keys as id: secret
78
+ if !is_string(secret) or secret.length < 32
79
+ throw "JWT keys must contain at least 32 characters"
80
+ result.keys = keys
81
+ result.key = null
82
+ result.database = databaseOptions(result.root, result.database, result.workers)
83
+ result.redis = redisOptions(result.redis)
84
+ result.static = staticOptions(result.root, result.static)
85
+ return result
86
+
87
+ deployment(directory)
88
+ file = path/join(directory, "deploy.xml")
89
+ root = xml2obj(fs/readFileSync(file, "utf8"))
90
+ if root.tag() != "deploy"
91
+ throw "Expected deploy root"
92
+ attributes(root, [])
93
+ settings = {}
94
+ seen = []
95
+ for root.children() as tag
96
+ name = tag.tag()
97
+ if seen.includes(name) or tag.children().length != 0 or tag.innerText().trim() != ""
98
+ throw "Duplicate or nonempty deployment section: ${name}"
99
+ seen.add(name)
100
+ switch name
101
+ case "static"
102
+ attributes(tag, ["path", "directory", "index"])
103
+ settings.static = tag.attributes()
104
+ continue
105
+ case "http"
106
+ attributes(tag, ["host", "port", "bodyLimit", "bodyTimeoutMs"])
107
+ case "workers"
108
+ attributes(tag, ["workers", "maxQueue", "requestTimeoutMs", "startupTimeoutMs", "shutdownTimeoutMs"])
109
+ case "events"
110
+ attributes(tag, ["requestEvent", "eventTimeoutMs"])
111
+ case "redis"
112
+ attributes(tag, ["connectionEnv", "namespace", "maxPendingPolls"])
113
+ settings.redis = tag.attributes()
114
+ continue
115
+ case "database"
116
+ attributes(tag, ["type", "file", "connectionEnv", "busyTimeoutMs", "queryTimeoutMs", "connectTimeoutSeconds"])
117
+ settings.database = tag.attributes()
118
+ continue
119
+ case "jwt"
120
+ attributes(tag, ["issuer", "audience", "ttlSeconds", "keyEnv", "keysFile", "activeKeyId"])
121
+ else
122
+ throw "Unknown deployment section: ${name}"
123
+ for tag.attributes() as key: value
124
+ if key == "keyEnv"
125
+ settings.key = process.env[value]
126
+ if settings.key == null
127
+ throw "JWT key environment variable is missing: ${value}"
128
+ else
129
+ if key == "keysFile"
130
+ settings.keys = from_json(fs/readFileSync(path/resolve(directory, value), "utf8"))
131
+ else
132
+ if contains(["host", "issuer", "audience", "activeKeyId"], key)
133
+ settings[key] = value
134
+ else
135
+ if key == "requestEvent"
136
+ if value != "true" and value != "false"
137
+ throw "requestEvent must be true or false"
138
+ settings[key] = value == "true"
139
+ else
140
+ settings[key] = Number(value)
141
+ return options(directory, settings)
142
+
143
+ contains(items, value)
144
+ return items.includes(value)
@@ -0,0 +1,138 @@
1
+ import js "node:module" as modules
2
+ import js "node:path" as path
3
+ import js "node:worker_threads" as threads
4
+ import js global Reflect
5
+ import js global SharedArrayBuffer
6
+ import js global Int32Array
7
+ import js global Atomics
8
+ import js global Math
9
+ import js global Error
10
+
11
+ export class PostgresAdapter(mod, settings, root)
12
+ properties
13
+ parameterStyle
14
+ methods
15
+ execute(sql, parameters)
16
+ begin()
17
+ commit()
18
+ rollback()
19
+ transactionState()
20
+ close()
21
+
22
+ PostgresAdapter(mod, settings, root)
23
+ @closed = false
24
+ @broken = false
25
+ @state = null
26
+ @depth = 0
27
+ @rollbackOnly = false
28
+ @parameterStyle = "postgresql"
29
+ @timeout = Math/min(2147483647, settings.queryTimeoutMs + 1000)
30
+ @signal = new Int32Array(new SharedArrayBuffer(4))
31
+ channel = Reflect/construct(mod.MessageChannel, [])
32
+ @port = channel.port1
33
+ resolver = modules/createRequire(path/join(root, "package.json"))
34
+ entry = resolver.resolve("@lango-project/lango-server")
35
+ @worker = Reflect/construct(mod.Worker, [path/join(path/dirname(entry), "postgres_worker.mjs"), {
36
+ workerData: {
37
+ settings: settings
38
+ port: channel.port2
39
+ signal: @signal
40
+ }
41
+ transferList: [channel.port2]
42
+ }])
43
+ worker = @worker
44
+ worker.on("error", (error)
45
+ @broken = true
46
+ )
47
+ @worker.unref()
48
+ @port.unref()
49
+ try
50
+ exchange({
51
+ action: "connect"
52
+ }, Math/min(2147483647, settings.connectTimeoutSeconds * 1000 + 1000))
53
+ catch error
54
+ close()
55
+ throw new Error("PostgreSQL initialization failed")
56
+
57
+ PostgresAdapter:exchange(task, timeout)
58
+ if @closed or @broken
59
+ throw new Error("PostgreSQL connection is unavailable")
60
+ Atomics/store(@signal, 0, 0)
61
+ @port.postMessage(task)
62
+ waited = Atomics/wait(@signal, 0, 0, timeout)
63
+ if waited == "timed-out"
64
+ @broken = true
65
+ @worker.terminate()
66
+ throw new Error("PostgreSQL operation timed out")
67
+ reply = threads/receiveMessageOnPort(@port)
68
+ if reply == null
69
+ @broken = true
70
+ throw new Error("PostgreSQL response was not received")
71
+ result = reply.message
72
+ @state = result.state
73
+ if result.failed
74
+ @broken = result.dead
75
+ error = new Error("PostgreSQL query failed")
76
+ error.code = result.code
77
+ error.position = result.position
78
+ error.transactionUnusable = @state == "failed"
79
+ throw error
80
+ return result
81
+
82
+ PostgresAdapter:execute(sql, parameters)
83
+ return exchange({
84
+ action: "query"
85
+ sql: sql
86
+ parameters: parameters
87
+ }, @timeout)
88
+
89
+ PostgresAdapter:begin()
90
+ if @depth == 0 and @state == null
91
+ execute("BEGIN", [])
92
+ @depth = @depth + 1
93
+ return null
94
+
95
+ PostgresAdapter:commit()
96
+ if @depth == 0
97
+ throw new Error("NoActiveTransaction")
98
+ if @depth > 1
99
+ @depth = @depth - 1
100
+ return null
101
+ if @rollbackOnly or @state == "failed"
102
+ rollback()
103
+ throw new Error("TransactionRolledBack")
104
+ execute("COMMIT", [])
105
+ @depth = 0
106
+ return null
107
+
108
+ PostgresAdapter:rollback()
109
+ if @depth > 1
110
+ @depth = @depth - 1
111
+ @rollbackOnly = true
112
+ return null
113
+ if @state != null
114
+ execute("ROLLBACK", [])
115
+ @depth = 0
116
+ @rollbackOnly = false
117
+ return null
118
+
119
+ PostgresAdapter:transactionState()
120
+ if @broken
121
+ throw new Error("PostgreSQL connection is unavailable")
122
+ if @rollbackOnly and @state != "failed"
123
+ return "rollback_only"
124
+ return @state
125
+
126
+ PostgresAdapter:close()
127
+ if @closed
128
+ return null
129
+ try
130
+ if !@broken
131
+ exchange({
132
+ action: "close"
133
+ }, @timeout)
134
+ finally
135
+ @closed = true
136
+ @port.close()
137
+ @worker.terminate()
138
+ return null