|
| 1 | +import { Injectable, Logger } from '@nestjs/common'; |
| 2 | +import { InjectModel } from '@nestjs/mongoose'; |
| 3 | +import { Model } from 'mongoose'; |
| 4 | + |
| 5 | +import { |
| 6 | + Song, |
| 7 | + SONG_MIGRATION_REGISTRY, |
| 8 | + SONG_PENDING_QUERY_CLAUSES, |
| 9 | + buildPendingQuery, |
| 10 | + isFullyMigrated, |
| 11 | + migrateDocument, |
| 12 | + type MigrationRegistry, |
| 13 | +} from '@nbw/database'; |
| 14 | + |
| 15 | +export interface MigrationBatchResult { |
| 16 | + collection: string; |
| 17 | + matched: number; |
| 18 | + migrated: number; |
| 19 | + errors: string[]; |
| 20 | +} |
| 21 | + |
| 22 | +export interface MigrationStatus { |
| 23 | + collection: string; |
| 24 | + currentVersion: number; |
| 25 | + pendingCount: number; |
| 26 | +} |
| 27 | + |
| 28 | +const DEFAULT_BATCH_SIZE = 500; |
| 29 | + |
| 30 | +@Injectable() |
| 31 | +export class MigrationService { |
| 32 | + private readonly logger = new Logger(MigrationService.name); |
| 33 | + |
| 34 | + private readonly registries = new Map<string, MigrationRegistry<object>>([ |
| 35 | + [SONG_MIGRATION_REGISTRY.collection, SONG_MIGRATION_REGISTRY], |
| 36 | + ]); |
| 37 | + |
| 38 | + constructor( |
| 39 | + @InjectModel(Song.name) |
| 40 | + private readonly songModel: Model<Song>, |
| 41 | + ) {} |
| 42 | + |
| 43 | + async getMigrationStatus(collection: string): Promise<MigrationStatus> { |
| 44 | + const registry = this.getRegistry(collection); |
| 45 | + const model = this.getModel(collection); |
| 46 | + const pendingQuery = this.buildRegistryPendingQuery(collection); |
| 47 | + |
| 48 | + const pendingCount = await model.countDocuments(pendingQuery); |
| 49 | + |
| 50 | + return { |
| 51 | + collection, |
| 52 | + currentVersion: registry.currentVersion, |
| 53 | + pendingCount, |
| 54 | + }; |
| 55 | + } |
| 56 | + |
| 57 | + async runAllPendingMigrations(options?: { |
| 58 | + batchSize?: number; |
| 59 | + }): Promise<MigrationBatchResult[]> { |
| 60 | + const results: MigrationBatchResult[] = []; |
| 61 | + |
| 62 | + for (const collection of this.registries.keys()) { |
| 63 | + results.push(await this.runBulkMigration(collection, options)); |
| 64 | + } |
| 65 | + |
| 66 | + return results; |
| 67 | + } |
| 68 | + |
| 69 | + async runBulkMigration( |
| 70 | + collection: string, |
| 71 | + options?: { batchSize?: number }, |
| 72 | + ): Promise<MigrationBatchResult> { |
| 73 | + const registry = this.getRegistry(collection); |
| 74 | + const model = this.getModel(collection); |
| 75 | + const batchSize = options?.batchSize ?? DEFAULT_BATCH_SIZE; |
| 76 | + const pendingQuery = this.buildRegistryPendingQuery(collection); |
| 77 | + |
| 78 | + const matched = await model.countDocuments(pendingQuery); |
| 79 | + |
| 80 | + if (matched === 0) { |
| 81 | + this.logger.log( |
| 82 | + `No pending migrations for ${collection} (current version ${registry.currentVersion})`, |
| 83 | + ); |
| 84 | + |
| 85 | + return { |
| 86 | + collection, |
| 87 | + matched: 0, |
| 88 | + migrated: 0, |
| 89 | + errors: [], |
| 90 | + }; |
| 91 | + } |
| 92 | + |
| 93 | + this.logger.log( |
| 94 | + `Migrating ${matched} ${collection} document(s) to schema version ${registry.currentVersion}`, |
| 95 | + ); |
| 96 | + |
| 97 | + let migrated = 0; |
| 98 | + const errors: string[] = []; |
| 99 | + let lastId: unknown; |
| 100 | + |
| 101 | + while (true) { |
| 102 | + const query = lastId |
| 103 | + ? { ...pendingQuery, _id: { $gt: lastId } } |
| 104 | + : pendingQuery; |
| 105 | + |
| 106 | + const batch = await model |
| 107 | + .find(query) |
| 108 | + .sort({ _id: 1 }) |
| 109 | + .limit(batchSize) |
| 110 | + .exec(); |
| 111 | + |
| 112 | + if (batch.length === 0) { |
| 113 | + break; |
| 114 | + } |
| 115 | + |
| 116 | + for (const doc of batch) { |
| 117 | + try { |
| 118 | + if (isFullyMigrated(registry, doc)) { |
| 119 | + lastId = doc._id; |
| 120 | + continue; |
| 121 | + } |
| 122 | + |
| 123 | + const updated = migrateDocument(registry, doc.toObject()); |
| 124 | + |
| 125 | + doc.set(updated); |
| 126 | + await doc.save(); |
| 127 | + migrated++; |
| 128 | + } catch (error) { |
| 129 | + const message = |
| 130 | + error instanceof Error ? error.message : String(error); |
| 131 | + errors.push(`${doc._id}: ${message}`); |
| 132 | + } |
| 133 | + |
| 134 | + lastId = doc._id; |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + if (errors.length > 0) { |
| 139 | + throw new Error( |
| 140 | + `Migration failed for ${collection}: ${errors.join('; ')}`, |
| 141 | + ); |
| 142 | + } |
| 143 | + |
| 144 | + this.logger.log( |
| 145 | + `Migrated ${migrated}/${matched} ${collection} document(s)`, |
| 146 | + ); |
| 147 | + |
| 148 | + return { |
| 149 | + collection, |
| 150 | + matched, |
| 151 | + migrated, |
| 152 | + errors, |
| 153 | + }; |
| 154 | + } |
| 155 | + |
| 156 | + private getRegistry(collection: string): MigrationRegistry<object> { |
| 157 | + const registry = this.registries.get(collection); |
| 158 | + |
| 159 | + if (!registry) { |
| 160 | + throw new Error(`No migration registry registered for ${collection}`); |
| 161 | + } |
| 162 | + |
| 163 | + return registry; |
| 164 | + } |
| 165 | + |
| 166 | + private getModel(collection: string): Model<Song> { |
| 167 | + if (collection === SONG_MIGRATION_REGISTRY.collection) { |
| 168 | + return this.songModel; |
| 169 | + } |
| 170 | + |
| 171 | + throw new Error(`No model registered for ${collection}`); |
| 172 | + } |
| 173 | + |
| 174 | + private buildRegistryPendingQuery(collection: string) { |
| 175 | + if (collection === SONG_MIGRATION_REGISTRY.collection) { |
| 176 | + return buildPendingQuery( |
| 177 | + SONG_MIGRATION_REGISTRY, |
| 178 | + SONG_PENDING_QUERY_CLAUSES, |
| 179 | + ); |
| 180 | + } |
| 181 | + |
| 182 | + return buildPendingQuery(this.getRegistry(collection)); |
| 183 | + } |
| 184 | +} |
0 commit comments