velocious 1.0.482 → 1.0.483

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 (33) hide show
  1. package/README.md +2 -0
  2. package/build/cli/commands/db/tenants/drop.js +34 -0
  3. package/build/cli/tenant-database-command-helper.js +8 -85
  4. package/build/database/tenants/data-copier.js +269 -0
  5. package/build/database/tenants/tenant-table-plan.js +20 -0
  6. package/build/src/cli/commands/db/tenants/drop.d.ts +13 -0
  7. package/build/src/cli/commands/db/tenants/drop.d.ts.map +1 -0
  8. package/build/src/cli/commands/db/tenants/drop.js +31 -0
  9. package/build/src/cli/tenant-database-command-helper.d.ts +0 -20
  10. package/build/src/cli/tenant-database-command-helper.d.ts.map +1 -1
  11. package/build/src/cli/tenant-database-command-helper.js +8 -73
  12. package/build/src/database/tenants/data-copier.d.ts +125 -0
  13. package/build/src/database/tenants/data-copier.d.ts.map +1 -0
  14. package/build/src/database/tenants/data-copier.js +232 -0
  15. package/build/src/database/tenants/tenant-table-plan.d.ts +30 -0
  16. package/build/src/database/tenants/tenant-table-plan.d.ts.map +1 -0
  17. package/build/src/database/tenants/tenant-table-plan.js +3 -0
  18. package/build/src/tenants/tenant-iterator.d.ts +52 -0
  19. package/build/src/tenants/tenant-iterator.d.ts.map +1 -0
  20. package/build/src/tenants/tenant-iterator.js +97 -0
  21. package/build/src/tenants/tenant.d.ts +51 -0
  22. package/build/src/tenants/tenant.d.ts.map +1 -0
  23. package/build/src/tenants/tenant.js +76 -0
  24. package/build/tenants/tenant-iterator.js +111 -0
  25. package/build/tenants/tenant.js +86 -0
  26. package/build/tsconfig.tsbuildinfo +1 -1
  27. package/package.json +1 -1
  28. package/src/cli/commands/db/tenants/drop.js +34 -0
  29. package/src/cli/tenant-database-command-helper.js +8 -85
  30. package/src/database/tenants/data-copier.js +269 -0
  31. package/src/database/tenants/tenant-table-plan.js +20 -0
  32. package/src/tenants/tenant-iterator.js +111 -0
  33. package/src/tenants/tenant.js +86 -0
@@ -0,0 +1,111 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * Runs a callback once within each tenant's context for a tenant database identifier,
5
+ * optionally several tenants at a time. Each tenant is entered with `runWithTenant`, and a
6
+ * tenant whose database identifier is inactive throws rather than running the callback
7
+ * against the wrong connection. When iterating in parallel the per-tenant failures are
8
+ * collected and rethrown together as an `AggregateError` so one bad tenant does not hide the
9
+ * others. This is the iteration engine shared by the `db:tenants:*` CLI commands and the
10
+ * runtime {@link Tenant} façade; the caller is responsible for producing the tenant list.
11
+ */
12
+ export default class TenantIterator {
13
+ /**
14
+ * Creates an iterator bound to a configuration and tenant database identifier.
15
+ * @param {{configuration: import("../configuration.js").default, identifier: string, parallelCount?: number}} args
16
+ */
17
+ constructor({configuration, identifier, parallelCount = 1}) {
18
+ this.configuration = configuration
19
+ this.identifier = identifier
20
+ this.parallelCount = parallelCount
21
+ }
22
+
23
+ /**
24
+ * Runs `callback` within each tenant's context and returns how many tenants were processed.
25
+ * @param {Array<?>} tenants
26
+ * @param {function({databaseConfiguration: import("../configuration-types.js").DatabaseConfigurationType, tenant: ?}) : Promise<void>} callback
27
+ * @returns {Promise<number>}
28
+ */
29
+ async run(tenants, callback) {
30
+ if (this.parallelCount <= 1) {
31
+ for (const tenant of tenants) {
32
+ await this.runTenantCallback({callback, tenant})
33
+ }
34
+
35
+ return tenants.length
36
+ }
37
+
38
+ /** @type {Array<{error: Error, tenant: ?}>} */
39
+ const failures = []
40
+ const workers = []
41
+ let tenantIndex = 0
42
+ const workerCount = Math.min(this.parallelCount, tenants.length)
43
+
44
+ for (let workerIndex = 0; workerIndex < workerCount; workerIndex++) {
45
+ workers.push((async () => {
46
+ while (tenantIndex < tenants.length) {
47
+ const tenant = tenants[tenantIndex]
48
+
49
+ tenantIndex++
50
+
51
+ try {
52
+ await this.runTenantCallback({callback, tenant})
53
+ } catch (error) {
54
+ failures.push({
55
+ error: error instanceof Error ? error : new Error(String(error)),
56
+ tenant
57
+ })
58
+ }
59
+ }
60
+ })())
61
+ }
62
+
63
+ await Promise.all(workers)
64
+
65
+ if (failures.length > 0) {
66
+ const failedTenantLabels = failures.map((failure) => TenantIterator.tenantLabel(failure.tenant)).join(", ")
67
+
68
+ throw new AggregateError(
69
+ failures.map((failure) => failure.error),
70
+ `Failed tenant database command for tenant(s): ${failedTenantLabels}`
71
+ )
72
+ }
73
+
74
+ return tenants.length
75
+ }
76
+
77
+ /**
78
+ * Enters one tenant's context and runs the callback, asserting the database is active first.
79
+ * @param {{callback: function({databaseConfiguration: import("../configuration-types.js").DatabaseConfigurationType, tenant: ?}) : Promise<void>, tenant: ?}} args
80
+ * @returns {Promise<void>}
81
+ */
82
+ async runTenantCallback({callback, tenant}) {
83
+ await this.configuration.runWithTenant(tenant, async () => {
84
+ if (!this.configuration.isDatabaseIdentifierActive(this.identifier)) {
85
+ throw new Error(`Tenant database identifier ${this.identifier} is inactive for tenant: ${TenantIterator.tenantLabel(tenant)}`)
86
+ }
87
+
88
+ await callback({
89
+ databaseConfiguration: this.configuration.resolveDatabaseConfiguration(this.identifier),
90
+ tenant
91
+ })
92
+ })
93
+ }
94
+
95
+ /**
96
+ * Builds a human-readable label for a tenant for use in error messages.
97
+ * @param {?} tenant
98
+ * @returns {string}
99
+ */
100
+ static tenantLabel(tenant) {
101
+ if (tenant && typeof tenant === "object") {
102
+ const tenantObject = /** @type {{id?: ?, name?: ?, slug?: ?}} */ (tenant)
103
+
104
+ if (tenantObject.slug) return String(tenantObject.slug)
105
+ if (tenantObject.name) return String(tenantObject.name)
106
+ if (tenantObject.id) return String(tenantObject.id)
107
+ }
108
+
109
+ return JSON.stringify(tenant)
110
+ }
111
+ }
@@ -0,0 +1,86 @@
1
+ // @ts-check
2
+
3
+ import Current from "../current.js"
4
+ import TenantIterator from "./tenant-iterator.js"
5
+
6
+ /**
7
+ * Apartment-style runtime façade for multi-tenant apps. A "tenant" is whatever descriptor
8
+ * object the app's `tenantDatabaseResolver` understands (an account, a project, …); this
9
+ * class is the single discoverable home for switching into a tenant's context, reading the
10
+ * current one, iterating every tenant of a database identifier, and dropping a tenant's
11
+ * database. Switching/reading delegate to {@link Current} (which owns the async-context
12
+ * tenant state), so they compose with the existing connection pools and request lifecycle;
13
+ * iteration and drop drive the app's tenant database provider hooks.
14
+ */
15
+ export default class Tenant {
16
+ /**
17
+ * Runs `callback` with `tenant` as the current tenant, restoring the previous tenant after.
18
+ * @param {object} tenant Descriptor understood by the app's tenantDatabaseResolver.
19
+ * @param {() => Promise<?>} callback
20
+ * @returns {Promise<?>}
21
+ */
22
+ static async with(tenant, callback) {
23
+ return await Current.withTenant(tenant, callback)
24
+ }
25
+
26
+ /**
27
+ * The current tenant descriptor, or undefined when running outside any tenant context.
28
+ * @returns {Record<string, unknown> | undefined}
29
+ */
30
+ static current() {
31
+ return Current.tenant()
32
+ }
33
+
34
+ /**
35
+ * Lists the tenants for a database identifier through the provider and runs `callback`
36
+ * within each tenant's context, optionally filtered and several at a time. Returns how
37
+ * many tenants the callback ran for (after filtering).
38
+ * @param {{identifier: string, callback: function({databaseConfiguration: import("../configuration-types.js").DatabaseConfigurationType, tenant: ?}) : Promise<void>, parallel?: number, filter?: (tenant: ?) => boolean, configuration?: import("../configuration.js").default}} args
39
+ * @returns {Promise<number>}
40
+ */
41
+ static async each({identifier, callback, parallel = 1, filter, configuration = Current.configuration()}) {
42
+ const provider = configuration.getTenantDatabaseProvider(identifier)
43
+ const listedTenants = await configuration.ensureConnections({name: `Tenant.each: ${identifier}`}, async () => {
44
+ return await provider.listTenants({configuration, identifier})
45
+ })
46
+
47
+ if (!Array.isArray(listedTenants)) {
48
+ throw new Error(`Tenant database provider for ${identifier} must return an array from listTenants`)
49
+ }
50
+
51
+ const tenants = filter ? listedTenants.filter(filter) : listedTenants
52
+ const iterator = new TenantIterator({configuration, identifier, parallelCount: parallel})
53
+
54
+ return await iterator.run(tenants, callback)
55
+ }
56
+
57
+ /**
58
+ * Drops one tenant's database/schema through the provider's `dropDatabase` hook.
59
+ * @param {{identifier: string, tenant: object, configuration?: import("../configuration.js").default}} args
60
+ * @returns {Promise<void>}
61
+ */
62
+ static async drop({identifier, tenant, configuration = Current.configuration()}) {
63
+ const provider = configuration.getTenantDatabaseProvider(identifier)
64
+
65
+ if (typeof provider.dropDatabase !== "function") {
66
+ throw new Error(`Tenant database provider for ${identifier} must define dropDatabase to drop a tenant`)
67
+ }
68
+
69
+ await configuration.runWithTenant(tenant, async () => {
70
+ // Guard against an unresolved tenant. resolveDatabaseConfiguration falls back to the
71
+ // base (template/default) tenant database when the resolver returns nothing for this
72
+ // descriptor, so without this check a provider that drops by databaseConfiguration.name
73
+ // would drop the template database instead of rejecting the bad tenant.
74
+ if (!configuration.isDatabaseIdentifierActive(identifier)) {
75
+ throw new Error(`Tenant database identifier ${identifier} is inactive for tenant: ${TenantIterator.tenantLabel(tenant)}`)
76
+ }
77
+
78
+ await provider.dropDatabase?.({
79
+ configuration,
80
+ databaseConfiguration: configuration.resolveDatabaseConfiguration(identifier),
81
+ identifier,
82
+ tenant
83
+ })
84
+ })
85
+ }
86
+ }