@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,138 +0,0 @@
1
- import { DBTestConfiguration } from "../../../tests/extra"
2
- import {
3
- structures,
4
- expectFunctionWasCalledTimesWith,
5
- mocks,
6
- } from "../../../tests"
7
- import { Writethrough } from "../writethrough"
8
- import { getDB } from "../../db"
9
- import tk from "timekeeper"
10
-
11
- tk.freeze(Date.now())
12
-
13
- const DELAY = 5000
14
-
15
- describe("writethrough", () => {
16
- const config = new DBTestConfiguration()
17
-
18
- const db = getDB(structures.db.id())
19
- const db2 = getDB(structures.db.id())
20
-
21
- const writethrough = new Writethrough(db, DELAY)
22
- const writethrough2 = new Writethrough(db2, DELAY)
23
-
24
- const docId = structures.uuid()
25
-
26
- beforeEach(() => {
27
- jest.clearAllMocks()
28
- })
29
-
30
- describe("put", () => {
31
- let current: any
32
-
33
- it("should be able to store, will go to DB", async () => {
34
- await config.doInTenant(async () => {
35
- const response = await writethrough.put({
36
- _id: docId,
37
- value: 1,
38
- })
39
- const output = await db.get<any>(response.id)
40
- current = output
41
- expect(output.value).toBe(1)
42
- })
43
- })
44
-
45
- it("second put shouldn't update DB", async () => {
46
- await config.doInTenant(async () => {
47
- const response = await writethrough.put({ ...current, value: 2 })
48
- const output = await db.get<any>(response.id)
49
- expect(current._rev).toBe(output._rev)
50
- expect(output.value).toBe(1)
51
- })
52
- })
53
-
54
- it("should put it again after delay period", async () => {
55
- await config.doInTenant(async () => {
56
- tk.freeze(Date.now() + DELAY + 1)
57
- const response = await writethrough.put({ ...current, value: 3 })
58
- const output = await db.get<any>(response.id)
59
- expect(response.rev).not.toBe(current._rev)
60
- expect(output.value).toBe(3)
61
-
62
- current = output
63
- })
64
- })
65
-
66
- it("should handle parallel DB updates ignoring conflicts", async () => {
67
- await config.doInTenant(async () => {
68
- tk.freeze(Date.now() + DELAY + 1)
69
- const responses = await Promise.all([
70
- writethrough.put({ ...current, value: 4 }),
71
- writethrough.put({ ...current, value: 4 }),
72
- writethrough.put({ ...current, value: 4 }),
73
- ])
74
-
75
- // with a lock, this will work
76
- const newRev = responses.map(x => x.rev).find(x => x !== current._rev)
77
- expect(newRev).toBeDefined()
78
- expect(responses.map(x => x.rev)).toEqual(
79
- expect.arrayContaining([current._rev, current._rev, newRev])
80
- )
81
-
82
- const output = await db.get<any>(current._id)
83
- expect(output.value).toBe(4)
84
- expect(output._rev).toBe(newRev)
85
-
86
- current = output
87
- })
88
- })
89
-
90
- it("should handle updates with documents falling behind", async () => {
91
- await config.doInTenant(async () => {
92
- tk.freeze(Date.now() + DELAY + 1)
93
-
94
- const id = structures.uuid()
95
- await writethrough.put({ _id: id, value: 1 })
96
- const doc = await writethrough.get(id)
97
-
98
- // Updating document
99
- tk.freeze(Date.now() + DELAY + 1)
100
- await writethrough.put({ ...doc, value: 2 })
101
-
102
- // Update with the old rev value
103
- tk.freeze(Date.now() + DELAY + 1)
104
- const res = await writethrough.put({
105
- ...doc,
106
- value: 3,
107
- })
108
- expect(res.ok).toBe(true)
109
-
110
- const output = await db.get<any>(id)
111
- expect(output.value).toBe(3)
112
- expect(output._rev).toBe(res.rev)
113
- })
114
- })
115
- })
116
-
117
- describe("get", () => {
118
- it("should be able to retrieve", async () => {
119
- await config.doInTenant(async () => {
120
- const response = await writethrough.get(docId)
121
- expect(response.value).toBe(4)
122
- })
123
- })
124
- })
125
-
126
- describe("same doc, different databases (tenancy)", () => {
127
- it("should be able to two different databases", async () => {
128
- await config.doInTenant(async () => {
129
- const resp1 = await writethrough.put({ _id: "db1", value: "first" })
130
- const resp2 = await writethrough2.put({ _id: "db1", value: "second" })
131
- expect(resp1.rev).toBeDefined()
132
- expect(resp2.rev).toBeDefined()
133
- expect((await db.get<any>("db1")).value).toBe("first")
134
- expect((await db2.get<any>("db1")).value).toBe("second")
135
- })
136
- })
137
- })
138
- })
package/src/cache/user.ts DELETED
@@ -1,69 +0,0 @@
1
- import * as redis from "../redis/init"
2
- import * as tenancy from "../tenancy"
3
- import * as context from "../context"
4
- import * as platform from "../platform"
5
- import env from "../environment"
6
- import * as accounts from "../accounts"
7
-
8
- const EXPIRY_SECONDS = 3600
9
-
10
- /**
11
- * The default populate user function
12
- */
13
- async function populateFromDB(userId: string, tenantId: string) {
14
- const db = tenancy.getTenantDB(tenantId)
15
- const user = await db.get<any>(userId)
16
- user.budibaseAccess = true
17
- if (!env.SELF_HOSTED && !env.DISABLE_ACCOUNT_PORTAL) {
18
- const account = await accounts.getAccount(user.email)
19
- if (account) {
20
- user.account = account
21
- user.accountPortalAccess = true
22
- }
23
- }
24
-
25
- return user
26
- }
27
-
28
- /**
29
- * Get the requested user by id.
30
- * Use redis cache to first read the user.
31
- * If not present fallback to loading the user directly and re-caching.
32
- * @param {*} userId the id of the user to get
33
- * @param {*} tenantId the tenant of the user to get
34
- * @param {*} populateUser function to provide the user for re-caching. default to couch db
35
- * @returns
36
- */
37
- export async function getUser(
38
- userId: string,
39
- tenantId?: string,
40
- populateUser?: any
41
- ) {
42
- if (!populateUser) {
43
- populateUser = populateFromDB
44
- }
45
- if (!tenantId) {
46
- try {
47
- tenantId = context.getTenantId()
48
- } catch (err) {
49
- tenantId = await platform.users.lookupTenantId(userId)
50
- }
51
- }
52
- const client = await redis.getUserClient()
53
- // try cache
54
- let user = await client.get(userId)
55
- if (!user) {
56
- user = await populateUser(userId, tenantId)
57
- await client.store(userId, user, EXPIRY_SECONDS)
58
- }
59
- if (user && !user.tenantId && tenantId) {
60
- // make sure the tenant ID is always correct/set
61
- user.tenantId = tenantId
62
- }
63
- return user
64
- }
65
-
66
- export async function invalidateUser(userId: string) {
67
- const client = await redis.getUserClient()
68
- await client.delete(userId)
69
- }
@@ -1,133 +0,0 @@
1
- import BaseCache from "./base"
2
- import { getWritethroughClient } from "../redis/init"
3
- import { logWarn } from "../logging"
4
- import { Database, Document, LockName, LockType } from "@budibase/types"
5
- import * as locks from "../redis/redlockImpl"
6
-
7
- const DEFAULT_WRITE_RATE_MS = 10000
8
- let CACHE: BaseCache | null = null
9
-
10
- interface CacheItem {
11
- doc: any
12
- lastWrite: number
13
- }
14
-
15
- async function getCache() {
16
- if (!CACHE) {
17
- const client = await getWritethroughClient()
18
- CACHE = new BaseCache(client)
19
- }
20
- return CACHE
21
- }
22
-
23
- function makeCacheKey(db: Database, key: string) {
24
- return db.name + key
25
- }
26
-
27
- function makeCacheItem(doc: any, lastWrite: number | null = null): CacheItem {
28
- return { doc, lastWrite: lastWrite || Date.now() }
29
- }
30
-
31
- async function put(
32
- db: Database,
33
- doc: Document,
34
- writeRateMs: number = DEFAULT_WRITE_RATE_MS
35
- ) {
36
- const cache = await getCache()
37
- const key = doc._id
38
- let cacheItem: CacheItem | undefined
39
- if (key) {
40
- cacheItem = await cache.get(makeCacheKey(db, key))
41
- }
42
- const updateDb = !cacheItem || cacheItem.lastWrite < Date.now() - writeRateMs
43
- let output = doc
44
- if (updateDb) {
45
- const lockResponse = await locks.doWithLock(
46
- {
47
- type: LockType.TRY_ONCE,
48
- name: LockName.PERSIST_WRITETHROUGH,
49
- resource: key,
50
- ttl: 15000,
51
- },
52
- async () => {
53
- const writeDb = async (toWrite: any) => {
54
- // doc should contain the _id and _rev
55
- const response = await db.put(toWrite, { force: true })
56
- output = {
57
- ...doc,
58
- _id: response.id,
59
- _rev: response.rev,
60
- }
61
- }
62
- try {
63
- await writeDb(doc)
64
- } catch (err: any) {
65
- if (err.status !== 409) {
66
- throw err
67
- } else {
68
- // Swallow 409s but log them
69
- logWarn(`Ignoring conflict in write-through cache`)
70
- }
71
- }
72
- }
73
- )
74
-
75
- if (!lockResponse.executed) {
76
- logWarn(`Ignoring redlock conflict in write-through cache`)
77
- }
78
- }
79
- // if we are updating the DB then need to set the lastWrite to now
80
- cacheItem = makeCacheItem(output, updateDb ? null : cacheItem?.lastWrite)
81
- if (output._id) {
82
- await cache.store(makeCacheKey(db, output._id), cacheItem)
83
- }
84
- return { ok: true, id: output._id, rev: output._rev }
85
- }
86
-
87
- async function get(db: Database, id: string): Promise<any> {
88
- const cache = await getCache()
89
- const cacheKey = makeCacheKey(db, id)
90
- let cacheItem: CacheItem = await cache.get(cacheKey)
91
- if (!cacheItem) {
92
- const doc = await db.get(id)
93
- cacheItem = makeCacheItem(doc)
94
- await cache.store(cacheKey, cacheItem)
95
- }
96
- return cacheItem.doc
97
- }
98
-
99
- async function remove(db: Database, docOrId: any, rev?: any): Promise<void> {
100
- const cache = await getCache()
101
- if (!docOrId) {
102
- throw new Error("No ID/Rev provided.")
103
- }
104
- const id = typeof docOrId === "string" ? docOrId : docOrId._id
105
- rev = typeof docOrId === "string" ? rev : docOrId._rev
106
- try {
107
- await cache.delete(makeCacheKey(db, id))
108
- } finally {
109
- await db.remove(id, rev)
110
- }
111
- }
112
-
113
- export class Writethrough {
114
- db: Database
115
- writeRateMs: number
116
-
117
- constructor(db: Database, writeRateMs: number = DEFAULT_WRITE_RATE_MS) {
118
- this.db = db
119
- this.writeRateMs = writeRateMs
120
- }
121
-
122
- async put(doc: any) {
123
- return put(this.db, doc, this.writeRateMs)
124
- }
125
-
126
- async get(id: string) {
127
- return get(this.db, id)
128
- }
129
-
130
- async remove(docOrId: any, rev?: any) {
131
- return remove(this.db, docOrId, rev)
132
- }
133
- }
@@ -1,257 +0,0 @@
1
- import {
2
- Config,
3
- ConfigType,
4
- GoogleConfig,
5
- GoogleInnerConfig,
6
- OIDCConfig,
7
- OIDCInnerConfig,
8
- OIDCLogosConfig,
9
- SCIMConfig,
10
- SCIMInnerConfig,
11
- SettingsConfig,
12
- SettingsInnerConfig,
13
- SMTPConfig,
14
- SMTPInnerConfig,
15
- } from "@budibase/types"
16
- import { DocumentType, SEPARATOR } from "../constants"
17
- import { CacheKey, TTL, withCache } from "../cache"
18
- import * as context from "../context"
19
- import env from "../environment"
20
- import environment from "../environment"
21
-
22
- // UTILS
23
-
24
- /**
25
- * Generates a new configuration ID.
26
- * @returns {string} The new configuration ID which the config doc can be stored under.
27
- */
28
- export function generateConfigID(type: ConfigType) {
29
- return `${DocumentType.CONFIG}${SEPARATOR}${type}`
30
- }
31
-
32
- export async function getConfig<T extends Config>(
33
- type: ConfigType
34
- ): Promise<T | undefined> {
35
- const db = context.getGlobalDB()
36
- try {
37
- // await to catch error
38
- return (await db.get(generateConfigID(type))) as T
39
- } catch (e: any) {
40
- if (e.status === 404) {
41
- return
42
- }
43
- throw e
44
- }
45
- }
46
-
47
- export async function save(
48
- config: Config
49
- ): Promise<{ id: string; rev: string }> {
50
- const db = context.getGlobalDB()
51
- return db.put(config)
52
- }
53
-
54
- // SETTINGS
55
-
56
- export async function getSettingsConfigDoc(): Promise<SettingsConfig> {
57
- let config = await getConfig<SettingsConfig>(ConfigType.SETTINGS)
58
-
59
- if (!config) {
60
- config = {
61
- _id: generateConfigID(ConfigType.SETTINGS),
62
- type: ConfigType.SETTINGS,
63
- config: {},
64
- }
65
- }
66
-
67
- // overridden fields
68
- config.config.platformUrl = await getPlatformUrl({
69
- tenantAware: true,
70
- config: config.config,
71
- })
72
- config.config.analyticsEnabled = await analyticsEnabled({
73
- config: config.config,
74
- })
75
-
76
- return config
77
- }
78
-
79
- export async function getSettingsConfig(): Promise<SettingsInnerConfig> {
80
- return (await getSettingsConfigDoc()).config
81
- }
82
-
83
- export async function getPlatformUrl(
84
- opts: { tenantAware: boolean; config?: SettingsInnerConfig } = {
85
- tenantAware: true,
86
- }
87
- ) {
88
- let platformUrl = env.PLATFORM_URL || "http://localhost:10000"
89
-
90
- if (!env.SELF_HOSTED && env.MULTI_TENANCY && opts.tenantAware) {
91
- // cloud and multi tenant - add the tenant to the default platform url
92
- const tenantId = context.getTenantId()
93
- if (!platformUrl.includes("localhost:")) {
94
- platformUrl = platformUrl.replace("://", `://${tenantId}.`)
95
- }
96
- } else if (env.SELF_HOSTED) {
97
- const config = opts?.config
98
- ? opts.config
99
- : // direct to db to prevent infinite loop
100
- (await getConfig<SettingsConfig>(ConfigType.SETTINGS))?.config
101
- if (config?.platformUrl) {
102
- platformUrl = config.platformUrl
103
- }
104
- }
105
-
106
- return platformUrl
107
- }
108
-
109
- export const analyticsEnabled = async (opts?: {
110
- config?: SettingsInnerConfig
111
- }) => {
112
- // cloud - always use the environment variable
113
- if (!env.SELF_HOSTED) {
114
- return !!env.ENABLE_ANALYTICS
115
- }
116
-
117
- // self host - prefer the settings doc
118
- // use cache as events have high throughput
119
- const enabledInDB = await withCache(
120
- CacheKey.ANALYTICS_ENABLED,
121
- TTL.ONE_DAY,
122
- async () => {
123
- const config = opts?.config
124
- ? opts.config
125
- : // direct to db to prevent infinite loop
126
- (await getConfig<SettingsConfig>(ConfigType.SETTINGS))?.config
127
-
128
- // need to do explicit checks in case the field is not set
129
- if (config?.analyticsEnabled === false) {
130
- return false
131
- } else if (config?.analyticsEnabled === true) {
132
- return true
133
- }
134
- }
135
- )
136
-
137
- if (enabledInDB !== undefined) {
138
- return enabledInDB
139
- }
140
-
141
- // fallback to the environment variable
142
- // explicitly check for 0 or false here, undefined or otherwise is treated as true
143
- const envEnabled: any = env.ENABLE_ANALYTICS
144
- if (envEnabled === 0 || envEnabled === false) {
145
- return false
146
- } else {
147
- return true
148
- }
149
- }
150
-
151
- // GOOGLE
152
-
153
- async function getGoogleConfigDoc(): Promise<GoogleConfig | undefined> {
154
- return await getConfig<GoogleConfig>(ConfigType.GOOGLE)
155
- }
156
-
157
- export async function getGoogleConfig(): Promise<
158
- GoogleInnerConfig | undefined
159
- > {
160
- const config = await getGoogleConfigDoc()
161
- return config?.config
162
- }
163
-
164
- export async function getGoogleDatasourceConfig(): Promise<
165
- GoogleInnerConfig | undefined
166
- > {
167
- if (!env.SELF_HOSTED) {
168
- // always use the env vars in cloud
169
- return getDefaultGoogleConfig()
170
- }
171
-
172
- // prefer the config in self-host
173
- let config = await getGoogleConfig()
174
-
175
- // fallback to env vars
176
- if (!config || !config.activated) {
177
- config = getDefaultGoogleConfig()
178
- }
179
-
180
- return config
181
- }
182
-
183
- export function getDefaultGoogleConfig(): GoogleInnerConfig | undefined {
184
- if (environment.GOOGLE_CLIENT_ID && environment.GOOGLE_CLIENT_SECRET) {
185
- return {
186
- clientID: environment.GOOGLE_CLIENT_ID!,
187
- clientSecret: environment.GOOGLE_CLIENT_SECRET!,
188
- activated: true,
189
- }
190
- }
191
- }
192
-
193
- // OIDC
194
-
195
- export async function getOIDCLogosDoc(): Promise<OIDCLogosConfig | undefined> {
196
- return getConfig<OIDCLogosConfig>(ConfigType.OIDC_LOGOS)
197
- }
198
-
199
- async function getOIDCConfigDoc(): Promise<OIDCConfig | undefined> {
200
- return getConfig<OIDCConfig>(ConfigType.OIDC)
201
- }
202
-
203
- export async function getOIDCConfig(): Promise<OIDCInnerConfig | undefined> {
204
- const config = (await getOIDCConfigDoc())?.config
205
- // default to the 0th config
206
- return config?.configs && config.configs[0]
207
- }
208
-
209
- /**
210
- * @param configId The config id of the inner config to retrieve
211
- */
212
- export async function getOIDCConfigById(
213
- configId: string
214
- ): Promise<OIDCInnerConfig | undefined> {
215
- const config = (await getConfig<OIDCConfig>(ConfigType.OIDC))?.config
216
- return config && config.configs.filter((c: any) => c.uuid === configId)[0]
217
- }
218
-
219
- // SMTP
220
-
221
- export async function getSMTPConfigDoc(): Promise<SMTPConfig | undefined> {
222
- return getConfig<SMTPConfig>(ConfigType.SMTP)
223
- }
224
-
225
- export async function getSMTPConfig(
226
- isAutomation?: boolean
227
- ): Promise<SMTPInnerConfig | undefined> {
228
- const config = await getSMTPConfigDoc()
229
- if (config) {
230
- return config.config
231
- }
232
-
233
- // always allow fallback in self host
234
- // in cloud don't allow for automations
235
- const allowFallback = env.SELF_HOSTED || !isAutomation
236
-
237
- // Use an SMTP fallback configuration from env variables
238
- if (env.SMTP_FALLBACK_ENABLED && allowFallback) {
239
- return {
240
- port: env.SMTP_PORT,
241
- host: env.SMTP_HOST!,
242
- secure: false,
243
- from: env.SMTP_FROM_ADDRESS!,
244
- auth: {
245
- user: env.SMTP_USER!,
246
- pass: env.SMTP_PASSWORD!,
247
- },
248
- }
249
- }
250
- }
251
-
252
- // SCIM
253
-
254
- export async function getSCIMConfig(): Promise<SCIMInnerConfig | undefined> {
255
- const config = await getConfig<SCIMConfig>(ConfigType.SCIM)
256
- return config?.config
257
- }
@@ -1 +0,0 @@
1
- export * from "./configs"