velocious 1.0.482 → 1.0.484

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 +61 -0
  22. package/build/src/tenants/tenant.d.ts.map +1 -0
  23. package/build/src/tenants/tenant.js +93 -0
  24. package/build/tenants/tenant-iterator.js +111 -0
  25. package/build/tenants/tenant.js +104 -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 +104 -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,104 @@
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 delegates to {@link Current} (which owns the async-context tenant
12
+ * state) and additionally runs the callback inside `ensureConnections`, so entering a tenant
13
+ * makes its database immediately queryable — the apartment-style "switch" semantics — without
14
+ * the caller establishing connections itself; iteration and drop drive the app's tenant
15
+ * database provider hooks.
16
+ */
17
+ export default class Tenant {
18
+ /**
19
+ * Runs `callback` with `tenant` as the current tenant, restoring the previous tenant after.
20
+ * The callback runs inside `ensureConnections`, so every database identifier the tenant
21
+ * activates (the global database plus the tenant's database) has a checked-out connection
22
+ * available for the callback's duration: switching into a tenant makes it queryable without
23
+ * the caller wiring up connections. Already-checked-out connections are reused, so nesting
24
+ * `Tenant.with` calls does not open redundant connections. The callback receives the active
25
+ * connections keyed by identifier, the same as `ensureConnections`.
26
+ * @param {object} tenant Descriptor understood by the app's tenantDatabaseResolver.
27
+ * @param {(connections: Record<string, import("../database/drivers/base.js").default>) => Promise<?>} callback
28
+ * @returns {Promise<?>}
29
+ */
30
+ static async with(tenant, callback) {
31
+ const configuration = Current.configuration()
32
+
33
+ return await Current.withTenant(tenant, async () => await configuration.ensureConnections(callback))
34
+ }
35
+
36
+ /**
37
+ * The current tenant descriptor, or undefined when running outside any tenant context.
38
+ * @returns {Record<string, unknown> | undefined}
39
+ */
40
+ static current() {
41
+ return Current.tenant()
42
+ }
43
+
44
+ /**
45
+ * Lists the tenants for a database identifier through the provider and runs `callback`
46
+ * within each tenant's context, optionally filtered and several at a time. Like
47
+ * {@link Tenant.with}, the callback runs inside `ensureConnections` so each tenant's
48
+ * database is queryable without the caller wiring up connections. Returns how many tenants
49
+ * the callback ran for (after filtering).
50
+ * @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
51
+ * @returns {Promise<number>}
52
+ */
53
+ static async each({identifier, callback, parallel = 1, filter, configuration = Current.configuration()}) {
54
+ const provider = configuration.getTenantDatabaseProvider(identifier)
55
+ const listedTenants = await configuration.ensureConnections({name: `Tenant.each: ${identifier}`}, async () => {
56
+ return await provider.listTenants({configuration, identifier})
57
+ })
58
+
59
+ if (!Array.isArray(listedTenants)) {
60
+ throw new Error(`Tenant database provider for ${identifier} must return an array from listTenants`)
61
+ }
62
+
63
+ const tenants = filter ? listedTenants.filter(filter) : listedTenants
64
+ const iterator = new TenantIterator({configuration, identifier, parallelCount: parallel})
65
+
66
+ // Run each tenant's callback inside ensureConnections so the iterator stays
67
+ // connection-agnostic (the db:tenants:* CLI commands share TenantIterator and must run
68
+ // their callbacks, such as create, before the tenant database exists) while runtime
69
+ // iteration here gets the tenant's connections established the same way Tenant.with does.
70
+ return await iterator.run(tenants, async (callbackArgs) => {
71
+ await configuration.ensureConnections({name: `Tenant.each: ${identifier}`}, async () => await callback(callbackArgs))
72
+ })
73
+ }
74
+
75
+ /**
76
+ * Drops one tenant's database/schema through the provider's `dropDatabase` hook.
77
+ * @param {{identifier: string, tenant: object, configuration?: import("../configuration.js").default}} args
78
+ * @returns {Promise<void>}
79
+ */
80
+ static async drop({identifier, tenant, configuration = Current.configuration()}) {
81
+ const provider = configuration.getTenantDatabaseProvider(identifier)
82
+
83
+ if (typeof provider.dropDatabase !== "function") {
84
+ throw new Error(`Tenant database provider for ${identifier} must define dropDatabase to drop a tenant`)
85
+ }
86
+
87
+ await configuration.runWithTenant(tenant, async () => {
88
+ // Guard against an unresolved tenant. resolveDatabaseConfiguration falls back to the
89
+ // base (template/default) tenant database when the resolver returns nothing for this
90
+ // descriptor, so without this check a provider that drops by databaseConfiguration.name
91
+ // would drop the template database instead of rejecting the bad tenant.
92
+ if (!configuration.isDatabaseIdentifierActive(identifier)) {
93
+ throw new Error(`Tenant database identifier ${identifier} is inactive for tenant: ${TenantIterator.tenantLabel(tenant)}`)
94
+ }
95
+
96
+ await provider.dropDatabase?.({
97
+ configuration,
98
+ databaseConfiguration: configuration.resolveDatabaseConfiguration(identifier),
99
+ identifier,
100
+ tenant
101
+ })
102
+ })
103
+ }
104
+ }