@budibase/backend-core 2.9.19 → 2.9.21-alpha.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 (250) hide show
  1. package/dist/index.js +266 -324
  2. package/dist/index.js.map +4 -4
  3. package/dist/index.js.meta.json +1 -1
  4. package/dist/package.json +19 -4
  5. package/dist/plugins.js +1 -1
  6. package/dist/plugins.js.map +1 -1
  7. package/dist/plugins.js.meta.json +1 -1
  8. package/dist/src/security/permissions.d.ts +1 -1
  9. package/dist/tests.js +222 -260
  10. package/dist/tests.js.map +4 -4
  11. package/dist/tests.js.meta.json +1 -1
  12. package/package.json +19 -4
  13. package/dist/tsconfig.build.tsbuildinfo +0 -1
  14. package/src/accounts/accounts.ts +0 -82
  15. package/src/accounts/api.ts +0 -59
  16. package/src/accounts/index.ts +0 -1
  17. package/src/auth/auth.ts +0 -208
  18. package/src/auth/index.ts +0 -1
  19. package/src/auth/tests/auth.spec.ts +0 -14
  20. package/src/blacklist/blacklist.ts +0 -54
  21. package/src/blacklist/index.ts +0 -1
  22. package/src/blacklist/tests/blacklist.spec.ts +0 -46
  23. package/src/cache/appMetadata.ts +0 -88
  24. package/src/cache/base/index.ts +0 -92
  25. package/src/cache/generic.ts +0 -30
  26. package/src/cache/index.ts +0 -5
  27. package/src/cache/tests/writethrough.spec.ts +0 -138
  28. package/src/cache/user.ts +0 -69
  29. package/src/cache/writethrough.ts +0 -133
  30. package/src/configs/configs.ts +0 -257
  31. package/src/configs/index.ts +0 -1
  32. package/src/configs/tests/configs.spec.ts +0 -184
  33. package/src/constants/db.ts +0 -63
  34. package/src/constants/index.ts +0 -2
  35. package/src/constants/misc.ts +0 -50
  36. package/src/context/Context.ts +0 -14
  37. package/src/context/identity.ts +0 -58
  38. package/src/context/index.ts +0 -3
  39. package/src/context/mainContext.ts +0 -310
  40. package/src/context/tests/index.spec.ts +0 -147
  41. package/src/context/types.ts +0 -11
  42. package/src/db/Replication.ts +0 -84
  43. package/src/db/constants.ts +0 -10
  44. package/src/db/couch/DatabaseImpl.ts +0 -238
  45. package/src/db/couch/connections.ts +0 -77
  46. package/src/db/couch/index.ts +0 -5
  47. package/src/db/couch/pouchDB.ts +0 -97
  48. package/src/db/couch/pouchDump.ts +0 -0
  49. package/src/db/couch/utils.ts +0 -50
  50. package/src/db/db.ts +0 -39
  51. package/src/db/errors.ts +0 -14
  52. package/src/db/index.ts +0 -12
  53. package/src/db/lucene.ts +0 -732
  54. package/src/db/searchIndexes/index.ts +0 -1
  55. package/src/db/searchIndexes/searchIndexes.ts +0 -62
  56. package/src/db/tests/index.spec.js +0 -25
  57. package/src/db/tests/lucene.spec.ts +0 -298
  58. package/src/db/tests/pouch.spec.js +0 -62
  59. package/src/db/tests/utils.spec.ts +0 -63
  60. package/src/db/utils.ts +0 -207
  61. package/src/db/views.ts +0 -241
  62. package/src/docIds/conversions.ts +0 -59
  63. package/src/docIds/ids.ts +0 -113
  64. package/src/docIds/index.ts +0 -2
  65. package/src/docIds/newid.ts +0 -5
  66. package/src/docIds/params.ts +0 -174
  67. package/src/docUpdates/index.ts +0 -29
  68. package/src/environment.ts +0 -201
  69. package/src/errors/errors.ts +0 -119
  70. package/src/errors/index.ts +0 -1
  71. package/src/events/analytics.ts +0 -6
  72. package/src/events/asyncEvents/index.ts +0 -2
  73. package/src/events/asyncEvents/publisher.ts +0 -12
  74. package/src/events/asyncEvents/queue.ts +0 -22
  75. package/src/events/backfill.ts +0 -183
  76. package/src/events/documentId.ts +0 -56
  77. package/src/events/events.ts +0 -40
  78. package/src/events/identification.ts +0 -310
  79. package/src/events/index.ts +0 -14
  80. package/src/events/processors/AnalyticsProcessor.ts +0 -64
  81. package/src/events/processors/AuditLogsProcessor.ts +0 -93
  82. package/src/events/processors/LoggingProcessor.ts +0 -37
  83. package/src/events/processors/Processors.ts +0 -52
  84. package/src/events/processors/async/DocumentUpdateProcessor.ts +0 -43
  85. package/src/events/processors/index.ts +0 -19
  86. package/src/events/processors/posthog/PosthogProcessor.ts +0 -118
  87. package/src/events/processors/posthog/index.ts +0 -2
  88. package/src/events/processors/posthog/rateLimiting.ts +0 -106
  89. package/src/events/processors/posthog/tests/PosthogProcessor.spec.ts +0 -168
  90. package/src/events/processors/types.ts +0 -1
  91. package/src/events/publishers/account.ts +0 -35
  92. package/src/events/publishers/app.ts +0 -155
  93. package/src/events/publishers/auditLog.ts +0 -26
  94. package/src/events/publishers/auth.ts +0 -73
  95. package/src/events/publishers/automation.ts +0 -110
  96. package/src/events/publishers/backfill.ts +0 -74
  97. package/src/events/publishers/backup.ts +0 -42
  98. package/src/events/publishers/datasource.ts +0 -48
  99. package/src/events/publishers/email.ts +0 -17
  100. package/src/events/publishers/environmentVariable.ts +0 -38
  101. package/src/events/publishers/group.ts +0 -99
  102. package/src/events/publishers/index.ts +0 -24
  103. package/src/events/publishers/installation.ts +0 -38
  104. package/src/events/publishers/layout.ts +0 -26
  105. package/src/events/publishers/license.ts +0 -84
  106. package/src/events/publishers/org.ts +0 -37
  107. package/src/events/publishers/plugin.ts +0 -47
  108. package/src/events/publishers/query.ts +0 -88
  109. package/src/events/publishers/role.ts +0 -62
  110. package/src/events/publishers/rows.ts +0 -29
  111. package/src/events/publishers/screen.ts +0 -36
  112. package/src/events/publishers/serve.ts +0 -43
  113. package/src/events/publishers/table.ts +0 -70
  114. package/src/events/publishers/user.ts +0 -202
  115. package/src/events/publishers/view.ts +0 -107
  116. package/src/featureFlags/index.ts +0 -77
  117. package/src/featureFlags/tests/featureFlags.spec.ts +0 -85
  118. package/src/helpers.ts +0 -9
  119. package/src/index.ts +0 -53
  120. package/src/installation.ts +0 -107
  121. package/src/logging/alerts.ts +0 -26
  122. package/src/logging/correlation/correlation.ts +0 -13
  123. package/src/logging/correlation/index.ts +0 -1
  124. package/src/logging/correlation/middleware.ts +0 -17
  125. package/src/logging/index.ts +0 -4
  126. package/src/logging/pino/logger.ts +0 -232
  127. package/src/logging/pino/middleware.ts +0 -45
  128. package/src/logging/system.ts +0 -81
  129. package/src/logging/tests/system.spec.ts +0 -61
  130. package/src/middleware/adminOnly.ts +0 -9
  131. package/src/middleware/auditLog.ts +0 -6
  132. package/src/middleware/authenticated.ts +0 -193
  133. package/src/middleware/builderOnly.ts +0 -20
  134. package/src/middleware/builderOrAdmin.ts +0 -20
  135. package/src/middleware/csrf.ts +0 -81
  136. package/src/middleware/errorHandling.ts +0 -29
  137. package/src/middleware/index.ts +0 -21
  138. package/src/middleware/internalApi.ts +0 -23
  139. package/src/middleware/joi-validator.ts +0 -45
  140. package/src/middleware/matchers.ts +0 -47
  141. package/src/middleware/passport/datasource/google.ts +0 -95
  142. package/src/middleware/passport/local.ts +0 -54
  143. package/src/middleware/passport/sso/google.ts +0 -77
  144. package/src/middleware/passport/sso/oidc.ts +0 -154
  145. package/src/middleware/passport/sso/sso.ts +0 -165
  146. package/src/middleware/passport/sso/tests/google.spec.ts +0 -67
  147. package/src/middleware/passport/sso/tests/oidc.spec.ts +0 -152
  148. package/src/middleware/passport/sso/tests/sso.spec.ts +0 -197
  149. package/src/middleware/passport/utils.ts +0 -38
  150. package/src/middleware/querystringToBody.ts +0 -28
  151. package/src/middleware/tenancy.ts +0 -36
  152. package/src/middleware/tests/builder.spec.ts +0 -180
  153. package/src/middleware/tests/matchers.spec.ts +0 -134
  154. package/src/migrations/definitions.ts +0 -40
  155. package/src/migrations/index.ts +0 -2
  156. package/src/migrations/migrations.ts +0 -191
  157. package/src/migrations/tests/__snapshots__/migrations.spec.ts.snap +0 -11
  158. package/src/migrations/tests/migrations.spec.ts +0 -64
  159. package/src/objectStore/buckets/app.ts +0 -40
  160. package/src/objectStore/buckets/global.ts +0 -29
  161. package/src/objectStore/buckets/index.ts +0 -3
  162. package/src/objectStore/buckets/plugins.ts +0 -71
  163. package/src/objectStore/buckets/tests/app.spec.ts +0 -171
  164. package/src/objectStore/buckets/tests/global.spec.ts +0 -74
  165. package/src/objectStore/buckets/tests/plugins.spec.ts +0 -111
  166. package/src/objectStore/cloudfront.ts +0 -41
  167. package/src/objectStore/index.ts +0 -3
  168. package/src/objectStore/objectStore.ts +0 -440
  169. package/src/objectStore/utils.ts +0 -27
  170. package/src/platform/index.ts +0 -3
  171. package/src/platform/platformDb.ts +0 -6
  172. package/src/platform/tenants.ts +0 -101
  173. package/src/platform/tests/tenants.spec.ts +0 -26
  174. package/src/platform/users.ts +0 -90
  175. package/src/plugin/index.ts +0 -1
  176. package/src/plugin/tests/validation.spec.ts +0 -83
  177. package/src/plugin/utils.ts +0 -156
  178. package/src/queue/constants.ts +0 -6
  179. package/src/queue/inMemoryQueue.ts +0 -141
  180. package/src/queue/index.ts +0 -2
  181. package/src/queue/listeners.ts +0 -195
  182. package/src/queue/queue.ts +0 -54
  183. package/src/redis/index.ts +0 -6
  184. package/src/redis/init.ts +0 -86
  185. package/src/redis/redis.ts +0 -308
  186. package/src/redis/redlockImpl.ts +0 -139
  187. package/src/redis/utils.ts +0 -117
  188. package/src/security/encryption.ts +0 -179
  189. package/src/security/permissions.ts +0 -159
  190. package/src/security/roles.ts +0 -420
  191. package/src/security/sessions.ts +0 -120
  192. package/src/security/tests/encryption.spec.ts +0 -31
  193. package/src/security/tests/permissions.spec.ts +0 -145
  194. package/src/security/tests/sessions.spec.ts +0 -12
  195. package/src/tenancy/db.ts +0 -6
  196. package/src/tenancy/index.ts +0 -2
  197. package/src/tenancy/tenancy.ts +0 -140
  198. package/src/tenancy/tests/tenancy.spec.ts +0 -184
  199. package/src/timers/index.ts +0 -1
  200. package/src/timers/timers.ts +0 -22
  201. package/src/users/db.ts +0 -460
  202. package/src/users/events.ts +0 -176
  203. package/src/users/index.ts +0 -4
  204. package/src/users/lookup.ts +0 -102
  205. package/src/users/users.ts +0 -276
  206. package/src/users/utils.ts +0 -55
  207. package/src/utils/hashing.ts +0 -14
  208. package/src/utils/index.ts +0 -3
  209. package/src/utils/stringUtils.ts +0 -8
  210. package/src/utils/tests/utils.spec.ts +0 -191
  211. package/src/utils/utils.ts +0 -239
  212. package/tests/core/logging.ts +0 -34
  213. package/tests/core/utilities/index.ts +0 -6
  214. package/tests/core/utilities/jestUtils.ts +0 -30
  215. package/tests/core/utilities/mocks/alerts.ts +0 -3
  216. package/tests/core/utilities/mocks/date.ts +0 -2
  217. package/tests/core/utilities/mocks/events.ts +0 -131
  218. package/tests/core/utilities/mocks/fetch.ts +0 -17
  219. package/tests/core/utilities/mocks/index.ts +0 -10
  220. package/tests/core/utilities/mocks/licenses.ts +0 -107
  221. package/tests/core/utilities/mocks/posthog.ts +0 -7
  222. package/tests/core/utilities/structures/Chance.ts +0 -20
  223. package/tests/core/utilities/structures/accounts.ts +0 -115
  224. package/tests/core/utilities/structures/apps.ts +0 -21
  225. package/tests/core/utilities/structures/common.ts +0 -7
  226. package/tests/core/utilities/structures/db.ts +0 -12
  227. package/tests/core/utilities/structures/documents/index.ts +0 -1
  228. package/tests/core/utilities/structures/documents/platform/index.ts +0 -1
  229. package/tests/core/utilities/structures/documents/platform/installation.ts +0 -12
  230. package/tests/core/utilities/structures/generator.ts +0 -2
  231. package/tests/core/utilities/structures/index.ts +0 -15
  232. package/tests/core/utilities/structures/koa.ts +0 -16
  233. package/tests/core/utilities/structures/licenses.ts +0 -167
  234. package/tests/core/utilities/structures/plugins.ts +0 -19
  235. package/tests/core/utilities/structures/quotas.ts +0 -67
  236. package/tests/core/utilities/structures/scim.ts +0 -80
  237. package/tests/core/utilities/structures/shared.ts +0 -19
  238. package/tests/core/utilities/structures/sso.ts +0 -119
  239. package/tests/core/utilities/structures/tenants.ts +0 -5
  240. package/tests/core/utilities/structures/userGroups.ts +0 -10
  241. package/tests/core/utilities/structures/users.ts +0 -73
  242. package/tests/core/utilities/testContainerUtils.ts +0 -98
  243. package/tests/core/utilities/utils/index.ts +0 -1
  244. package/tests/core/utilities/utils/time.ts +0 -3
  245. package/tests/extra/DBTestConfiguration.ts +0 -36
  246. package/tests/extra/index.ts +0 -2
  247. package/tests/extra/testEnv.ts +0 -95
  248. package/tests/index.ts +0 -1
  249. package/tests/jestEnv.ts +0 -6
  250. package/tests/jestSetup.ts +0 -28
@@ -1,83 +0,0 @@
1
- import { validate } from "../utils"
2
- import fetch from "node-fetch"
3
- import { PluginType } from "@budibase/types"
4
-
5
- const repoUrl =
6
- "https://raw.githubusercontent.com/Budibase/budibase-skeleton/master"
7
- const automationLink = `${repoUrl}/automation/schema.json.hbs`
8
- const componentLink = `${repoUrl}/component/schema.json.hbs`
9
- const datasourceLink = `${repoUrl}/datasource/schema.json.hbs`
10
-
11
- async function getSchema(link: string) {
12
- const response = await fetch(link)
13
- if (response.status > 300) {
14
- return
15
- }
16
- const text = await response.text()
17
- return JSON.parse(text)
18
- }
19
-
20
- async function runTest(opts: { link?: string; schema?: any }) {
21
- let error
22
- try {
23
- let schema = opts.schema
24
- if (opts.link) {
25
- schema = await getSchema(opts.link)
26
- }
27
- validate(schema)
28
- } catch (err) {
29
- error = err
30
- }
31
- return error
32
- }
33
-
34
- describe("it should be able to validate an automation schema", () => {
35
- it("should return automation skeleton schema is valid", async () => {
36
- const error = await runTest({ link: automationLink })
37
- expect(error).toBeUndefined()
38
- })
39
-
40
- it("should fail given invalid automation schema", async () => {
41
- const error = await runTest({
42
- schema: {
43
- type: PluginType.AUTOMATION,
44
- schema: {},
45
- },
46
- })
47
- expect(error).toBeDefined()
48
- })
49
- })
50
-
51
- describe("it should be able to validate a component schema", () => {
52
- it("should return component skeleton schema is valid", async () => {
53
- const error = await runTest({ link: componentLink })
54
- expect(error).toBeUndefined()
55
- })
56
-
57
- it("should fail given invalid component schema", async () => {
58
- const error = await runTest({
59
- schema: {
60
- type: PluginType.COMPONENT,
61
- schema: {},
62
- },
63
- })
64
- expect(error).toBeDefined()
65
- })
66
- })
67
-
68
- describe("it should be able to validate a datasource schema", () => {
69
- it("should return datasource skeleton schema is valid", async () => {
70
- const error = await runTest({ link: datasourceLink })
71
- expect(error).toBeUndefined()
72
- })
73
-
74
- it("should fail given invalid datasource schema", async () => {
75
- const error = await runTest({
76
- schema: {
77
- type: PluginType.DATASOURCE,
78
- schema: {},
79
- },
80
- })
81
- expect(error).toBeDefined()
82
- })
83
- })
@@ -1,156 +0,0 @@
1
- import {
2
- DatasourceFieldType,
3
- QueryType,
4
- PluginType,
5
- AutomationStepType,
6
- AutomationStepIdArray,
7
- AutomationIOType,
8
- AutomationCustomIOType,
9
- } from "@budibase/types"
10
- import joi from "joi"
11
-
12
- const DATASOURCE_TYPES = [
13
- "Relational",
14
- "Non-relational",
15
- "Spreadsheet",
16
- "Object store",
17
- "Graph",
18
- "API",
19
- ]
20
-
21
- function runJoi(validator: joi.Schema, schema: any) {
22
- const { error } = validator.validate(schema)
23
- if (error) {
24
- throw error
25
- }
26
- }
27
-
28
- function validateComponent(schema: any) {
29
- const validator = joi.object({
30
- type: joi.string().allow(PluginType.COMPONENT).required(),
31
- metadata: joi.object().unknown(true).required(),
32
- hash: joi.string().optional(),
33
- version: joi.string().optional(),
34
- schema: joi
35
- .object({
36
- name: joi.string().required(),
37
- settings: joi.array().items(joi.object().unknown(true)).required(),
38
- })
39
- .unknown(true),
40
- })
41
- runJoi(validator, schema)
42
- }
43
-
44
- function validateDatasource(schema: any) {
45
- const fieldValidator = joi.object({
46
- type: joi
47
- .string()
48
- .allow(...Object.values(DatasourceFieldType))
49
- .required(),
50
- required: joi.boolean().required(),
51
- default: joi.any(),
52
- display: joi.string(),
53
- })
54
-
55
- const queryValidator = joi
56
- .object({
57
- type: joi.string().allow(...Object.values(QueryType)),
58
- readable: joi.boolean(),
59
- fields: joi.object().pattern(joi.string(), fieldValidator),
60
- })
61
- .required()
62
-
63
- const validator = joi.object({
64
- type: joi.string().allow(PluginType.DATASOURCE).required(),
65
- metadata: joi.object().unknown(true).required(),
66
- hash: joi.string().optional(),
67
- version: joi.string().optional(),
68
- schema: joi.object({
69
- docs: joi.string(),
70
- friendlyName: joi.string().required(),
71
- type: joi.string().allow(...DATASOURCE_TYPES),
72
- description: joi.string().required(),
73
- datasource: joi.object().pattern(joi.string(), fieldValidator).required(),
74
- query: joi
75
- .object()
76
- .pattern(joi.string(), queryValidator)
77
- .unknown(true)
78
- .required(),
79
- extra: joi.object().pattern(
80
- joi.string(),
81
- joi.object({
82
- type: joi.string().required(),
83
- displayName: joi.string().required(),
84
- required: joi.boolean(),
85
- data: joi.object(),
86
- })
87
- ),
88
- }),
89
- })
90
- runJoi(validator, schema)
91
- }
92
-
93
- function validateAutomation(schema: any) {
94
- const basePropsValidator = joi.object().pattern(joi.string(), {
95
- type: joi
96
- .string()
97
- .allow(...Object.values(AutomationIOType))
98
- .required(),
99
- customType: joi.string().allow(...Object.values(AutomationCustomIOType)),
100
- title: joi.string(),
101
- description: joi.string(),
102
- enum: joi.array().items(joi.string()),
103
- pretty: joi.array().items(joi.string()),
104
- })
105
- const stepSchemaValidator = joi
106
- .object({
107
- properties: basePropsValidator,
108
- required: joi.array().items(joi.string()),
109
- })
110
- .concat(basePropsValidator)
111
- .required()
112
- const validator = joi.object({
113
- type: joi.string().allow(PluginType.AUTOMATION).required(),
114
- metadata: joi.object().unknown(true).required(),
115
- hash: joi.string().optional(),
116
- version: joi.string().optional(),
117
- schema: joi.object({
118
- name: joi.string().required(),
119
- tagline: joi.string().required(),
120
- icon: joi.string().required(),
121
- description: joi.string().required(),
122
- type: joi
123
- .string()
124
- .allow(AutomationStepType.ACTION, AutomationStepType.LOGIC)
125
- .required(),
126
- stepId: joi
127
- .string()
128
- .disallow(...AutomationStepIdArray)
129
- .required(),
130
- inputs: joi.object().optional(),
131
- schema: joi
132
- .object({
133
- inputs: stepSchemaValidator,
134
- outputs: stepSchemaValidator,
135
- })
136
- .required(),
137
- }),
138
- })
139
- runJoi(validator, schema)
140
- }
141
-
142
- export function validate(schema: any) {
143
- switch (schema?.type) {
144
- case PluginType.COMPONENT:
145
- validateComponent(schema)
146
- break
147
- case PluginType.DATASOURCE:
148
- validateDatasource(schema)
149
- break
150
- case PluginType.AUTOMATION:
151
- validateAutomation(schema)
152
- break
153
- default:
154
- throw new Error(`Unknown plugin type - check schema.json: ${schema.type}`)
155
- }
156
- }
@@ -1,6 +0,0 @@
1
- export enum JobQueue {
2
- AUTOMATION = "automationQueue",
3
- APP_BACKUP = "appBackupQueue",
4
- AUDIT_LOG = "auditLogQueue",
5
- SYSTEM_EVENT_QUEUE = "systemEventQueue",
6
- }
@@ -1,141 +0,0 @@
1
- import events from "events"
2
- import { timeout } from "../utils"
3
-
4
- /**
5
- * Bull works with a Job wrapper around all messages that contains a lot more information about
6
- * the state of the message, this object constructor implements the same schema of Bull jobs
7
- * for the sake of maintaining API consistency.
8
- * @param {string} queue The name of the queue which the message will be carried on.
9
- * @param {object} message The JSON message which will be passed back to the consumer.
10
- * @returns {Object} A new job which can now be put onto the queue, this is mostly an
11
- * internal structure so that an in memory queue can be easily swapped for a Bull queue.
12
- */
13
- function newJob(queue: string, message: any) {
14
- return {
15
- timestamp: Date.now(),
16
- queue: queue,
17
- data: message,
18
- }
19
- }
20
-
21
- /**
22
- * This is designed to replicate Bull (https://github.com/OptimalBits/bull) in memory as a sort of mock.
23
- * It is relatively simple, using an event emitter internally to register when messages are available
24
- * to the consumers - in can support many inputs and many consumers.
25
- */
26
- class InMemoryQueue {
27
- _name: string
28
- _opts?: any
29
- _messages: any[]
30
- _emitter: EventEmitter
31
- _runCount: number
32
- _addCount: number
33
- /**
34
- * The constructor the queue, exactly the same as that of Bulls.
35
- * @param {string} name The name of the queue which is being configured.
36
- * @param {object|null} opts This is not used by the in memory queue as there is no real use
37
- * case when in memory, but is the same API as Bull
38
- */
39
- constructor(name: string, opts = null) {
40
- this._name = name
41
- this._opts = opts
42
- this._messages = []
43
- this._emitter = new events.EventEmitter()
44
- this._runCount = 0
45
- this._addCount = 0
46
- }
47
-
48
- /**
49
- * Same callback API as Bull, each callback passed to this will consume messages as they are
50
- * available. Please note this is a queue service, not a notification service, so each
51
- * consumer will receive different messages.
52
- * @param {function<object>} func The callback function which will return a "Job", the same
53
- * as the Bull API, within this job the property "data" contains the JSON message. Please
54
- * note this is incredibly limited compared to Bull as in reality the Job would contain
55
- * a lot more information about the queue and current status of Bull cluster.
56
- */
57
- process(func: any) {
58
- this._emitter.on("message", async () => {
59
- if (this._messages.length <= 0) {
60
- return
61
- }
62
- let msg = this._messages.shift()
63
- let resp = func(msg)
64
- if (resp.then != null) {
65
- await resp
66
- }
67
- this._runCount++
68
- })
69
- }
70
-
71
- // simply puts a message to the queue and emits to the queue for processing
72
- /**
73
- * Simple function to replicate the add message functionality of Bull, putting
74
- * a new message on the queue. This then emits an event which will be used to
75
- * return the message to a consumer (if one is attached).
76
- * @param {object} msg A message to be transported over the queue, this should be
77
- * a JSON message as this is required by Bull.
78
- * @param {boolean} repeat serves no purpose for the import queue.
79
- */
80
- // eslint-disable-next-line no-unused-vars
81
- add(msg: any, repeat: boolean) {
82
- if (typeof msg !== "object") {
83
- throw "Queue only supports carrying JSON."
84
- }
85
- this._messages.push(newJob(this._name, msg))
86
- this._addCount++
87
- this._emitter.emit("message")
88
- }
89
-
90
- /**
91
- * replicating the close function from bull, which waits for jobs to finish.
92
- */
93
- async close() {
94
- return []
95
- }
96
-
97
- /**
98
- * This removes a cron which has been implemented, this is part of Bull API.
99
- * @param {string} cronJobId The cron which is to be removed.
100
- */
101
- removeRepeatableByKey(cronJobId: string) {
102
- // TODO: implement for testing
103
- console.log(cronJobId)
104
- }
105
-
106
- /**
107
- * Implemented for tests
108
- */
109
- getRepeatableJobs() {
110
- return []
111
- }
112
-
113
- // eslint-disable-next-line no-unused-vars
114
- removeJobs(pattern: string) {
115
- // no-op
116
- }
117
-
118
- /**
119
- * Implemented for tests
120
- */
121
- async clean() {
122
- return []
123
- }
124
-
125
- async getJob() {
126
- return {}
127
- }
128
-
129
- on() {
130
- // do nothing
131
- return this
132
- }
133
-
134
- async waitForCompletion() {
135
- do {
136
- await timeout(50)
137
- } while (this._addCount < this._runCount)
138
- }
139
- }
140
-
141
- export default InMemoryQueue
@@ -1,2 +0,0 @@
1
- export * from "./queue"
2
- export * from "./constants"
@@ -1,195 +0,0 @@
1
- import { Job, JobId, Queue } from "bull"
2
- import { JobQueue } from "./constants"
3
- import * as context from "../context"
4
-
5
- export type StalledFn = (job: Job) => Promise<void>
6
-
7
- export function addListeners(
8
- queue: Queue,
9
- jobQueue: JobQueue,
10
- removeStalledCb?: StalledFn
11
- ) {
12
- logging(queue, jobQueue)
13
- if (removeStalledCb) {
14
- handleStalled(queue, removeStalledCb)
15
- }
16
- }
17
-
18
- function handleStalled(queue: Queue, removeStalledCb?: StalledFn) {
19
- queue.on("stalled", async (job: Job) => {
20
- if (removeStalledCb) {
21
- await removeStalledCb(job)
22
- } else if (job.opts.repeat) {
23
- const jobId = job.id
24
- const repeatJobs = await queue.getRepeatableJobs()
25
- for (let repeatJob of repeatJobs) {
26
- if (repeatJob.id === jobId) {
27
- await queue.removeRepeatableByKey(repeatJob.key)
28
- }
29
- }
30
- console.log(`jobId=${jobId} disabled`)
31
- }
32
- })
33
- }
34
-
35
- function getLogParams(
36
- eventType: QueueEventType,
37
- event: BullEvent,
38
- opts: {
39
- job?: Job
40
- jobId?: JobId
41
- error?: Error
42
- } = {},
43
- extra: any = {}
44
- ) {
45
- const message = `[BULL] ${eventType}=${event}`
46
- const err = opts.error
47
-
48
- const bullLog = {
49
- _logKey: "bull",
50
- eventType,
51
- event,
52
- job: opts.job,
53
- jobId: opts.jobId || opts.job?.id,
54
- ...extra,
55
- }
56
-
57
- let automationLog
58
- if (opts.job?.data?.automation) {
59
- automationLog = {
60
- _logKey: "automation",
61
- trigger: opts.job
62
- ? opts.job.data.automation.definition.trigger.event
63
- : undefined,
64
- }
65
- }
66
-
67
- return [message, err, bullLog, automationLog]
68
- }
69
-
70
- enum BullEvent {
71
- ERROR = "error",
72
- WAITING = "waiting",
73
- ACTIVE = "active",
74
- STALLED = "stalled",
75
- PROGRESS = "progress",
76
- COMPLETED = "completed",
77
- FAILED = "failed",
78
- PAUSED = "paused",
79
- RESUMED = "resumed",
80
- CLEANED = "cleaned",
81
- DRAINED = "drained",
82
- REMOVED = "removed",
83
- }
84
-
85
- enum QueueEventType {
86
- AUTOMATION_EVENT = "automation-event",
87
- APP_BACKUP_EVENT = "app-backup-event",
88
- AUDIT_LOG_EVENT = "audit-log-event",
89
- SYSTEM_EVENT = "system-event",
90
- }
91
-
92
- const EventTypeMap: { [key in JobQueue]: QueueEventType } = {
93
- [JobQueue.AUTOMATION]: QueueEventType.AUTOMATION_EVENT,
94
- [JobQueue.APP_BACKUP]: QueueEventType.APP_BACKUP_EVENT,
95
- [JobQueue.AUDIT_LOG]: QueueEventType.AUDIT_LOG_EVENT,
96
- [JobQueue.SYSTEM_EVENT_QUEUE]: QueueEventType.SYSTEM_EVENT,
97
- }
98
-
99
- function logging(queue: Queue, jobQueue: JobQueue) {
100
- const eventType = EventTypeMap[jobQueue]
101
-
102
- function doInJobContext(job: Job, task: any) {
103
- // if this is an automation job try to get the app id
104
- const appId = job.data.event?.appId
105
- if (appId) {
106
- return context.doInContext(appId, task)
107
- } else {
108
- task()
109
- }
110
- }
111
-
112
- queue
113
- .on(BullEvent.STALLED, async (job: Job) => {
114
- // A job has been marked as stalled. This is useful for debugging job
115
- // workers that crash or pause the event loop.
116
- await doInJobContext(job, () => {
117
- console.error(...getLogParams(eventType, BullEvent.STALLED, { job }))
118
- })
119
- })
120
- .on(BullEvent.ERROR, (error: any) => {
121
- // An error occurred.
122
- console.error(...getLogParams(eventType, BullEvent.ERROR, { error }))
123
- })
124
-
125
- if (process.env.NODE_DEBUG?.includes("bull")) {
126
- queue
127
- .on(BullEvent.WAITING, (jobId: JobId) => {
128
- // A Job is waiting to be processed as soon as a worker is idling.
129
- console.info(...getLogParams(eventType, BullEvent.WAITING, { jobId }))
130
- })
131
- .on(BullEvent.ACTIVE, async (job: Job, jobPromise: any) => {
132
- // A job has started. You can use `jobPromise.cancel()`` to abort it.
133
- await doInJobContext(job, () => {
134
- console.info(...getLogParams(eventType, BullEvent.ACTIVE, { job }))
135
- })
136
- })
137
- .on(BullEvent.PROGRESS, async (job: Job, progress: any) => {
138
- // A job's progress was updated
139
- await doInJobContext(job, () => {
140
- console.info(
141
- ...getLogParams(
142
- eventType,
143
- BullEvent.PROGRESS,
144
- { job },
145
- { progress }
146
- )
147
- )
148
- })
149
- })
150
- .on(BullEvent.COMPLETED, async (job: Job, result) => {
151
- // A job successfully completed with a `result`.
152
- await doInJobContext(job, () => {
153
- console.info(
154
- ...getLogParams(eventType, BullEvent.COMPLETED, { job }, { result })
155
- )
156
- })
157
- })
158
- .on(BullEvent.FAILED, async (job: Job, error: any) => {
159
- // A job failed with reason `err`!
160
- await doInJobContext(job, () => {
161
- console.error(
162
- ...getLogParams(eventType, BullEvent.FAILED, { job, error })
163
- )
164
- })
165
- })
166
- .on(BullEvent.PAUSED, () => {
167
- // The queue has been paused.
168
- console.info(...getLogParams(eventType, BullEvent.PAUSED))
169
- })
170
- .on(BullEvent.RESUMED, () => {
171
- // The queue has been resumed.
172
- console.info(...getLogParams(eventType, BullEvent.RESUMED))
173
- })
174
- .on(BullEvent.CLEANED, (jobs: Job[], type: string) => {
175
- // Old jobs have been cleaned from the queue. `jobs` is an array of cleaned
176
- // jobs, and `type` is the type of jobs cleaned.
177
- console.info(
178
- ...getLogParams(
179
- eventType,
180
- BullEvent.CLEANED,
181
- {},
182
- { length: jobs.length, type }
183
- )
184
- )
185
- })
186
- .on(BullEvent.DRAINED, () => {
187
- // Emitted every time the queue has processed all the waiting jobs (even if there can be some delayed jobs not yet processed)
188
- console.info(...getLogParams(eventType, BullEvent.DRAINED))
189
- })
190
- .on(BullEvent.REMOVED, (job: Job) => {
191
- // A job successfully removed.
192
- console.info(...getLogParams(eventType, BullEvent.REMOVED, { job }))
193
- })
194
- }
195
- }
@@ -1,54 +0,0 @@
1
- import env from "../environment"
2
- import { getRedisOptions } from "../redis/utils"
3
- import { JobQueue } from "./constants"
4
- import InMemoryQueue from "./inMemoryQueue"
5
- import BullQueue from "bull"
6
- import { addListeners, StalledFn } from "./listeners"
7
- import * as timers from "../timers"
8
-
9
- const CLEANUP_PERIOD_MS = 60 * 1000
10
- let QUEUES: BullQueue.Queue[] | InMemoryQueue[] = []
11
- let cleanupInterval: NodeJS.Timeout
12
-
13
- async function cleanup() {
14
- for (let queue of QUEUES) {
15
- await queue.clean(CLEANUP_PERIOD_MS, "completed")
16
- }
17
- }
18
-
19
- export function createQueue<T>(
20
- jobQueue: JobQueue,
21
- opts: { removeStalledCb?: StalledFn } = {}
22
- ): BullQueue.Queue<T> {
23
- const { opts: redisOpts, redisProtocolUrl } = getRedisOptions()
24
- const queueConfig: any = redisProtocolUrl || { redis: redisOpts }
25
- let queue: any
26
- if (!env.isTest()) {
27
- queue = new BullQueue(jobQueue, queueConfig)
28
- } else {
29
- queue = new InMemoryQueue(jobQueue, queueConfig)
30
- }
31
- addListeners(queue, jobQueue, opts?.removeStalledCb)
32
- QUEUES.push(queue)
33
- if (!cleanupInterval && !env.isTest()) {
34
- cleanupInterval = timers.set(cleanup, CLEANUP_PERIOD_MS)
35
- // fire off an initial cleanup
36
- cleanup().catch(err => {
37
- console.error(`Unable to cleanup automation queue initially - ${err}`)
38
- })
39
- }
40
- return queue
41
- }
42
-
43
- export async function shutdown() {
44
- if (cleanupInterval) {
45
- timers.clear(cleanupInterval)
46
- }
47
- if (QUEUES.length) {
48
- for (let queue of QUEUES) {
49
- await queue.close()
50
- }
51
- QUEUES = []
52
- }
53
- console.log("Queues shutdown")
54
- }
@@ -1,6 +0,0 @@
1
- // Mimic the outer package export for usage in index.ts
2
- // The outer exports can't be used as they now reference dist directly
3
- export { default as Client } from "./redis"
4
- export * as utils from "./utils"
5
- export * as clients from "./init"
6
- export * as locks from "./redlockImpl"