@contember/engine-actions 2.2.0-alpha.2 → 2.2.0-alpha.20

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 (281) hide show
  1. package/CLAUDE.md +95 -0
  2. package/dist/development/index.cjs +28 -13
  3. package/dist/development/index.cjs.map +1 -1
  4. package/dist/development/index.js +29 -14
  5. package/dist/development/index.js.map +1 -1
  6. package/dist/development/src/ActionsExecutionContainerHookFactory.cjs +14 -2
  7. package/dist/development/src/ActionsExecutionContainerHookFactory.cjs.map +1 -1
  8. package/dist/development/src/ActionsExecutionContainerHookFactory.js +14 -2
  9. package/dist/development/src/ActionsExecutionContainerHookFactory.js.map +1 -1
  10. package/dist/development/src/ActionsMetrics.cjs +98 -0
  11. package/dist/development/src/ActionsMetrics.cjs.map +1 -0
  12. package/dist/development/src/ActionsMetrics.js +98 -0
  13. package/dist/development/src/ActionsMetrics.js.map +1 -0
  14. package/dist/development/src/dispatch/EventDispatcher.cjs +93 -24
  15. package/dist/development/src/dispatch/EventDispatcher.cjs.map +1 -1
  16. package/dist/development/src/dispatch/EventDispatcher.js +93 -24
  17. package/dist/development/src/dispatch/EventDispatcher.js.map +1 -1
  18. package/dist/development/src/dispatch/EventsRepository.cjs +87 -22
  19. package/dist/development/src/dispatch/EventsRepository.cjs.map +1 -1
  20. package/dist/development/src/dispatch/EventsRepository.js +87 -22
  21. package/dist/development/src/dispatch/EventsRepository.js.map +1 -1
  22. package/dist/development/src/dispatch/ProjectDispatcher.cjs +63 -21
  23. package/dist/development/src/dispatch/ProjectDispatcher.cjs.map +1 -1
  24. package/dist/development/src/dispatch/ProjectDispatcher.js +63 -21
  25. package/dist/development/src/dispatch/ProjectDispatcher.js.map +1 -1
  26. package/dist/development/src/dispatch/WebhookFetcher.cjs +6 -1
  27. package/dist/development/src/dispatch/WebhookFetcher.cjs.map +1 -1
  28. package/dist/development/src/dispatch/WebhookFetcher.js +7 -2
  29. package/dist/development/src/dispatch/WebhookFetcher.js.map +1 -1
  30. package/dist/development/src/dispatch/WebhookTargetHandler.cjs +154 -25
  31. package/dist/development/src/dispatch/WebhookTargetHandler.cjs.map +1 -1
  32. package/dist/development/src/dispatch/WebhookTargetHandler.js +154 -25
  33. package/dist/development/src/dispatch/WebhookTargetHandler.js.map +1 -1
  34. package/dist/development/src/dispatch/redactRequestError.cjs +49 -0
  35. package/dist/development/src/dispatch/redactRequestError.cjs.map +1 -0
  36. package/dist/development/src/dispatch/redactRequestError.js +49 -0
  37. package/dist/development/src/dispatch/redactRequestError.js.map +1 -0
  38. package/dist/development/src/dispatch/truncateText.cjs +12 -0
  39. package/dist/development/src/dispatch/truncateText.cjs.map +1 -0
  40. package/dist/development/src/dispatch/truncateText.js +12 -0
  41. package/dist/development/src/dispatch/truncateText.js.map +1 -0
  42. package/dist/development/src/graphql/http/ActionsGraphQLHandlerFactory.cjs +1 -1
  43. package/dist/development/src/graphql/http/ActionsGraphQLHandlerFactory.cjs.map +1 -1
  44. package/dist/development/src/graphql/http/ActionsGraphQLHandlerFactory.js +2 -2
  45. package/dist/development/src/graphql/http/ActionsGraphQLHandlerFactory.js.map +1 -1
  46. package/dist/development/src/graphql/http/ActionsWebsocketControllerFactory.cjs +68 -28
  47. package/dist/development/src/graphql/http/ActionsWebsocketControllerFactory.cjs.map +1 -1
  48. package/dist/development/src/graphql/http/ActionsWebsocketControllerFactory.js +68 -28
  49. package/dist/development/src/graphql/http/ActionsWebsocketControllerFactory.js.map +1 -1
  50. package/dist/development/src/graphql/resolvers/ResolversFactory.cjs +1 -1
  51. package/dist/development/src/graphql/resolvers/ResolversFactory.cjs.map +1 -1
  52. package/dist/development/src/graphql/resolvers/ResolversFactory.js +1 -1
  53. package/dist/development/src/graphql/resolvers/ResolversFactory.js.map +1 -1
  54. package/dist/development/src/graphql/resolvers/mutation/SetVariablesMutationResolver.cjs +7 -2
  55. package/dist/development/src/graphql/resolvers/mutation/SetVariablesMutationResolver.cjs.map +1 -1
  56. package/dist/development/src/graphql/resolvers/mutation/SetVariablesMutationResolver.js +7 -2
  57. package/dist/development/src/graphql/resolvers/mutation/SetVariablesMutationResolver.js.map +1 -1
  58. package/dist/development/src/graphql/resolvers/query/EventsQueryResolver.cjs +1 -1
  59. package/dist/development/src/graphql/resolvers/query/EventsQueryResolver.cjs.map +1 -1
  60. package/dist/development/src/graphql/resolvers/query/EventsQueryResolver.js +1 -1
  61. package/dist/development/src/graphql/resolvers/query/EventsQueryResolver.js.map +1 -1
  62. package/dist/development/src/graphql/resolvers/query/VariablesQueryResolver.cjs +1 -4
  63. package/dist/development/src/graphql/resolvers/query/VariablesQueryResolver.cjs.map +1 -1
  64. package/dist/development/src/graphql/resolvers/query/VariablesQueryResolver.js +1 -4
  65. package/dist/development/src/graphql/resolvers/query/VariablesQueryResolver.js.map +1 -1
  66. package/dist/development/src/graphql/schema/actions.graphql.cjs +27 -11
  67. package/dist/development/src/graphql/schema/actions.graphql.cjs.map +1 -1
  68. package/dist/development/src/graphql/schema/actions.graphql.js +27 -11
  69. package/dist/development/src/graphql/schema/actions.graphql.js.map +1 -1
  70. package/dist/development/src/model/VariablesManager.cjs +59 -5
  71. package/dist/development/src/model/VariablesManager.cjs.map +1 -1
  72. package/dist/development/src/model/VariablesManager.js +60 -6
  73. package/dist/development/src/model/VariablesManager.js.map +1 -1
  74. package/dist/development/src/triggers/TriggerPayloadPersister.cjs +3 -1
  75. package/dist/development/src/triggers/TriggerPayloadPersister.cjs.map +1 -1
  76. package/dist/development/src/triggers/TriggerPayloadPersister.js +3 -1
  77. package/dist/development/src/triggers/TriggerPayloadPersister.js.map +1 -1
  78. package/dist/production/index.cjs +28 -13
  79. package/dist/production/index.cjs.map +1 -1
  80. package/dist/production/index.js +29 -14
  81. package/dist/production/index.js.map +1 -1
  82. package/dist/production/src/ActionsExecutionContainerHookFactory.cjs +14 -2
  83. package/dist/production/src/ActionsExecutionContainerHookFactory.cjs.map +1 -1
  84. package/dist/production/src/ActionsExecutionContainerHookFactory.js +14 -2
  85. package/dist/production/src/ActionsExecutionContainerHookFactory.js.map +1 -1
  86. package/dist/production/src/ActionsMetrics.cjs +98 -0
  87. package/dist/production/src/ActionsMetrics.cjs.map +1 -0
  88. package/dist/production/src/ActionsMetrics.js +98 -0
  89. package/dist/production/src/ActionsMetrics.js.map +1 -0
  90. package/dist/production/src/dispatch/EventDispatcher.cjs +93 -24
  91. package/dist/production/src/dispatch/EventDispatcher.cjs.map +1 -1
  92. package/dist/production/src/dispatch/EventDispatcher.js +93 -24
  93. package/dist/production/src/dispatch/EventDispatcher.js.map +1 -1
  94. package/dist/production/src/dispatch/EventsRepository.cjs +87 -22
  95. package/dist/production/src/dispatch/EventsRepository.cjs.map +1 -1
  96. package/dist/production/src/dispatch/EventsRepository.js +87 -22
  97. package/dist/production/src/dispatch/EventsRepository.js.map +1 -1
  98. package/dist/production/src/dispatch/ProjectDispatcher.cjs +63 -21
  99. package/dist/production/src/dispatch/ProjectDispatcher.cjs.map +1 -1
  100. package/dist/production/src/dispatch/ProjectDispatcher.js +63 -21
  101. package/dist/production/src/dispatch/ProjectDispatcher.js.map +1 -1
  102. package/dist/production/src/dispatch/WebhookFetcher.cjs +6 -1
  103. package/dist/production/src/dispatch/WebhookFetcher.cjs.map +1 -1
  104. package/dist/production/src/dispatch/WebhookFetcher.js +7 -2
  105. package/dist/production/src/dispatch/WebhookFetcher.js.map +1 -1
  106. package/dist/production/src/dispatch/WebhookTargetHandler.cjs +154 -25
  107. package/dist/production/src/dispatch/WebhookTargetHandler.cjs.map +1 -1
  108. package/dist/production/src/dispatch/WebhookTargetHandler.js +154 -25
  109. package/dist/production/src/dispatch/WebhookTargetHandler.js.map +1 -1
  110. package/dist/production/src/dispatch/redactRequestError.cjs +49 -0
  111. package/dist/production/src/dispatch/redactRequestError.cjs.map +1 -0
  112. package/dist/production/src/dispatch/redactRequestError.js +49 -0
  113. package/dist/production/src/dispatch/redactRequestError.js.map +1 -0
  114. package/dist/production/src/dispatch/truncateText.cjs +12 -0
  115. package/dist/production/src/dispatch/truncateText.cjs.map +1 -0
  116. package/dist/production/src/dispatch/truncateText.js +12 -0
  117. package/dist/production/src/dispatch/truncateText.js.map +1 -0
  118. package/dist/production/src/graphql/http/ActionsGraphQLHandlerFactory.cjs +1 -1
  119. package/dist/production/src/graphql/http/ActionsGraphQLHandlerFactory.cjs.map +1 -1
  120. package/dist/production/src/graphql/http/ActionsGraphQLHandlerFactory.js +2 -2
  121. package/dist/production/src/graphql/http/ActionsGraphQLHandlerFactory.js.map +1 -1
  122. package/dist/production/src/graphql/http/ActionsWebsocketControllerFactory.cjs +68 -28
  123. package/dist/production/src/graphql/http/ActionsWebsocketControllerFactory.cjs.map +1 -1
  124. package/dist/production/src/graphql/http/ActionsWebsocketControllerFactory.js +68 -28
  125. package/dist/production/src/graphql/http/ActionsWebsocketControllerFactory.js.map +1 -1
  126. package/dist/production/src/graphql/resolvers/ResolversFactory.cjs +1 -1
  127. package/dist/production/src/graphql/resolvers/ResolversFactory.cjs.map +1 -1
  128. package/dist/production/src/graphql/resolvers/ResolversFactory.js +1 -1
  129. package/dist/production/src/graphql/resolvers/ResolversFactory.js.map +1 -1
  130. package/dist/production/src/graphql/resolvers/mutation/SetVariablesMutationResolver.cjs +7 -2
  131. package/dist/production/src/graphql/resolvers/mutation/SetVariablesMutationResolver.cjs.map +1 -1
  132. package/dist/production/src/graphql/resolvers/mutation/SetVariablesMutationResolver.js +7 -2
  133. package/dist/production/src/graphql/resolvers/mutation/SetVariablesMutationResolver.js.map +1 -1
  134. package/dist/production/src/graphql/resolvers/query/EventsQueryResolver.cjs +1 -1
  135. package/dist/production/src/graphql/resolvers/query/EventsQueryResolver.cjs.map +1 -1
  136. package/dist/production/src/graphql/resolvers/query/EventsQueryResolver.js +1 -1
  137. package/dist/production/src/graphql/resolvers/query/EventsQueryResolver.js.map +1 -1
  138. package/dist/production/src/graphql/resolvers/query/VariablesQueryResolver.cjs +1 -4
  139. package/dist/production/src/graphql/resolvers/query/VariablesQueryResolver.cjs.map +1 -1
  140. package/dist/production/src/graphql/resolvers/query/VariablesQueryResolver.js +1 -4
  141. package/dist/production/src/graphql/resolvers/query/VariablesQueryResolver.js.map +1 -1
  142. package/dist/production/src/graphql/schema/actions.graphql.cjs +27 -11
  143. package/dist/production/src/graphql/schema/actions.graphql.cjs.map +1 -1
  144. package/dist/production/src/graphql/schema/actions.graphql.js +27 -11
  145. package/dist/production/src/graphql/schema/actions.graphql.js.map +1 -1
  146. package/dist/production/src/model/VariablesManager.cjs +59 -5
  147. package/dist/production/src/model/VariablesManager.cjs.map +1 -1
  148. package/dist/production/src/model/VariablesManager.js +60 -6
  149. package/dist/production/src/model/VariablesManager.js.map +1 -1
  150. package/dist/production/src/triggers/TriggerPayloadPersister.cjs +3 -1
  151. package/dist/production/src/triggers/TriggerPayloadPersister.cjs.map +1 -1
  152. package/dist/production/src/triggers/TriggerPayloadPersister.js +3 -1
  153. package/dist/production/src/triggers/TriggerPayloadPersister.js.map +1 -1
  154. package/dist/tests/cases/unit/actionsMetrics.test.d.ts +2 -0
  155. package/dist/tests/cases/unit/actionsMetrics.test.d.ts.map +1 -0
  156. package/dist/tests/cases/unit/actionsWebsocketController.test.d.ts +2 -0
  157. package/dist/tests/cases/unit/actionsWebsocketController.test.d.ts.map +1 -0
  158. package/dist/tests/cases/unit/dispatchTracing.test.d.ts +2 -0
  159. package/dist/tests/cases/unit/dispatchTracing.test.d.ts.map +1 -0
  160. package/dist/tests/cases/unit/eventsRepository.test.d.ts +2 -0
  161. package/dist/tests/cases/unit/eventsRepository.test.d.ts.map +1 -0
  162. package/dist/tests/cases/unit/projectDispatcher.test.d.ts +2 -0
  163. package/dist/tests/cases/unit/projectDispatcher.test.d.ts.map +1 -0
  164. package/dist/tests/cases/unit/redactRequestError.test.d.ts +2 -0
  165. package/dist/tests/cases/unit/redactRequestError.test.d.ts.map +1 -0
  166. package/dist/tests/cases/unit/truncateText.test.d.ts +2 -0
  167. package/dist/tests/cases/unit/truncateText.test.d.ts.map +1 -0
  168. package/dist/tests/cases/unit/variablesManager.test.d.ts +2 -0
  169. package/dist/tests/cases/unit/variablesManager.test.d.ts.map +1 -0
  170. package/dist/tests/cases/unit/webhookEgress.test.d.ts +2 -0
  171. package/dist/tests/cases/unit/webhookEgress.test.d.ts.map +1 -0
  172. package/dist/tests/cases/unit/webhookTracing.test.d.ts +2 -0
  173. package/dist/tests/cases/unit/webhookTracing.test.d.ts.map +1 -0
  174. package/dist/tests/src/event.d.ts +4 -0
  175. package/dist/tests/src/event.d.ts.map +1 -0
  176. package/dist/tests/src/gql.d.ts.map +1 -1
  177. package/dist/tests/src/tracer.d.ts +7 -0
  178. package/dist/tests/src/tracer.d.ts.map +1 -0
  179. package/dist/tests/src/utils.d.ts +6 -0
  180. package/dist/tests/src/utils.d.ts.map +1 -0
  181. package/dist/tests/src/uuid.d.ts.map +1 -1
  182. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  183. package/dist/types/ActionsExecutionContainerHookFactory.d.ts +3 -1
  184. package/dist/types/ActionsExecutionContainerHookFactory.d.ts.map +1 -1
  185. package/dist/types/ActionsMetrics.d.ts +59 -0
  186. package/dist/types/ActionsMetrics.d.ts.map +1 -0
  187. package/dist/types/ListenerStoreProvider.d.ts.map +1 -1
  188. package/dist/types/authorization/ActionsPermissionsFactory.d.ts.map +1 -1
  189. package/dist/types/dispatch/DispatchWorkerSupervisor.d.ts.map +1 -1
  190. package/dist/types/dispatch/EventDispatcher.d.ts +15 -4
  191. package/dist/types/dispatch/EventDispatcher.d.ts.map +1 -1
  192. package/dist/types/dispatch/EventsRepository.d.ts +34 -3
  193. package/dist/types/dispatch/EventsRepository.d.ts.map +1 -1
  194. package/dist/types/dispatch/LazyDispatchWorker.d.ts.map +1 -1
  195. package/dist/types/dispatch/ProjectDispatcher.d.ts +10 -2
  196. package/dist/types/dispatch/ProjectDispatcher.d.ts.map +1 -1
  197. package/dist/types/dispatch/TargetHandlerResolver.d.ts.map +1 -1
  198. package/dist/types/dispatch/WebhookFetcher.d.ts +7 -2
  199. package/dist/types/dispatch/WebhookFetcher.d.ts.map +1 -1
  200. package/dist/types/dispatch/WebhookTargetHandler.d.ts +14 -1
  201. package/dist/types/dispatch/WebhookTargetHandler.d.ts.map +1 -1
  202. package/dist/types/dispatch/redactRequestError.d.ts +8 -0
  203. package/dist/types/dispatch/redactRequestError.d.ts.map +1 -0
  204. package/dist/types/dispatch/truncateText.d.ts +6 -0
  205. package/dist/types/dispatch/truncateText.d.ts.map +1 -0
  206. package/dist/types/graphql/http/ActionsApiMiddlewareFactory.d.ts.map +1 -1
  207. package/dist/types/graphql/http/ActionsContextResolver.d.ts.map +1 -1
  208. package/dist/types/graphql/http/ActionsGraphQLHandlerFactory.d.ts.map +1 -1
  209. package/dist/types/graphql/http/ActionsWebsocketControllerFactory.d.ts +7 -5
  210. package/dist/types/graphql/http/ActionsWebsocketControllerFactory.d.ts.map +1 -1
  211. package/dist/types/graphql/resolvers/ResolversFactory.d.ts.map +1 -1
  212. package/dist/types/graphql/resolvers/mutation/ProcessBatchMutationResolver.d.ts.map +1 -1
  213. package/dist/types/graphql/resolvers/mutation/RetryEventMutationResolver.d.ts.map +1 -1
  214. package/dist/types/graphql/resolvers/mutation/SetVariablesMutationResolver.d.ts +3 -1
  215. package/dist/types/graphql/resolvers/mutation/SetVariablesMutationResolver.d.ts.map +1 -1
  216. package/dist/types/graphql/resolvers/mutation/StopEventMutationResolver.d.ts.map +1 -1
  217. package/dist/types/graphql/resolvers/query/EventsQueryResolver.d.ts.map +1 -1
  218. package/dist/types/graphql/resolvers/query/VariablesQueryResolver.d.ts +1 -4
  219. package/dist/types/graphql/resolvers/query/VariablesQueryResolver.d.ts.map +1 -1
  220. package/dist/types/graphql/schema/actions.graphql.d.ts.map +1 -1
  221. package/dist/types/graphql/schema/index.d.ts +27 -17
  222. package/dist/types/graphql/schema/index.d.ts.map +1 -1
  223. package/dist/types/index.d.ts +6 -0
  224. package/dist/types/index.d.ts.map +1 -1
  225. package/dist/types/model/EventByIdQuery.d.ts.map +1 -1
  226. package/dist/types/model/EventsInProcessingQuery.d.ts.map +1 -1
  227. package/dist/types/model/EventsToProcessQuery.d.ts.map +1 -1
  228. package/dist/types/model/FailedEventsQuery.d.ts.map +1 -1
  229. package/dist/types/model/SetVariableCommand.d.ts.map +1 -1
  230. package/dist/types/model/VariablesManager.d.ts +18 -3
  231. package/dist/types/model/VariablesManager.d.ts.map +1 -1
  232. package/dist/types/model/VariablesQuery.d.ts.map +1 -1
  233. package/dist/types/triggers/TriggerHandler.d.ts.map +1 -1
  234. package/dist/types/triggers/TriggerIndirectChangesFetcher.d.ts.map +1 -1
  235. package/dist/types/triggers/TriggerListenersBuilder.d.ts.map +1 -1
  236. package/dist/types/triggers/TriggerListenersFactory.d.ts.map +1 -1
  237. package/dist/types/triggers/TriggerListenersStore.d.ts.map +1 -1
  238. package/dist/types/triggers/TriggerPayloadBuilder.d.ts.map +1 -1
  239. package/dist/types/triggers/TriggerPayloadManager.d.ts.map +1 -1
  240. package/dist/types/triggers/TriggerPayloadPersister.d.ts +3 -1
  241. package/dist/types/triggers/TriggerPayloadPersister.d.ts.map +1 -1
  242. package/dist/types/tsconfig.tsbuildinfo +1 -1
  243. package/dist/types/utils/map.d.ts.map +1 -1
  244. package/dist/types/utils/notifyChannel.d.ts.map +1 -1
  245. package/graphql.codegen.yml +1 -1
  246. package/package.json +18 -16
  247. package/src/ActionsExecutionContainerHookFactory.ts +19 -2
  248. package/src/ActionsMetrics.ts +135 -0
  249. package/src/dispatch/EventDispatcher.ts +104 -26
  250. package/src/dispatch/EventsRepository.ts +146 -28
  251. package/src/dispatch/ProjectDispatcher.ts +79 -19
  252. package/src/dispatch/WebhookFetcher.ts +11 -3
  253. package/src/dispatch/WebhookTargetHandler.ts +182 -28
  254. package/src/dispatch/redactRequestError.ts +65 -0
  255. package/src/dispatch/truncateText.ts +13 -0
  256. package/src/graphql/http/ActionsGraphQLHandlerFactory.ts +2 -2
  257. package/src/graphql/http/ActionsWebsocketControllerFactory.ts +73 -30
  258. package/src/graphql/resolvers/ResolversFactory.ts +1 -1
  259. package/src/graphql/resolvers/mutation/SetVariablesMutationResolver.ts +8 -1
  260. package/src/graphql/resolvers/query/EventsQueryResolver.ts +1 -1
  261. package/src/graphql/resolvers/query/VariablesQueryResolver.ts +1 -4
  262. package/src/graphql/schema/actions.graphql.ts +26 -12
  263. package/src/graphql/schema/index.ts +30 -17
  264. package/src/index.ts +37 -12
  265. package/src/model/VariablesManager.ts +72 -6
  266. package/src/triggers/TriggerPayloadPersister.ts +6 -0
  267. package/src/tsconfig.json +1 -0
  268. package/tests/cases/unit/actionsMetrics.test.ts +76 -0
  269. package/tests/cases/unit/actionsWebsocketController.test.ts +270 -0
  270. package/tests/cases/unit/dispatchTracing.test.ts +277 -0
  271. package/tests/cases/unit/eventsRepository.test.ts +158 -0
  272. package/tests/cases/unit/projectDispatcher.test.ts +114 -0
  273. package/tests/cases/unit/redactRequestError.test.ts +66 -0
  274. package/tests/cases/unit/truncateText.test.ts +25 -0
  275. package/tests/cases/unit/variablesManager.test.ts +154 -0
  276. package/tests/cases/unit/webhookEgress.test.ts +80 -0
  277. package/tests/cases/unit/webhookHandler.test.ts +328 -33
  278. package/tests/cases/unit/webhookTracing.test.ts +163 -0
  279. package/tests/src/event.ts +27 -0
  280. package/tests/src/tracer.ts +11 -0
  281. package/tests/src/utils.ts +5 -0
@@ -0,0 +1,158 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { Client, Connection, EventManager } from '@contember/database'
3
+ import { createLogger, TestLoggerHandler } from '@contember/logger'
4
+ import { Actions } from '@contember/schema'
5
+ import { EventsRepository } from '../../../src/dispatch/EventsRepository.js'
6
+ import { HandledEvent } from '../../../src/dispatch/types.js'
7
+ import { createTestEvent } from '../../src/event.js'
8
+ import { testUuid } from '../../src/uuid.js'
9
+
10
+ /**
11
+ * Answers statements from a script, then with an empty result, so what is under test is the
12
+ * repository's own bookkeeping rather than any SQL. Every statement is recorded in `queries`.
13
+ */
14
+ const createStubClient = (responses: Connection.Result[] = [], queries: { sql: string; parameters: readonly any[] }[] = []): Client => {
15
+ const remaining = [...responses]
16
+ const eventManager = new EventManager()
17
+ const query = async <Row extends Record<string, any>>(sql: string, parameters: readonly any[] = []): Promise<Connection.Result<Row>> => {
18
+ queries.push({ sql, parameters })
19
+ const next = remaining.shift() ?? { rowCount: 0, rows: [] }
20
+ return { rowCount: next.rowCount, rows: next.rows as Row[] }
21
+ }
22
+ const transaction: Connection.TransactionLike = {
23
+ eventManager,
24
+ isClosed: false,
25
+ query,
26
+ scope: cb => Promise.resolve(cb(transaction)),
27
+ transaction: cb => Promise.resolve(cb(transaction)),
28
+ on: () => () => {},
29
+ rollback: async () => {},
30
+ commit: async () => {},
31
+ }
32
+ const connection: Connection.ConnectionLike = {
33
+ eventManager,
34
+ query,
35
+ scope: cb => Promise.resolve(cb(transaction)),
36
+ transaction: cb => Promise.resolve(cb(transaction)),
37
+ }
38
+ return new Client(connection, 'system', {})
39
+ }
40
+
41
+ const target: Actions.WebhookTarget = {
42
+ name: 'test_target',
43
+ type: 'webhook',
44
+ url: 'http://localhost',
45
+ maxAttempts: 3,
46
+ }
47
+
48
+ const createFailedEvent = (numRetries: number): HandledEvent => ({
49
+ row: createTestEvent(0, { num_retries: numRetries, state: 'processing' }),
50
+ target,
51
+ result: { ok: false, code: 401, errorMessage: 'Unauthorized' },
52
+ })
53
+
54
+ const errorsOf = (handler: TestLoggerHandler) => handler.messages.filter(it => it.level.name === 'error')
55
+
56
+ describe('persistProcessed', () => {
57
+ test('logs an error when the last attempt fails', async () => {
58
+ const testLoggerHandler = new TestLoggerHandler()
59
+
60
+ const result = await new EventsRepository().persistProcessed(
61
+ createStubClient(),
62
+ [createFailedEvent(2)],
63
+ createLogger(testLoggerHandler),
64
+ )
65
+
66
+ expect(result).toEqual({ succeeded: 0, retried: 0, failed: 1 })
67
+ const errors = errorsOf(testLoggerHandler)
68
+ expect(errors).toHaveLength(1)
69
+ expect(errors[0].message).toBe('Action event failed permanently, no attempts left')
70
+ // exact match: neither the target URL nor its headers may end up in the log
71
+ expect(errors[0].ownAttributes).toStrictEqual({
72
+ eventId: testUuid(1),
73
+ target: 'test_target',
74
+ trigger: 'test',
75
+ attempts: 3,
76
+ code: 401,
77
+ errorMessage: 'Unauthorized',
78
+ })
79
+ })
80
+
81
+ test('stays quiet while attempts remain', async () => {
82
+ const testLoggerHandler = new TestLoggerHandler()
83
+
84
+ const result = await new EventsRepository().persistProcessed(
85
+ createStubClient(),
86
+ [createFailedEvent(0)],
87
+ createLogger(testLoggerHandler),
88
+ )
89
+
90
+ expect(result).toEqual({ succeeded: 0, retried: 1, failed: 0 })
91
+ expect(errorsOf(testLoggerHandler)).toHaveLength(0)
92
+ })
93
+ })
94
+
95
+ describe('fetchBatch', () => {
96
+ const eventRow = createTestEvent(0, { state: 'processing' })
97
+
98
+ test('logs an error when the event names a target the schema does not have', async () => {
99
+ const testLoggerHandler = new TestLoggerHandler()
100
+ const client = createStubClient([
101
+ { rowCount: 1, rows: [eventRow] },
102
+ { rowCount: 1, rows: [] },
103
+ ])
104
+
105
+ const result = await new EventsRepository().fetchBatch(
106
+ { triggers: {}, targets: {} },
107
+ client,
108
+ createLogger(testLoggerHandler),
109
+ )
110
+
111
+ expect(result).toEqual({ ok: false, backoffMs: undefined, unknownTargetFailed: 1 })
112
+ const errors = errorsOf(testLoggerHandler)
113
+ expect(errors).toHaveLength(1)
114
+ expect(errors[0].message).toBe('Action event failed permanently, its target is not in the schema')
115
+ expect(errors[0].ownAttributes).toStrictEqual({
116
+ eventId: testUuid(1),
117
+ target: 'test_target',
118
+ trigger: 'test',
119
+ })
120
+ })
121
+
122
+ test('stays quiet when the target is in the schema', async () => {
123
+ const testLoggerHandler = new TestLoggerHandler()
124
+ const client = createStubClient([
125
+ { rowCount: 1, rows: [eventRow] },
126
+ ])
127
+
128
+ const result = await new EventsRepository().fetchBatch(
129
+ { triggers: {}, targets: { test_target: target } },
130
+ client,
131
+ createLogger(testLoggerHandler),
132
+ )
133
+
134
+ expect(result).toEqual({ ok: true, events: [eventRow], target, unknownTargetFailed: 0 })
135
+ expect(testLoggerHandler.messages).toStrictEqual([])
136
+ })
137
+
138
+ test("fills a batch only with events of the primary event's target", async () => {
139
+ const queries: { sql: string; parameters: readonly any[] }[] = []
140
+ const batchTarget: Actions.WebhookTarget = { ...target, batchSize: 3 }
141
+ const client = createStubClient([
142
+ { rowCount: 1, rows: [eventRow] },
143
+ { rowCount: 0, rows: [] },
144
+ ], queries)
145
+
146
+ const result = await new EventsRepository().fetchBatch(
147
+ { triggers: {}, targets: { test_target: batchTarget } },
148
+ client,
149
+ createLogger(new TestLoggerHandler()),
150
+ )
151
+
152
+ expect(result).toEqual({ ok: true, events: [eventRow], target: batchTarget, unknownTargetFailed: 0 })
153
+ expect(queries).toHaveLength(2)
154
+ // the rest of the batch goes to the same webhook — it must not pick up events of other targets
155
+ expect(queries[1].sql).toContain('"target" = ?')
156
+ expect(queries[1].parameters).toContain('test_target')
157
+ })
158
+ })
@@ -0,0 +1,114 @@
1
+ import { expect, test } from 'bun:test'
2
+ import { Connection, EventManager } from '@contember/database'
3
+ import { ContentSchemaResolver } from '@contember/engine-http'
4
+ import { DatabaseContext, DatabaseContextFactory } from '@contember/engine-system-api'
5
+ import { createLogger, TestLoggerHandler } from '@contember/logger'
6
+ import { emptySchema } from '@contember/schema-utils'
7
+ import { Registry } from 'prom-client'
8
+ import { ActionsMetrics } from '../../../src/ActionsMetrics.js'
9
+ import { EventDispatcher } from '../../../src/dispatch/EventDispatcher.js'
10
+ import { ProjectDispatcher } from '../../../src/dispatch/ProjectDispatcher.js'
11
+ import { createMock } from '../../src/utils.js'
12
+ import { testUuid } from '../../src/uuid.js'
13
+
14
+ type ProcessBatchResult = Awaited<ReturnType<EventDispatcher['processBatch']>>
15
+
16
+ const emptyQueue: ProcessBatchResult = { succeeded: 0, retried: 0, failedAfterAttempt: 0, failedUnknownTarget: 0, backoffMs: undefined }
17
+ const processedBatch: ProcessBatchResult = { succeeded: 2, retried: 0, failedAfterAttempt: 0, failedUnknownTarget: 0, backoffMs: 0 }
18
+
19
+ const createDatabaseContext = (): DatabaseContext => {
20
+ const eventManager = new EventManager()
21
+ // The listener issues LISTEN / UNLISTEN only, the dispatcher itself is stubbed.
22
+ const query = async () => ({ rowCount: 0, rows: [] })
23
+ const transaction: Connection.TransactionLike = {
24
+ eventManager,
25
+ isClosed: false,
26
+ query,
27
+ scope: cb => Promise.resolve(cb(transaction)),
28
+ transaction: cb => Promise.resolve(cb(transaction)),
29
+ on: () => () => {},
30
+ rollback: async () => {},
31
+ commit: async () => {},
32
+ }
33
+ const connection: Connection.ConnectionLike = {
34
+ eventManager,
35
+ query,
36
+ scope: cb => Promise.resolve(cb(transaction)),
37
+ transaction: cb => Promise.resolve(cb(transaction)),
38
+ }
39
+ return new DatabaseContextFactory('system', { uuid: () => testUuid(1) }).create(connection)
40
+ }
41
+
42
+ const contentSchemaResolver = createMock<ContentSchemaResolver>({
43
+ clearCache: () => {},
44
+ getSchema: async () => ({ schema: emptySchema, meta: {} }),
45
+ })
46
+
47
+ const startDispatcher = async (processBatch: () => Promise<ProcessBatchResult>, endTimeoutMs: number) => {
48
+ const loggerHandler = new TestLoggerHandler()
49
+ const dispatcher = new ProjectDispatcher(
50
+ createMock<EventDispatcher>({ processBatch }),
51
+ createDatabaseContext(),
52
+ contentSchemaResolver,
53
+ 'blog',
54
+ new ActionsMetrics(new Registry()).forProject('blog'),
55
+ { endTimeoutMs },
56
+ )
57
+ const running = await dispatcher.run({
58
+ logger: createLogger(loggerHandler),
59
+ onError: e => {
60
+ throw e
61
+ },
62
+ })
63
+ const warnings = () => loggerHandler.messages.filter(it => it.level.name === 'warn').map(it => it.message)
64
+ return { running, warnings }
65
+ }
66
+
67
+ const measure = async (cb: () => Promise<void>): Promise<number> => {
68
+ const startedAt = Date.now()
69
+ await cb()
70
+ return Date.now() - startedAt
71
+ }
72
+
73
+ test('end() returns promptly while the loop waits for a notification', async () => {
74
+ let batchCount = 0
75
+ const { running, warnings } = await startDispatcher(async () => {
76
+ batchCount++
77
+ return emptyQueue
78
+ }, 5_000)
79
+ await new Promise(resolve => setTimeout(resolve, 10))
80
+
81
+ expect(await measure(() => running.end())).toBeLessThan(500)
82
+ expect(batchCount).toBe(1)
83
+ expect(warnings()).toEqual([])
84
+ })
85
+
86
+ test('end() returns promptly while the loop waits for a retry backoff', async () => {
87
+ const { running, warnings } = await startDispatcher(async () => ({ ...emptyQueue, backoffMs: 20_000 }), 5_000)
88
+ await new Promise(resolve => setTimeout(resolve, 10))
89
+
90
+ expect(await measure(() => running.end())).toBeLessThan(500)
91
+ expect(warnings()).toEqual([])
92
+ })
93
+
94
+ test('end() waits for a short in-flight batch to finish', async () => {
95
+ const steps: string[] = []
96
+ const { running, warnings } = await startDispatcher(async () => {
97
+ await new Promise(resolve => setTimeout(resolve, 50))
98
+ steps.push('batch finished')
99
+ return processedBatch
100
+ }, 5_000)
101
+
102
+ await running.end()
103
+ steps.push('end resolved')
104
+
105
+ expect(steps).toEqual(['batch finished', 'end resolved'])
106
+ expect(warnings()).toEqual([])
107
+ })
108
+
109
+ test('end() gives up on a hanging batch after the timeout', async () => {
110
+ const { running, warnings } = await startDispatcher(() => new Promise<ProcessBatchResult>(() => {}), 50)
111
+
112
+ expect(await measure(() => running.end())).toBeLessThan(1_000)
113
+ expect(warnings()).toEqual(['Worker did not finish its batch in time, events still in processing will be delivered again'])
114
+ })
@@ -0,0 +1,66 @@
1
+ import { expect, test } from 'bun:test'
2
+ import { redactRequestError } from '../../../src/dispatch/redactRequestError.js'
3
+
4
+ test('keeps a message without a URL or a secret', () => {
5
+ expect(redactRequestError('getaddrinfo ENOTFOUND example.com', [])).toBe('getaddrinfo ENOTFOUND example.com')
6
+ })
7
+
8
+ test('keeps only the scheme, host and port of a URL', () => {
9
+ expect(redactRequestError('Failed to parse URL from https://user:pw@example.com:8443/a/b?c=d#e', []))
10
+ .toBe('Failed to parse URL from https://[redacted]@example.com:8443/[redacted]')
11
+ expect(redactRequestError('Invalid URL http://example.com/?token=abc.', [])).toBe('Invalid URL http://example.com/[redacted]')
12
+ expect(redactRequestError('Unable to connect to http://example.com/ or http://example.org', []))
13
+ .toBe('Unable to connect to http://example.com/ or http://example.org')
14
+ })
15
+
16
+ test('redacts every URL, a quoted one included', () => {
17
+ expect(redactRequestError('Redirect from "https://a.example/x?t=1" to https://b.example/y', []))
18
+ .toBe('Redirect from "https://a.example/[redacted]" to https://b.example/[redacted]')
19
+ })
20
+
21
+ test('redacts every occurrence of a secret, the longest first', () => {
22
+ expect(redactRequestError('expected abc, got abcdef and abc', ['abc', 'abcdef', ''])).toBe('expected [redacted], got [redacted] and [redacted]')
23
+ expect(redactRequestError('invalid header value "Bearer abc"', ['Bearer abc', 'abc'])).toBe('invalid header value "[redacted]"')
24
+ })
25
+
26
+ test('redacts a password containing @, / or ?', () => {
27
+ expect(redactRequestError('Request cannot be constructed from a URL that includes credentials: https://user:p@ss@example.com/hooks', []))
28
+ .toBe('Request cannot be constructed from a URL that includes credentials: https://[redacted]@example.com/[redacted]')
29
+ // such a password ends the authority early, so only the known value redacts all of it
30
+ expect(redactRequestError('Failed to parse URL from https://user:pa/s?s@example.com/hooks', ['pa/s?s']))
31
+ .toBe('Failed to parse URL from https://[redacted]@example.com/[redacted]')
32
+ })
33
+
34
+ test('redacts a secret quoted without its surrounding whitespace', () => {
35
+ expect(redactRequestError('Headers.append: "Bearer abc\ndef" is an invalid header value.', [' Bearer abc\ndef\n', 'abc\ndef\n']))
36
+ .toBe('Headers.append: "[redacted]" is an invalid header value.')
37
+ })
38
+
39
+ test('redacts the path and query of a secret URL quoted on their own', () => {
40
+ const url = 'https://hooks.example.com/services/T0/B0/static-token?key=abc'
41
+ expect(redactRequestError('Cannot POST /services/T0/B0/static-token', [url])).toBe('Cannot POST [redacted]')
42
+ expect(redactRequestError('{"path":"/services/T0/B0/static-token?key=abc"}', [url])).toBe('{"path":"[redacted]"}')
43
+ expect(redactRequestError('bad query key=abc', [url])).toBe('bad query [redacted]')
44
+ expect(redactRequestError('{"error":"invalid apiKey STATICKEY"}', ['https://hooks.example.com/hook?apiKey=STATICKEY&v=2']))
45
+ .toBe('{"error":"invalid apiKey [redacted]"}')
46
+ // a bare-word query is no key=value pair, so the word stays elsewhere in the message
47
+ expect(redactRequestError('invalid header value', ['https://hooks.example.com/hook?id'])).toBe('invalid header value')
48
+ // a bare slash would redact every slash in the message
49
+ expect(redactRequestError('Cannot POST /', ['https://hooks.example.com/'])).toBe('Cannot POST /')
50
+ })
51
+
52
+ test('redacts a secret quoted with escaped slashes or percent-encoded', () => {
53
+ const url = 'https://hooks.example.com/p/static-token'
54
+ expect(redactRequestError('{"url":"https:\\/\\/hooks.example.com\\/p\\/static-token"}', [url])).toBe('{"url":"[redacted]"}')
55
+ expect(redactRequestError('{"path":"\\/p\\/static-token"}', [url])).toBe('{"path":"[redacted]"}')
56
+ expect(redactRequestError('redirect=https%3A%2F%2Fhooks.example.com%2Fp%2Fstatic-token', [url])).toBe('redirect=[redacted]')
57
+ expect(redactRequestError('{"auth":"Bearer a\\/b"}', ['Bearer a/b'])).toBe('{"auth":"[redacted]"}')
58
+ })
59
+
60
+ test('scans a long message without a URL in linear time', () => {
61
+ const start = performance.now()
62
+ expect(redactRequestError('a-'.repeat(100_000), [])).toHaveLength(200_000)
63
+ expect(redactRequestError('a.'.repeat(100_000), [])).toHaveLength(200_000)
64
+ // the quadratic scan took seconds on a tenth of this
65
+ expect(performance.now() - start).toBeLessThan(1_000)
66
+ })
@@ -0,0 +1,25 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { truncateText } from '../../../src/dispatch/truncateText.js'
3
+
4
+ describe('truncateText', () => {
5
+ test('keeps a text up to the limit unchanged', () => {
6
+ expect(truncateText('', 5)).toBe('')
7
+ expect(truncateText('abcd', 5)).toBe('abcd')
8
+ expect(truncateText('abcde', 5)).toBe('abcde')
9
+ })
10
+
11
+ test('cuts a text one past the limit and marks the original length', () => {
12
+ expect(truncateText('abcdef', 5)).toBe('abcde… [truncated, 6 characters in total]')
13
+ })
14
+
15
+ test('does not split a surrogate pair at the boundary', () => {
16
+ // '😀' is two UTF-16 code units, the limit falls between them
17
+ const truncated = truncateText('abcd😀xyz', 5)
18
+ expect(truncated).toBe('abcd… [truncated, 9 characters in total]')
19
+ expect(() => encodeURIComponent(truncated)).not.toThrow()
20
+ })
21
+
22
+ test('keeps a surrogate pair ending exactly at the limit', () => {
23
+ expect(truncateText('abc😀xyz', 5)).toBe('abc😀… [truncated, 8 characters in total]')
24
+ })
25
+ })
@@ -0,0 +1,154 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { createConnectionMock, ExpectedQuery } from '@contember/database-tester'
3
+ import { DatabaseContext, DatabaseContextFactory } from '@contember/engine-system-api'
4
+ import { VariablesManager } from '../../../src/model/VariablesManager.js'
5
+ import { testUuid } from '../../src/uuid.js'
6
+
7
+ const selectVariables = (rows: { name: string; value: string }[]): ExpectedQuery => ({
8
+ sql: 'select * from "system"."actions_variable"',
9
+ parameters: [],
10
+ response: { rows },
11
+ })
12
+
13
+ const transaction = (...queries: ExpectedQuery[]): ExpectedQuery[] => [
14
+ { sql: 'BEGIN;', response: { rowCount: 1 } },
15
+ { sql: 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ', response: { rowCount: 1 } },
16
+ ...queries,
17
+ { sql: 'COMMIT;', response: { rowCount: 1 } },
18
+ ]
19
+
20
+ const createDb = (queries: ExpectedQuery[]): DatabaseContext =>
21
+ new DatabaseContextFactory('system', { uuid: () => testUuid(1) }).create(createConnectionMock(queries))
22
+
23
+ describe('variables from the environment', () => {
24
+ test('a project-scoped env variable overrides a stored row', async () => {
25
+ const manager = new VariablesManager({ MY_PROJECT_ACTIONS_VARIABLE_API_KEY: 'from-env' })
26
+ const db = createDb([selectVariables([{ name: 'API_KEY', value: 'from-db' }])])
27
+
28
+ expect(await manager.fetchVariables(db, 'my-project')).toEqual({ API_KEY: 'from-env' })
29
+ })
30
+
31
+ test('a project-scoped env variable works without any stored row', async () => {
32
+ const manager = new VariablesManager({ MY_PROJECT_ACTIONS_VARIABLE_API_KEY: 'from-env' })
33
+ const db = createDb([selectVariables([])])
34
+
35
+ expect(await manager.fetchVariables(db, 'my-project')).toEqual({ API_KEY: 'from-env' })
36
+ })
37
+
38
+ test('the shared DEFAULT_ value applies to every project, the project-scoped one wins', async () => {
39
+ const manager = new VariablesManager({
40
+ DEFAULT_ACTIONS_VARIABLE_API_KEY: 'shared',
41
+ DEFAULT_ACTIONS_VARIABLE_BASE_URL: 'https://example.com',
42
+ MY_PROJECT_ACTIONS_VARIABLE_API_KEY: 'mine',
43
+ })
44
+ const db = createDb([selectVariables([])])
45
+
46
+ expect(await manager.fetchVariables(db, 'my-project')).toEqual({
47
+ API_KEY: 'mine',
48
+ BASE_URL: 'https://example.com',
49
+ })
50
+ })
51
+
52
+ test('another project and unrelated env variables are ignored', async () => {
53
+ const manager = new VariablesManager({
54
+ OTHER_ACTIONS_VARIABLE_API_KEY: 'not-mine',
55
+ MY_PROJECT_ACTIONS_VARIABLE_: 'no-name',
56
+ MY_PROJECT_ACTIONS_VARIABLE_BLANK: '',
57
+ CONTEMBER_ROOT_TOKEN: 'unrelated',
58
+ })
59
+ const db = createDb([selectVariables([{ name: 'API_KEY', value: 'from-db' }])])
60
+
61
+ expect(await manager.fetchVariables(db, 'my-project')).toEqual({ API_KEY: 'from-db' })
62
+ })
63
+
64
+ test('a stored variable is unaffected when the environment supplies nothing', async () => {
65
+ const manager = new VariablesManager({})
66
+ const db = createDb([selectVariables([{ name: 'API_KEY', value: 'from-db' }, { name: 'baseUrl', value: 'http://localhost' }])])
67
+
68
+ expect(await manager.fetchVariables(db, 'my-project')).toEqual({ API_KEY: 'from-db', baseUrl: 'http://localhost' })
69
+ })
70
+
71
+ test('listing reports where each value comes from, sorted by name', async () => {
72
+ const manager = new VariablesManager({ MY_PROJECT_ACTIONS_VARIABLE_API_KEY: 'from-env' })
73
+ const db = createDb([selectVariables([{ name: 'API_KEY', value: 'from-db' }, { name: 'baseUrl', value: 'http://localhost' }])])
74
+
75
+ expect(await manager.listVariables(db, 'my-project')).toEqual([
76
+ { name: 'API_KEY', value: null, source: 'ENVIRONMENT' },
77
+ { name: 'baseUrl', value: 'http://localhost', source: 'DATABASE' },
78
+ ])
79
+ })
80
+
81
+ test('listing never returns an environment value, not even the one it shadows', async () => {
82
+ const manager = new VariablesManager({ MY_PROJECT_ACTIONS_VARIABLE_API_KEY: 'from-env' })
83
+ const db = createDb([selectVariables([{ name: 'API_KEY', value: 'from-db' }])])
84
+
85
+ const listed = JSON.stringify(await manager.listVariables(db, 'my-project'))
86
+ expect(listed).not.toContain('from-env')
87
+ expect(listed).not.toContain('from-db')
88
+ })
89
+
90
+ test('a stored variable named after an Object prototype member is still listed and writable', async () => {
91
+ const manager = new VariablesManager({ MY_PROJECT_ACTIONS_VARIABLE_API_KEY: 'from-env' })
92
+ const db = createDb([selectVariables([{ name: 'toString', value: 'from-db' }])])
93
+
94
+ expect(await manager.listVariables(db, 'my-project')).toEqual([
95
+ { name: 'API_KEY', value: null, source: 'ENVIRONMENT' },
96
+ { name: 'toString', value: 'from-db', source: 'DATABASE' },
97
+ ])
98
+ })
99
+ })
100
+
101
+ describe('setVariables', () => {
102
+ test('rejects a name supplied by the environment without touching the database', async () => {
103
+ const manager = new VariablesManager({ MY_PROJECT_ACTIONS_VARIABLE_API_KEY: 'from-env' })
104
+ const db = createDb([])
105
+
106
+ await expect(manager.setVariables(db, { variables: [{ name: 'API_KEY', value: 'attempted' }] }, 'my-project')).rejects.toThrow(
107
+ 'Variables supplied by the environment are read-only: API_KEY',
108
+ )
109
+ })
110
+
111
+ test('does not mistake an Object prototype member for an environment variable', async () => {
112
+ const manager = new VariablesManager({})
113
+ const db = createDb(transaction(
114
+ selectVariables([]),
115
+ {
116
+ sql:
117
+ 'insert into "system"."actions_variable" ("id", "name", "value") values (?, ?, ?) on conflict ("name") do update set "value" = ?, "updated_at" = NOW()',
118
+ parameters: [testUuid(1), 'toString', 'plain', 'plain'],
119
+ response: { rowCount: 1 },
120
+ },
121
+ ))
122
+
123
+ await manager.setVariables(db, { variables: [{ name: 'toString', value: 'plain' }] }, 'my-project')
124
+ })
125
+
126
+ test('writes a variable the environment does not supply', async () => {
127
+ const manager = new VariablesManager({ MY_PROJECT_ACTIONS_VARIABLE_API_KEY: 'from-env' })
128
+ const db = createDb(transaction(
129
+ selectVariables([]),
130
+ {
131
+ sql:
132
+ 'insert into "system"."actions_variable" ("id", "name", "value") values (?, ?, ?) on conflict ("name") do update set "value" = ?, "updated_at" = NOW()',
133
+ parameters: [testUuid(1), 'baseUrl', 'http://localhost', 'http://localhost'],
134
+ response: { rowCount: 1 },
135
+ },
136
+ ))
137
+
138
+ await manager.setVariables(db, { variables: [{ name: 'baseUrl', value: 'http://localhost' }] }, 'my-project')
139
+ })
140
+
141
+ test('SET mode drops the stored rows that are not submitted', async () => {
142
+ const manager = new VariablesManager({})
143
+ const db = createDb(transaction(
144
+ selectVariables([{ name: 'baseUrl', value: 'http://localhost' }, { name: 'stale', value: 'gone' }]),
145
+ {
146
+ sql: 'delete from "system"."actions_variable" where "name" in (?)',
147
+ parameters: ['stale'],
148
+ response: { rowCount: 1 },
149
+ },
150
+ ))
151
+
152
+ await manager.setVariables(db, { variables: [{ name: 'baseUrl', value: 'http://localhost' }], mode: 'SET' }, 'my-project')
153
+ })
154
+ })
@@ -0,0 +1,80 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
2
+ import http from 'node:http'
3
+ import { createEgressGuard } from '@contember/engine-common'
4
+ import { createLogger, TestLoggerHandler } from '@contember/logger'
5
+ import { Actions } from '@contember/schema'
6
+ import { noopTracer } from '@contember/telemetry'
7
+ import { createWebhookFetcher } from '../../../src/dispatch/WebhookFetcher.js'
8
+ import { WebhookTargetHandler } from '../../../src/dispatch/WebhookTargetHandler.js'
9
+ import { createTestEvent } from '../../src/event.js'
10
+
11
+ describe('webhook delivery and the egress guard', () => {
12
+ let server: http.Server
13
+ let port: number
14
+ let received = 0
15
+ // The test preload replaces the global `fetch` with a DOM one; the engine runs with the runtime's own.
16
+ let preloadFetch: typeof fetch
17
+
18
+ beforeAll(async () => {
19
+ preloadFetch = globalThis.fetch
20
+ globalThis.fetch = Bun.fetch
21
+ server = http.createServer((req, res) => {
22
+ received++
23
+ req.resume()
24
+ res.writeHead(200).end()
25
+ })
26
+ // All interfaces: `localhost` may resolve to ::1 first.
27
+ await new Promise<void>(resolve => server.listen(0, resolve))
28
+ const address = server.address()
29
+ if (address === null || typeof address === 'string') {
30
+ throw new Error('expected a TCP address')
31
+ }
32
+ port = address.port
33
+ })
34
+
35
+ afterAll(() => {
36
+ globalThis.fetch = preloadFetch
37
+ server.close()
38
+ })
39
+
40
+ const deliver = async (guard: ReturnType<typeof createEgressGuard>) => {
41
+ const handler = new WebhookTargetHandler(createWebhookFetcher(guard), noopTracer, { propagateToWebhooks: false })
42
+ const target: Actions.AnyTarget = { name: 'local_target', type: 'webhook', url: `http://localhost:${port}/hook` }
43
+ const [handled] = await handler.handle({
44
+ logger: createLogger(new TestLoggerHandler()),
45
+ target,
46
+ events: [createTestEvent(0)],
47
+ variables: {},
48
+ })
49
+ return handled.result
50
+ }
51
+
52
+ test('without the guard (the default), a local http webhook is delivered', async () => {
53
+ const before = received
54
+ const result = await deliver(createEgressGuard(undefined))
55
+ expect(result.ok).toBe(true)
56
+ expect(result.code).toBe(200)
57
+ expect(received).toBe(before + 1)
58
+ })
59
+
60
+ test('with the guard, a webhook to a non-public address fails as a delivery error', async () => {
61
+ const before = received
62
+ const result = await deliver(createEgressGuard({ guard: true, allowHttp: true }))
63
+ expect(result.ok).toBe(false)
64
+ expect(result.errorMessage).toContain('resolves to the non-public address')
65
+ expect(received).toBe(before)
66
+ })
67
+
68
+ test('with the guard, an http webhook is refused unless http is allowed', async () => {
69
+ const result = await deliver(createEgressGuard({ guard: true, allowlist: ['localhost'] }))
70
+ expect(result.ok).toBe(false)
71
+ expect(result.errorMessage).toContain('Only https:// URLs are allowed')
72
+ })
73
+
74
+ test('with the guard, an allow-listed internal host is delivered', async () => {
75
+ const before = received
76
+ const result = await deliver(createEgressGuard({ guard: true, allowHttp: true, allowlist: ['localhost'] }))
77
+ expect(result.ok).toBe(true)
78
+ expect(received).toBe(before + 1)
79
+ })
80
+ })