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

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 (105) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +431 -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 +69 -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 +44 -0
  41. package/dist/cli/endpoint.mjs.map +1 -0
  42. package/dist/cli/options.mjs +165 -0
  43. package/dist/cli/options.mjs.map +1 -0
  44. package/dist/cli/postgres_adapter.mjs +166 -0
  45. package/dist/cli/postgres_adapter.mjs.map +1 -0
  46. package/dist/cli/routes.mjs +233 -0
  47. package/dist/cli/routes.mjs.map +1 -0
  48. package/dist/cli/server.mjs +572 -0
  49. package/dist/cli/server.mjs.map +1 -0
  50. package/dist/cli/sqlite_adapter.mjs +163 -0
  51. package/dist/cli/sqlite_adapter.mjs.map +1 -0
  52. package/dist/database.mjs +101 -0
  53. package/dist/database.mjs.map +1 -0
  54. package/dist/database_options.mjs +83 -0
  55. package/dist/database_options.mjs.map +1 -0
  56. package/dist/database_scope.mjs +82 -0
  57. package/dist/database_scope.mjs.map +1 -0
  58. package/dist/endpoint.mjs +44 -0
  59. package/dist/endpoint.mjs.map +1 -0
  60. package/dist/group.mjs +75 -0
  61. package/dist/group.mjs.map +1 -0
  62. package/dist/library.mjs +6 -0
  63. package/dist/library.mjs.map +1 -0
  64. package/dist/options.mjs +165 -0
  65. package/dist/options.mjs.map +1 -0
  66. package/dist/postgres_adapter.mjs +166 -0
  67. package/dist/postgres_adapter.mjs.map +1 -0
  68. package/dist/postgres_worker.mjs +119 -0
  69. package/dist/postgres_worker.mjs.map +1 -0
  70. package/dist/response.mjs +62 -0
  71. package/dist/response.mjs.map +1 -0
  72. package/dist/routes.mjs +233 -0
  73. package/dist/routes.mjs.map +1 -0
  74. package/dist/runtime.mjs +475 -0
  75. package/dist/runtime.mjs.map +1 -0
  76. package/dist/server.mjs +568 -0
  77. package/dist/server.mjs.map +1 -0
  78. package/dist/sqlite_adapter.mjs +163 -0
  79. package/dist/sqlite_adapter.mjs.map +1 -0
  80. package/dist/token.mjs +106 -0
  81. package/dist/token.mjs.map +1 -0
  82. package/dist/tokens.mjs +76 -0
  83. package/dist/tokens.mjs.map +1 -0
  84. package/dist/worker.mjs +57 -0
  85. package/dist/worker.mjs.map +1 -0
  86. package/package.json +39 -4
  87. package/src/body_reader.lango +113 -0
  88. package/src/builder.lango +53 -0
  89. package/src/database.lango +66 -0
  90. package/src/database_options.lango +57 -0
  91. package/src/database_scope.lango +59 -0
  92. package/src/endpoint.lango +23 -0
  93. package/src/group.lango +47 -0
  94. package/src/library.lango +10 -0
  95. package/src/options.lango +128 -0
  96. package/src/postgres_adapter.lango +138 -0
  97. package/src/postgres_worker.lango +114 -0
  98. package/src/response.lango +42 -0
  99. package/src/routes.lango +160 -0
  100. package/src/runtime.lango +320 -0
  101. package/src/server.lango +432 -0
  102. package/src/sqlite_adapter.lango +127 -0
  103. package/src/token.lango +70 -0
  104. package/src/tokens.lango +70 -0
  105. package/src/worker.lango +43 -0
@@ -0,0 +1,66 @@
1
+ import js global Promise
2
+ import "./database_scope"
3
+ class DatabaseScope
4
+ import "./sqlite_adapter"
5
+ class SqliteAdapter
6
+ import "./postgres_adapter"
7
+ class PostgresAdapter
8
+
9
+ export prepareDatabase(settings)
10
+
11
+ export class Database(settings, root = null)
12
+ methods
13
+ open()
14
+ scope()
15
+ close()
16
+
17
+ Database(settings, root = null)
18
+ @root = root
19
+ @settings = settings
20
+ @adapter = null
21
+
22
+ Database:open()
23
+ if @settings == null
24
+ return Promise/resolve(null)
25
+ name = "node:sqlite"
26
+ if @settings.type == "postgresql"
27
+ name = "node:worker_threads"
28
+ return chain import_module(name)
29
+ then(mod)
30
+ if @settings.type == "sqlite"
31
+ @adapter = new SqliteAdapter(mod, @settings)
32
+ else
33
+ @adapter = new PostgresAdapter(mod, @settings, @root)
34
+ context db = scope()
35
+ try
36
+ query = SQL
37
+ select 1
38
+ query.execute()
39
+ finally
40
+ db.finish()
41
+ return null
42
+ catch(error)
43
+ context log
44
+ log.err("Database startup failed: ${error}")
45
+ close()
46
+ throw "Database startup failed; check configuration, compiler version and driver installation"
47
+
48
+ Database:scope()
49
+ if @adapter == null
50
+ return null
51
+ return new DatabaseScope(@adapter)
52
+
53
+ Database:close()
54
+ if @adapter != null
55
+ @adapter.close()
56
+ @adapter = null
57
+ return null
58
+
59
+ prepareDatabase(settings)
60
+ if settings == null or settings.type != "sqlite" or settings.file == ":memory:"
61
+ return Promise/resolve(null)
62
+ database = new Database(settings)
63
+ return chain database.open()
64
+ finally
65
+ capture database
66
+ database.close()
@@ -0,0 +1,57 @@
1
+ import js "node:path" as path
2
+ import js global Object
3
+ import js global Number
4
+ import js global process
5
+
6
+ export databaseOptions(root, spec, workers)
7
+
8
+ databaseOptions(root, spec, workers)
9
+ if spec == null
10
+ return null
11
+ if !is_object(spec) or is_array(spec)
12
+ throw "Database configuration must be a map"
13
+ allowed = []
14
+ switch spec.type
15
+ case "sqlite"
16
+ allowed = ["type", "file", "busyTimeoutMs"]
17
+ case "postgresql"
18
+ allowed = ["type", "connectionEnv", "queryTimeoutMs", "connectTimeoutSeconds"]
19
+ else
20
+ throw "Database type must be sqlite or postgresql"
21
+ for spec as key: value
22
+ if !allowed.includes(key)
23
+ throw "Unknown database option: ${key}"
24
+ if spec.type == "sqlite"
25
+ if !is_string(spec.file) or spec.file == ""
26
+ throw "SQLite database file is required"
27
+ file = spec.file
28
+ if file == ":memory:" and workers != 1
29
+ throw "An in-memory SQLite database requires exactly one worker"
30
+ if file != ":memory:"
31
+ file = path/resolve(root, file)
32
+ return {
33
+ type: "sqlite"
34
+ file: file
35
+ busyTimeoutMs: positive(spec.busyTimeoutMs, 5000)
36
+ }
37
+ name = spec.connectionEnv
38
+ if !is_string(name) or name == "" or !Object/hasOwn(process.env, name)
39
+ throw "PostgreSQL connectionEnv must name an existing environment variable"
40
+ connection = process.env[name]
41
+ if !is_string(connection) or (!connection.startsWith("postgresql://") and !connection.startsWith("postgres://"))
42
+ throw "PostgreSQL connectionEnv must contain a PostgreSQL connection URL"
43
+ return {
44
+ type: "postgresql"
45
+ connection: connection
46
+ queryTimeoutMs: positive(spec.queryTimeoutMs, 5000)
47
+ connectTimeoutSeconds: positive(spec.connectTimeoutSeconds, 5)
48
+ }
49
+
50
+ positive(value, fallback)
51
+ if value == null
52
+ return fallback
53
+ if is_string(value)
54
+ value = Number(value)
55
+ if !Number/isSafeInteger(value) or value < 1 or value > 2147483647
56
+ throw "Database timeout must be a positive integer within the timer limit"
57
+ return value
@@ -0,0 +1,59 @@
1
+ import js global Error
2
+ import js global Object
3
+ import js global process
4
+
5
+ export class DatabaseScope(adapter)
6
+ properties
7
+ parameterStyle
8
+ methods
9
+ execute(sql, parameters)
10
+ begin()
11
+ commit()
12
+ rollback()
13
+ transactionState()
14
+ finish()
15
+
16
+ DatabaseScope(adapter)
17
+ @adapter = adapter
18
+ @closed = false
19
+ @parameterStyle = adapter.parameterStyle
20
+
21
+ DatabaseScope:execute(sql, parameters)
22
+ requireOpen()
23
+ return @adapter.execute(sql, parameters)
24
+
25
+ DatabaseScope:begin()
26
+ requireOpen()
27
+ return @adapter.begin()
28
+
29
+ DatabaseScope:commit()
30
+ requireOpen()
31
+ return @adapter.commit()
32
+
33
+ DatabaseScope:rollback()
34
+ requireOpen()
35
+ return @adapter.rollback()
36
+
37
+ DatabaseScope:transactionState()
38
+ requireOpen()
39
+ return @adapter.transactionState()
40
+
41
+ DatabaseScope:requireOpen()
42
+ if @closed
43
+ throw new Error("DatabaseScopeClosed")
44
+ return null
45
+
46
+ DatabaseScope:finish()
47
+ if @closed
48
+ return false
49
+ @closed = true
50
+ dirty = false
51
+ try
52
+ loop while @adapter.transactionState() != null
53
+ dirty = true
54
+ @adapter.rollback()
55
+ catch error
56
+ context log
57
+ log.err("Database cleanup failed; retiring worker")
58
+ process.exit(1)
59
+ return dirty
@@ -0,0 +1,23 @@
1
+ export class Endpoint(spec)
2
+ properties
3
+ path
4
+ module
5
+ handler
6
+ auth
7
+
8
+ Endpoint(spec)
9
+ if !is_string(spec.path) or !spec.path.startsWith("/") or spec.path.includes("?") or spec.path.includes("#") or spec.path.includes("\\") or spec.path.includes("//")
10
+ throw "Endpoint requires an absolute URL path"
11
+ if spec.path.includes("*") and (!spec.path.endsWith("/*") or spec.path.indexOf("*") != spec.path.lastIndexOf("*"))
12
+ throw "Only trailing /* wildcards are supported"
13
+ for ["module", "handler"] as key
14
+ if !is_string(spec[key]) or spec[key] == ""
15
+ throw "Endpoint requires ${key}"
16
+ @path = spec.path
17
+ @module = spec.module
18
+ @handler = spec.handler
19
+ @auth = spec.auth
20
+ if @auth == null
21
+ @auth = "login"
22
+ if !is_string(@auth) or @auth == "" or @auth.includes(",")
23
+ throw "Endpoint auth must name one permission"
@@ -0,0 +1,47 @@
1
+ export class Group(routes, spec, prefix = "", inheritedModule = null, inheritedAuth = null)
2
+ methods
3
+ endpoint(spec)
4
+ group(spec)
5
+ include(spec)
6
+
7
+ Group(routes, spec, prefix = "", inheritedModule = null, inheritedAuth = null)
8
+ if !is_string(spec.path) or !spec.path.startsWith("/") or spec.path.endsWith("/") or spec.path.includes("*")
9
+ throw "Group requires a path without a trailing slash or wildcard"
10
+ @routes = routes
11
+ @prefix = "${prefix}${spec.path}"
12
+ @module = spec.module
13
+ @auth = spec.auth
14
+ if @module == null
15
+ @module = inheritedModule
16
+ if @auth == null
17
+ @auth = inheritedAuth
18
+
19
+ Group:endpoint(spec)
20
+ if !is_string(spec.path) or !spec.path.startsWith("/")
21
+ throw "Endpoint path must begin with /"
22
+ mod = spec.module
23
+ auth = spec.auth
24
+ if mod == null
25
+ mod = @module
26
+ if auth == null
27
+ auth = @auth
28
+ @routes.endpoint({
29
+ path: "${@prefix}${spec.path}"
30
+ module: mod
31
+ handler: spec.handler
32
+ auth: auth
33
+ })
34
+ return @this
35
+
36
+ Group:group(spec)
37
+ return new Group(@routes, spec, @prefix, @module, @auth)
38
+
39
+ Group:include(spec)
40
+ mount = spec.path
41
+ if mount == null
42
+ mount = "/"
43
+ @routes.include({
44
+ module: spec.module
45
+ path: "${@prefix}${mount}"
46
+ }, @auth)
47
+ return @this
@@ -0,0 +1,10 @@
1
+ import "./server"
2
+ alias ServerClass = class Server
3
+ import "./builder"
4
+ alias BuilderClass = class Builder
5
+
6
+ export global Server
7
+ export global Builder
8
+
9
+ global Server = ServerClass
10
+ global Builder = BuilderClass
@@ -0,0 +1,128 @@
1
+ import "./database_options"
2
+ databaseOptions(root, spec, workers)
3
+ import js "node:fs" as fs
4
+ import js "node:path" as path
5
+ import js global Object
6
+ import js global Number
7
+ import js global process
8
+
9
+ export contains(items, value)
10
+ export options(root, supplied = null)
11
+ export deployment(directory)
12
+ export attributes(tag, allowed)
13
+
14
+ attributes(tag, allowed)
15
+ for tag.attributes() as key: value
16
+ if !allowed.includes(key)
17
+ throw "Unknown ${tag.tag()} attribute: ${key}"
18
+ return null
19
+
20
+ options(root, supplied = null)
21
+ result = {
22
+ root: path/resolve(root)
23
+ host: "127.0.0.1"
24
+ port: 3000
25
+ workers: 2
26
+ maxQueue: 64
27
+ bodyLimit: 1048576
28
+ bodyTimeoutMs: 30000
29
+ requestTimeoutMs: 30000
30
+ eventTimeoutMs: 5000
31
+ startupTimeoutMs: 30000
32
+ shutdownTimeoutMs: 30000
33
+ issuer: "lango-server"
34
+ audience: "lango-client"
35
+ ttlSeconds: 900
36
+ key: null
37
+ keys: {}
38
+ activeKeyId: "current"
39
+ requestEvent: false
40
+ database: null
41
+ }
42
+ if supplied != null
43
+ for supplied as key: value
44
+ if !Object/hasOwn(result, key) or key == "root"
45
+ throw "Unknown server option: ${key}"
46
+ result[key] = value
47
+ if !is_string(result.host) or result.host == ""
48
+ throw "Host must be a nonempty string"
49
+ for ["port", "workers", "maxQueue", "bodyLimit", "bodyTimeoutMs", "requestTimeoutMs", "eventTimeoutMs", "startupTimeoutMs", "shutdownTimeoutMs", "ttlSeconds"] as key
50
+ value = result[key]
51
+ if !is_number(value) or !Number/isSafeInteger(value) or value < 0
52
+ throw "Invalid server option: ${key}"
53
+ if key != "port" and key != "maxQueue" and value == 0
54
+ throw "Server option must be positive: ${key}"
55
+ if key.endsWith("Ms") and value > 2147483647
56
+ throw "Timeout exceeds timer limit: ${key}"
57
+ if result.port > 65535 or result.workers > 128 or result.ttlSeconds > 86400
58
+ throw "Server option exceeds supported limit"
59
+ if !is_bool(result.requestEvent)
60
+ throw "requestEvent must be boolean"
61
+ for ["issuer", "audience", "activeKeyId"] as key
62
+ if !is_string(result[key]) or result[key] == ""
63
+ throw "Missing JWT option: ${key}"
64
+ if !is_object(result.keys) or is_array(result.keys)
65
+ throw "JWT keys must be a map"
66
+ keys = Object/assign(Object/create(null), result.keys)
67
+ if result.key != null
68
+ keys[result.activeKeyId] = result.key
69
+ if !Object/hasOwn(keys, result.activeKeyId)
70
+ throw "JWT signing key is required"
71
+ for keys as id: secret
72
+ if !is_string(secret) or secret.length < 32
73
+ throw "JWT keys must contain at least 32 characters"
74
+ result.keys = keys
75
+ result.key = null
76
+ result.database = databaseOptions(result.root, result.database, result.workers)
77
+ return result
78
+
79
+ deployment(directory)
80
+ file = path/join(directory, "deploy.xml")
81
+ root = xml2obj(fs/readFileSync(file, "utf8"))
82
+ if root.tag() != "deploy"
83
+ throw "Expected deploy root"
84
+ attributes(root, [])
85
+ settings = {}
86
+ seen = []
87
+ for root.children() as tag
88
+ name = tag.tag()
89
+ if seen.includes(name) or tag.children().length != 0 or tag.innerText().trim() != ""
90
+ throw "Duplicate or nonempty deployment section: ${name}"
91
+ seen.add(name)
92
+ switch name
93
+ case "http"
94
+ attributes(tag, ["host", "port", "bodyLimit", "bodyTimeoutMs"])
95
+ case "workers"
96
+ attributes(tag, ["workers", "maxQueue", "requestTimeoutMs", "startupTimeoutMs", "shutdownTimeoutMs"])
97
+ case "events"
98
+ attributes(tag, ["requestEvent", "eventTimeoutMs"])
99
+ case "database"
100
+ attributes(tag, ["type", "file", "connectionEnv", "busyTimeoutMs", "queryTimeoutMs", "connectTimeoutSeconds"])
101
+ settings.database = tag.attributes()
102
+ continue
103
+ case "jwt"
104
+ attributes(tag, ["issuer", "audience", "ttlSeconds", "keyEnv", "keysFile", "activeKeyId"])
105
+ else
106
+ throw "Unknown deployment section: ${name}"
107
+ for tag.attributes() as key: value
108
+ if key == "keyEnv"
109
+ settings.key = process.env[value]
110
+ if settings.key == null
111
+ throw "JWT key environment variable is missing: ${value}"
112
+ else
113
+ if key == "keysFile"
114
+ settings.keys = from_json(fs/readFileSync(path/resolve(directory, value), "utf8"))
115
+ else
116
+ if contains(["host", "issuer", "audience", "activeKeyId"], key)
117
+ settings[key] = value
118
+ else
119
+ if key == "requestEvent"
120
+ if value != "true" and value != "false"
121
+ throw "requestEvent must be true or false"
122
+ settings[key] = value == "true"
123
+ else
124
+ settings[key] = Number(value)
125
+ return options(directory, settings)
126
+
127
+ contains(items, value)
128
+ 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
@@ -0,0 +1,114 @@
1
+ import js "pg" as pg
2
+ import js "node:worker_threads" as threads
3
+ import js global Atomics
4
+ import js global Math
5
+ import js global Number
6
+ import js global Promise
7
+
8
+
9
+ global state = initialState()
10
+ global installed = install()
11
+
12
+ install()
13
+ port = threads.workerData.port
14
+ port.on("message", (task)
15
+ return chain Promise/resolve(null)
16
+ then(ignored)
17
+ capture task
18
+ return execute(task)
19
+ then(result)
20
+ reply(result)
21
+ return null
22
+ catch(error)
23
+ global state
24
+ if state.transaction != null
25
+ state.transaction = "failed"
26
+ if error.code == null or error.code.length != 5 or error.code.startsWith("08")
27
+ state.dead = true
28
+ position = null
29
+ if error.position != null
30
+ position = Number/parseInt(error.position, 10)
31
+ reply({
32
+ failed: true
33
+ dead: state.dead
34
+ code: error.code
35
+ position: position
36
+ state: state.transaction
37
+ })
38
+ return null
39
+ )
40
+ return null
41
+
42
+ execute(task)
43
+ global state
44
+ settings = threads.workerData.settings
45
+ switch task.action
46
+ case "connect"
47
+ state.client = new pg/Client({
48
+ connectionString: settings.connection
49
+ connectionTimeoutMillis: Math/min(2147483647, settings.connectTimeoutSeconds * 1000)
50
+ statement_timeout: settings.queryTimeoutMs
51
+ application_name: "lango-server"
52
+ })
53
+ client = state.client
54
+ client.on("error", (error)
55
+ global state
56
+ state.dead = true
57
+ )
58
+ return chain client.connect()
59
+ then(ignored)
60
+ return success([], null)
61
+ case "query"
62
+ return chain state.client.query({
63
+ text: task.sql
64
+ values: task.parameters
65
+ queryMode: "extended"
66
+ })
67
+ then(result)
68
+ global state
69
+ switch result.command
70
+ case "BEGIN"
71
+ state.transaction = "active"
72
+ case "COMMIT"
73
+ case "ROLLBACK"
74
+ state.transaction = null
75
+ changes = null
76
+ switch result.command
77
+ case "INSERT"
78
+ case "UPDATE"
79
+ case "DELETE"
80
+ case "MERGE"
81
+ changes = result.rowCount
82
+ return success(result.rows, changes)
83
+ case "close"
84
+ return chain state.client.end()
85
+ then(ignored)
86
+ return success([], null)
87
+ else
88
+ throw "Unknown PostgreSQL operation"
89
+
90
+ success(rows, changes)
91
+ global state
92
+ return {
93
+ failed: false
94
+ dead: false
95
+ state: state.transaction
96
+ rows: rows
97
+ changes: changes
98
+ lastInsertRowid: null
99
+ }
100
+
101
+ reply(result)
102
+ port = threads.workerData.port
103
+ signal = threads.workerData.signal
104
+ port.postMessage(result)
105
+ Atomics/store(signal, 0, 1)
106
+ Atomics/notify(signal, 0)
107
+ return null
108
+
109
+ initialState()
110
+ return {
111
+ client: null
112
+ transaction: null
113
+ dead: false
114
+ }
@@ -0,0 +1,42 @@
1
+ import js "node:http" as http
2
+
3
+ import "./options"
4
+ contains(items, value)
5
+ export class Response()
6
+ methods
7
+ status(code)
8
+ header(name, value)
9
+ result(body)
10
+
11
+ Response()
12
+ @status = 200
13
+ @headers = {
14
+ "content-type": "application/json; charset=utf-8"
15
+ "cache-control": "no-store"
16
+ }
17
+
18
+ Response:status(code)
19
+ if !is_number(code) or code % 1 != 0 or code < 200 or code > 599 or code == 204 or code == 205 or code == 304
20
+ throw "Response requires a JSON-compatible HTTP status"
21
+ @status = code
22
+ return @this
23
+
24
+ Response:header(name, value)
25
+ if !is_string(name) or !is_string(value)
26
+ throw "Header name and value must be strings"
27
+ name = name.toLowerCase()
28
+ if contains(["x-lango-token", "content-length", "transfer-encoding", "connection", "content-type"], name)
29
+ throw "Reserved response header: ${name}"
30
+ if name.includes("\r") or name.includes("\n") or value.includes("\r") or value.includes("\n")
31
+ throw "Invalid response header"
32
+ http/validateHeaderName(name)
33
+ http/validateHeaderValue(name, value)
34
+ @headers[name] = value
35
+ return @this
36
+
37
+ Response:result(body)
38
+ return {
39
+ status: @status
40
+ headers: from_json(to_json(@headers))
41
+ body: body
42
+ }