@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
package/src/builder.lango CHANGED
@@ -6,14 +6,20 @@ import "./group"
6
6
  class Group
7
7
  import "./options"
8
8
  options(root, supplied = null)
9
+ readDeployment(directory, credentials = true)
9
10
  import "./server"
10
11
  class Server
12
+ import "./queue_provider"
13
+ queueProvider(root, spec)
11
14
 
12
15
  export class Builder(root = null)
13
16
  methods
14
17
  configure(settings)
18
+ loadDeployment()
15
19
  addMiddleware(name, spec)
20
+ provideQueue(spec)
16
21
  endpoint(spec)
22
+ job(spec)
17
23
  longpoll(spec)
18
24
  group(spec)
19
25
  include(spec)
@@ -25,6 +31,7 @@ Builder(root = null)
25
31
  root = process.cwd()
26
32
  @root = path/resolve(root)
27
33
  @settings = {}
34
+ @queueProvider = null
28
35
  @routes = new Routes(@root)
29
36
 
30
37
  Builder:configure(settings)
@@ -32,14 +39,27 @@ Builder:configure(settings)
32
39
  @settings[key] = value
33
40
  return @this
34
41
 
42
+ Builder:loadDeployment()
43
+ return configure(readDeployment(@root))
44
+
35
45
  Builder:addMiddleware(name, spec)
36
46
  @routes.addMiddleware(name, spec)
37
47
  return @this
38
48
 
49
+ Builder:provideQueue(spec)
50
+ if @queueProvider != null
51
+ throw "Queue provider is already configured"
52
+ @queueProvider = queueProvider(@root, spec)
53
+ return @this
54
+
39
55
  Builder:endpoint(spec)
40
56
  @routes.endpoint(spec)
41
57
  return @this
42
58
 
59
+ Builder:job(spec)
60
+ @routes.job(spec)
61
+ return @this
62
+
43
63
  Builder:longpoll(spec)
44
64
  @routes.longpoll(spec)
45
65
  return @this
@@ -59,6 +79,8 @@ Builder:build()
59
79
  return new Server(null, {
60
80
  settings: options(@root, @settings)
61
81
  routes: @routes.definitions()
82
+ jobs: @routes.jobs()
62
83
  events: @routes.events()
63
84
  middlewares: @routes.middlewares()
85
+ queueProvider: @queueProvider
64
86
  })
@@ -0,0 +1,30 @@
1
+ import "./database"
2
+ class Database
3
+ import "./job_configuration"
4
+ readDatabaseConfiguration(directory)
5
+ import js "node:path" as path
6
+ import js global Promise
7
+
8
+ export withDatabase(directory, action)
9
+
10
+ withDatabase(directory, action)
11
+ root = path/resolve(directory)
12
+ database = new Database(readDatabaseConfiguration(root), root)
13
+ return chain database.open()
14
+ then(ignored)
15
+ capture database
16
+ context db = database.scope()
17
+ return chain Promise/resolve(null)
18
+ then(ignored)
19
+ capture action
20
+ return action()
21
+ then(result)
22
+ if db != null and db.finish()
23
+ throw "UnclosedTransaction"
24
+ return result
25
+ finally
26
+ if db != null
27
+ db.finish()
28
+ finally
29
+ capture database
30
+ database.close()
@@ -7,6 +7,7 @@ export class DatabaseScope(adapter)
7
7
  parameterStyle
8
8
  methods
9
9
  execute(sql, parameters)
10
+ invoke(spec, input)
10
11
  begin()
11
12
  commit()
12
13
  rollback()
@@ -22,6 +23,12 @@ DatabaseScope:execute(sql, parameters)
22
23
  requireOpen()
23
24
  return @adapter.execute(sql, parameters)
24
25
 
26
+ DatabaseScope:invoke(spec, input)
27
+ requireOpen()
28
+ if @parameterStyle != "postgresql"
29
+ throw "Database extensions require PostgreSQL"
30
+ return @adapter.invoke(spec, input)
31
+
25
32
  DatabaseScope:begin()
26
33
  requireOpen()
27
34
  return @adapter.begin()
@@ -0,0 +1,14 @@
1
+ import js global RegExp
2
+
3
+ export class ExecutionFailure(code)
4
+ properties
5
+ code?
6
+
7
+ ExecutionFailure(code)
8
+ pattern = new RegExp("^[A-Za-z][A-Za-z0-9_]{0,63}$")
9
+ if !is_string(code) or !pattern.test(code)
10
+ throw "Execution rejection requires an error code"
11
+ @code = code
12
+
13
+ ExecutionFailure:code?
14
+ return @code
@@ -0,0 +1,71 @@
1
+ import "./execution_failure"
2
+ class ExecutionFailure
3
+ import "./token"
4
+ class Token
5
+ import js global Object
6
+ import js global Date
7
+ import js global Number
8
+
9
+ export executionSource(source)
10
+ export executionToken(identity, source, route)
11
+
12
+ executionSource(source)
13
+ if source == null or !is_object(source) or is_array(source)
14
+ throw "Execution source must be a map"
15
+ allowed = ["kind", "clientId", "userId", "grantId", "identity"]
16
+ for source as key: value
17
+ if !allowed.includes(key)
18
+ throw "Unknown execution source field: ${key}"
19
+ if key != "kind" and (!is_string(value) or value.trim() == "")
20
+ throw "Execution source references must be nonempty strings"
21
+ switch source.kind
22
+ case "user"
23
+ if source.clientId == null or source.identity != null
24
+ throw "User execution source requires clientId and cannot select a system identity"
25
+ case "system"
26
+ if source.identity == null or source.clientId != null or source.userId != null or source.grantId != null
27
+ throw "System execution source requires only a configured identity"
28
+ else
29
+ throw "Execution source kind must be user or system"
30
+ return from_json(to_json(source))
31
+
32
+ executionToken(identity, source, route)
33
+ if identity == null or identity == false
34
+ throw new ExecutionFailure("IdentityRejected")
35
+ if !is_object(identity) or is_array(identity)
36
+ throw "Identity provider must return a map or null"
37
+ allowed = ["clientId", "userId", "grantId", "identity", "policies", "authenticatedAt"]
38
+ for identity as key: value
39
+ if !allowed.includes(key)
40
+ throw "Unknown execution identity field: ${key}"
41
+ if !is_array(identity.policies)
42
+ throw "Execution identity requires a policies array"
43
+ if source.kind == "user"
44
+ for ["clientId", "userId", "grantId"] as key
45
+ if identity[key] != source[key]
46
+ throw new ExecutionFailure("IdentityChanged")
47
+ if identity.identity != null
48
+ throw new ExecutionFailure("IdentityChanged")
49
+ else
50
+ if identity.identity != source.identity or identity.clientId != null or identity.userId != null or identity.grantId != null
51
+ throw new ExecutionFailure("IdentityChanged")
52
+ now = Date/now()
53
+ stamp = identity.authenticatedAt
54
+ if stamp != null and (!Number/isSafeInteger(stamp) or stamp < 0 or stamp > now)
55
+ throw "Execution identity authenticatedAt must be a real past timestamp"
56
+ claims = {
57
+ clientId: identity.clientId
58
+ userId: identity.userId
59
+ grantId: identity.grantId
60
+ identity: identity.identity
61
+ auth: ""
62
+ authenticatedAt: stamp
63
+ }
64
+ token = new Token(claims)
65
+ for identity.policies as policy
66
+ token.addPolicy(policy)
67
+ if route.policy != "anonymous" and !token.hasPolicy(route.policy)
68
+ throw new ExecutionFailure("Forbidden")
69
+ if route.reauthSeconds > 0 and (stamp == null or now - stamp >= route.reauthSeconds * 1000)
70
+ throw new ExecutionFailure("ReauthenticationRequired")
71
+ return new Token(token.snapshot(), true)
@@ -0,0 +1,28 @@
1
+ export class ExecutionLog(sink, job)
2
+ properties
3
+ verbose?
4
+ methods
5
+ debug(message)
6
+ info(message)
7
+ warn(message)
8
+ err(message)
9
+
10
+ ExecutionLog(sink, job)
11
+ @sink = sink
12
+ source = job.source?
13
+ @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}"
14
+
15
+ ExecutionLog:verbose?
16
+ return @sink.verbose?
17
+
18
+ ExecutionLog:debug(message)
19
+ return @sink.debug("${@prefix} ${message}")
20
+
21
+ ExecutionLog:info(message)
22
+ return @sink.info("${@prefix} ${message}")
23
+
24
+ ExecutionLog:warn(message)
25
+ return @sink.warn("${@prefix} ${message}")
26
+
27
+ ExecutionLog:err(message)
28
+ return @sink.err("${@prefix} ${message}")
@@ -0,0 +1,135 @@
1
+ import "./module_loader"
2
+ class ModuleLoader
3
+ import "./database"
4
+ class Database
5
+ import "./execution_identity"
6
+ executionSource(source)
7
+ executionToken(identity, source, route)
8
+ import "./execution_failure"
9
+ class ExecutionFailure
10
+ import "./job_context"
11
+ class JobContext
12
+ import "./execution_log"
13
+ class ExecutionLog
14
+ import "./error_details"
15
+ errorDetails(error)
16
+ import js global Promise
17
+ import js global Object
18
+
19
+ export class ExecutionRuntime(definition)
20
+ methods
21
+ preload()
22
+ execute(task)
23
+ close()
24
+
25
+ ExecutionRuntime(definition)
26
+ @definition = definition
27
+ @loader = new ModuleLoader()
28
+ @database = new Database(definition.database, definition.root)
29
+ @handlers = Object/create(null)
30
+ @identity = null
31
+ @queueFactory = null
32
+
33
+ ExecutionRuntime:preload()
34
+ pending = @database.open()
35
+ for @definition.targets as route
36
+ pending = prepare(pending, route)
37
+ return chain pending
38
+ then(ignored)
39
+ return @loader.target(@definition.identity)
40
+ then(handler)
41
+ @identity = handler
42
+ if @definition.queueProvider != null
43
+ return @loader.target(@definition.queueProvider)
44
+ return null
45
+ then(factory)
46
+ @queueFactory = factory
47
+ return null
48
+ catch(error)
49
+ close()
50
+ throw error
51
+
52
+ ExecutionRuntime:prepare(pending, route)
53
+ return chain pending
54
+ then(ignored)
55
+ capture route
56
+ return @loader.target(route)
57
+ then(handler)
58
+ capture route
59
+ @handlers[route.path] = handler
60
+ return null
61
+
62
+ ExecutionRuntime:execute(task)
63
+ context db = @database.scope()
64
+ context log
65
+ route = null
66
+ for @definition.targets as target
67
+ if target.path == task.path
68
+ route = target
69
+ if route == null
70
+ if db != null
71
+ db.finish()
72
+ throw "Unregistered execution path"
73
+ context job = new JobContext(task, route)
74
+ sink = log
75
+ context log = new ExecutionLog(sink, job)
76
+ return chain Promise/resolve(null)
77
+ then(ignored)
78
+ capture task
79
+ capture route
80
+ source = executionSource(task.source)
81
+ Object/freeze(source)
82
+ target = Object/freeze({
83
+ path: route.path
84
+ queue: route.queue
85
+ policy: route.policy
86
+ reauthSeconds: route.reauthSeconds
87
+ })
88
+ handler = @identity
89
+ return handler({
90
+ source: source
91
+ route: target
92
+ })
93
+ then(identity)
94
+ capture task
95
+ capture route
96
+ context token = executionToken(identity, task.source, route)
97
+ if task.authorize == true
98
+ return null
99
+ sender = null
100
+ if @queueFactory != null
101
+ factory = @queueFactory
102
+ sender = factory(@definition.queueProvider.options)
103
+ context queue = sender
104
+ handler = @handlers[route.path]
105
+ return handler(task.input)
106
+ then(output)
107
+ body = to_json(output)
108
+ if !is_string(body)
109
+ throw "Execution output is not JSON serializable"
110
+ if db != null and db.finish()
111
+ throw "UnclosedTransaction"
112
+ return {
113
+ ok: true
114
+ output: from_json(body)
115
+ }
116
+ catch(error)
117
+ capture ExecutionFailure
118
+ permanent = is_kindof(error, ExecutionFailure)
119
+ code = "ExecutionFailed"
120
+ if permanent
121
+ code = error.code?
122
+ log.err("code=${code}: ${errorDetails(error)}")
123
+ return {
124
+ ok: false
125
+ code: code
126
+ permanent: permanent
127
+ message: errorDetails(error)
128
+ }
129
+ finally
130
+ if db != null
131
+ db.finish()
132
+
133
+ ExecutionRuntime:close()
134
+ @database.close()
135
+ return null
@@ -0,0 +1,32 @@
1
+ import "./execution_runtime"
2
+ class ExecutionRuntime
3
+ import js "node:worker_threads" as threads
4
+ import js global process
5
+
6
+ export global execute
7
+
8
+ global runtime = new ExecutionRuntime(threads.workerData)
9
+ global execute = initialize()
10
+
11
+ initialize()
12
+ global runtime
13
+ process.setSourceMapsEnabled(true)
14
+ process.once("exit", ()
15
+ global runtime
16
+ runtime.close()
17
+ )
18
+ return chain runtime.preload()
19
+ then(ignored)
20
+ capture threads
21
+ threads/parentPort/postMessage({
22
+ kind: "ready"
23
+ threadId: threads.threadId
24
+ })
25
+ return workerHandler()
26
+
27
+ workerHandler()
28
+ return run
29
+
30
+ run(task)
31
+ global runtime
32
+ return runtime.execute(task)
@@ -0,0 +1,284 @@
1
+ import "./job_configuration"
2
+ readDatabaseConfiguration(directory)
3
+ readJobRoutes(directory)
4
+ import "./execution_identity"
5
+ executionSource(source)
6
+ import "./queue_provider"
7
+ queueProvider(root, spec)
8
+ import "./error_details"
9
+ errorDetails(error)
10
+ import js "node:path" as path
11
+ import js "node:module" as modules
12
+ import js "piscina" as piscina
13
+ import js global Object
14
+ import js global Number
15
+ import js global Promise
16
+ import js global Error
17
+ import js global AbortController
18
+ import js global AbortSignal
19
+ import js global setTimeout
20
+ import js global clearTimeout
21
+
22
+ export class Executor(directory, settings)
23
+ methods
24
+ start()
25
+ execute(task, options = null)
26
+ authorize(task, options = null)
27
+ close()
28
+
29
+ Executor(directory, settings)
30
+ if !is_string(directory) or directory == ""
31
+ throw "Executor requires an application directory"
32
+ if settings == null or !is_object(settings) or is_array(settings)
33
+ throw "Executor requires settings and an identity provider"
34
+ allowed = ["identity", "workers", "maxQueue", "timeoutMs", "startupTimeoutMs", "shutdownTimeoutMs", "queueProvider"]
35
+ for settings as key: value
36
+ if !allowed.includes(key)
37
+ throw "Unknown executor option: ${key}"
38
+ root = path/resolve(directory)
39
+ @definition = {
40
+ root: root
41
+ database: readDatabaseConfiguration(root)
42
+ targets: readJobRoutes(root)
43
+ identity: provider(root, settings.identity)
44
+ queueProvider: queueProvider(root, settings.queueProvider)
45
+ }
46
+ @workers = limit(settings.workers, 2, 1, 128, "workers")
47
+ @maxQueue = limit(settings.maxQueue, 64, 0, 2147483647, "maxQueue")
48
+ @timeout = limit(settings.timeoutMs, 900000, 1, 2147483647, "timeoutMs")
49
+ @startupTimeout = limit(settings.startupTimeoutMs, 30000, 1, 2147483647, "startupTimeoutMs")
50
+ @shutdownTimeout = limit(settings.shutdownTimeoutMs, 30000, 1, 2147483647, "shutdownTimeoutMs")
51
+ @state = "new"
52
+ @pool = null
53
+ @closing = null
54
+ @closeError = null
55
+ @ready = Promise/withResolvers()
56
+ @readyIds = []
57
+
58
+ provider(root, spec)
59
+ if spec == null or !is_object(spec) or is_array(spec)
60
+ throw "Executor identity provider requires module and handler"
61
+ for spec as key: value
62
+ if key != "module" and key != "handler"
63
+ throw "Unknown identity provider option: ${key}"
64
+ if !is_string(spec.module) or spec.module == "" or spec.module.startsWith("node:") or !is_string(spec.handler) or spec.handler == ""
65
+ throw "Executor identity provider requires module and handler"
66
+ resolver = modules/createRequire(path/join(root, "package.json"))
67
+ file = resolver.resolve(spec.module)
68
+ if !path/isAbsolute(file)
69
+ throw "Identity provider must resolve to an application module"
70
+ return {
71
+ module: file
72
+ handler: spec.handler
73
+ }
74
+
75
+ limit(value, fallback, minimum, maximum, name)
76
+ if value == null
77
+ return fallback
78
+ if !Number/isSafeInteger(value) or value < minimum or value > maximum
79
+ throw "Invalid executor option: ${name}"
80
+ return value
81
+
82
+ Executor:start()
83
+ if @state != "new"
84
+ return Promise/reject("Executor can only be started once")
85
+ @state = "starting"
86
+ try
87
+ resolver = modules/createRequire(path/join(@definition.root, "package.json"))
88
+ entry = resolver.resolve("@lango-project/lango-server")
89
+ @pool = new piscina/Piscina({
90
+ filename: path/join(path/dirname(entry), "execution_worker.mjs")
91
+ name: "execute"
92
+ minThreads: @workers
93
+ maxThreads: @workers
94
+ maxQueue: @maxQueue
95
+ concurrentTasksPerWorker: 1
96
+ closeTimeout: @shutdownTimeout
97
+ workerData: @definition
98
+ })
99
+ pool = @pool
100
+ pool.on("message", (message)
101
+ if message.kind == "ready" and !@readyIds.includes(message.threadId)
102
+ @readyIds.add(message.threadId)
103
+ if @readyIds.length == @workers
104
+ @ready.resolve(null)
105
+ )
106
+ pool.on("error", (error)
107
+ @ready.reject(error)
108
+ if @state == "closing"
109
+ @closeError = error
110
+ context log
111
+ log.err("Execution worker error: ${errorDetails(error)}")
112
+ )
113
+ catch error
114
+ @state = "closed"
115
+ return Promise/reject(error)
116
+ expire = ()
117
+ @ready.reject("Executor startup timed out")
118
+ timer = setTimeout(expire, @startupTimeout)
119
+ return chain @ready.promise
120
+ then(ignored)
121
+ if @state != "starting"
122
+ throw "Executor closed during startup"
123
+ @state = "running"
124
+ return null
125
+ catch(error)
126
+ return chain destroy()
127
+ then(ignored)
128
+ capture error
129
+ @state = "closed"
130
+ throw error
131
+ finally
132
+ capture timer
133
+ clearTimeout(timer)
134
+
135
+ Executor:execute(task, options = null)
136
+ return run(task, options, false)
137
+
138
+ Executor:authorize(task, options = null)
139
+ return run(task, options, true)
140
+
141
+ Executor:run(task, options, authorize)
142
+ if @state != "running"
143
+ return Promise/reject("Executor is not running")
144
+ try
145
+ task = validateTask(task, @definition.targets)
146
+ task.authorize = authorize
147
+ options = executionOptions(options, @timeout)
148
+ catch error
149
+ return Promise/reject(error)
150
+ controller = new AbortController()
151
+ status = {
152
+ expired: false
153
+ }
154
+ signal = options.signal
155
+ abort = ()
156
+ capture controller
157
+ controller.abort()
158
+ if signal != null
159
+ signal.addEventListener("abort", abort, {
160
+ once: true
161
+ })
162
+ if signal.aborted
163
+ controller.abort()
164
+ expire = ()
165
+ capture controller
166
+ capture status
167
+ if status.expired
168
+ return null
169
+ status.expired = true
170
+ controller.abort()
171
+ timer = setTimeout(expire, options.timeoutMs)
172
+ return chain @pool.run(task, {
173
+ signal: controller.signal
174
+ })
175
+ then(result)
176
+ if !result.ok
177
+ error = new Error(result.message)
178
+ error.code = result.code
179
+ error.permanent = result.permanent
180
+ error.logged = true
181
+ throw error
182
+ return result.output
183
+ catch(error)
184
+ capture status
185
+ capture task
186
+ capture signal
187
+ if status.expired
188
+ error = new Error("Execution attempt timed out")
189
+ error.code = "ExecutionTimeout"
190
+ error.permanent = false
191
+ else
192
+ if signal != null and signal.aborted
193
+ error = new Error("Execution attempt was aborted")
194
+ error.code = "ExecutionAborted"
195
+ error.permanent = false
196
+ if !is_object(error)
197
+ error = new Error("${error}")
198
+ if error.permanent != true
199
+ error.permanent = false
200
+ context log
201
+ if error.logged != true
202
+ source = task.source
203
+ log.err("[jobId=${task.id}] path=${task.path} attempt=${task.attempt} clientId=${source.clientId} userId=${source.userId} identity=${source.identity}: ${errorDetails(error)}")
204
+ throw error
205
+ finally
206
+ capture timer
207
+ capture signal
208
+ capture abort
209
+ clearTimeout(timer)
210
+ if signal != null
211
+ signal.removeEventListener("abort", abort)
212
+
213
+ executionOptions(options, timeout)
214
+ if options == null
215
+ options = {}
216
+ if !is_object(options) or is_array(options)
217
+ throw "Execution options must be a map"
218
+ for options as key: value
219
+ if key != "signal" and key != "timeoutMs"
220
+ throw "Unknown execution option: ${key}"
221
+ if options.signal != null and !is_kindof(options.signal, AbortSignal)
222
+ throw "Execution signal must be an AbortSignal"
223
+ return {
224
+ signal: options.signal
225
+ timeoutMs: limit(options.timeoutMs, timeout, 1, 2147483647, "timeoutMs")
226
+ }
227
+
228
+ validateTask(task, targets)
229
+ if task == null or !is_object(task) or is_array(task)
230
+ throw "Execution task must be a map"
231
+ allowed = ["id", "path", "input", "source", "attempt"]
232
+ for task as key: value
233
+ if !allowed.includes(key)
234
+ throw "Unknown execution task option: ${key}"
235
+ if !is_string(task.id) or task.id == "" or task.id.length > 200
236
+ throw "Execution task requires a job id"
237
+ found = false
238
+ for targets as route
239
+ if route.path == task.path
240
+ found = true
241
+ if !found
242
+ throw "Unregistered execution path"
243
+ if task.input == null or !is_object(task.input) or is_array(task.input)
244
+ throw "Execution input must be a JSON map"
245
+ return {
246
+ id: task.id
247
+ path: task.path
248
+ input: from_json(to_json(task.input))
249
+ source: executionSource(task.source)
250
+ attempt: limit(task.attempt, 1, 1, 2147483647, "attempt")
251
+ }
252
+
253
+ Executor:close()
254
+ if @closing != null
255
+ return @closing
256
+ if @state == "closed" or @state == "new"
257
+ @state = "closed"
258
+ return Promise/resolve(null)
259
+ state = @state
260
+ @state = "closing"
261
+ if state == "starting"
262
+ @ready.reject("Executor closed during startup")
263
+ @closing = destroy()
264
+ else
265
+ @closing = drain()
266
+ return @closing
267
+
268
+ Executor:drain()
269
+ return chain @pool.close()
270
+ then(ignored)
271
+ if @closeError != null
272
+ throw @closeError
273
+ return null
274
+ finally
275
+ return destroy()
276
+ finally
277
+ @state = "closed"
278
+
279
+ Executor:destroy()
280
+ if @pool == null
281
+ return Promise/resolve(null)
282
+ pool = @pool
283
+ @pool = null
284
+ return pool.destroy()