-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmigrate-user-ids.ts
More file actions
156 lines (131 loc) · 4 KB
/
migrate-user-ids.ts
File metadata and controls
156 lines (131 loc) · 4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import 'dotenv/config';
import { MongoClient } from 'mongodb';
type CliOptions = {
dryRun: boolean;
keepBackup: boolean;
confirm: boolean;
};
function parseArgs(): CliOptions {
return {
dryRun: process.argv.includes('--dry-run'),
keepBackup: process.argv.includes('--keep-backup'),
confirm: process.argv.includes('--confirm'),
};
}
function requireSafeExecutionGuards(options: CliOptions) {
if (options.dryRun) return;
const maintenanceMode = process.env.USER_ID_MIGRATION_MAINTENANCE_MODE;
if (maintenanceMode !== 'true') {
throw new Error('USER_ID_MIGRATION_MAINTENANCE_MODE=true is required for apply mode');
}
if (!options.confirm) {
throw new Error('Missing --confirm for apply mode');
}
}
async function verifyReferences(db: any) {
const users = db.collection('users');
const thirdParties = db.collection('thirdparties');
const sessions = db.collection('sessions');
const userIds = await users.distinct('_id');
const danglingThirdParty = await thirdParties.countDocuments({
uid: { $exists: true, $nin: userIds },
});
const danglingSessions = await sessions.countDocuments({
$or: [{ source: null }, { source: { $exists: false } }],
subject: { $nin: userIds },
});
const danglingInviter = await users.countDocuments({
inviter: { $exists: true, $nin: userIds },
});
return {
danglingThirdParty,
danglingSessions,
danglingInviter,
ok: danglingThirdParty === 0 && danglingSessions === 0 && danglingInviter === 0,
};
}
async function main() {
const options = parseArgs();
requireSafeExecutionGuards(options);
const mongoUrl = process.env.MONGO_URL;
if (!mongoUrl) {
throw new Error('MONGO_URL is required');
}
const client = new MongoClient(mongoUrl);
await client.connect();
try {
const db = client.db();
const users = db.collection('users');
const totalUsers = await users.countDocuments();
const duplicateTargetIds = await users
.aggregate([
{
$project: {
targetId: {
$cond: [{ $eq: [{ $type: '$_id' }, 'objectId'] }, { $toString: '$_id' }, '$_id'],
},
},
},
{ $group: { _id: '$targetId', count: { $sum: 1 } } },
{ $match: { count: { $gt: 1 } } },
])
.toArray();
if (duplicateTargetIds.length > 0) {
throw new Error(`Duplicate target ids detected: ${duplicateTargetIds.length}`);
}
if (options.dryRun) {
console.log(JSON.stringify({ totalUsers, mode: 'dry-run', ok: true }, null, 2));
return;
}
const timestamp = Date.now();
const temporaryCollectionName = `users_string_id_tmp_${timestamp}`;
const backupCollectionName = `users_backup_${timestamp}`;
await users
.aggregate([
{
$addFields: {
_id: {
$cond: [{ $eq: [{ $type: '$_id' }, 'objectId'] }, { $toString: '$_id' }, '$_id'],
},
},
},
{ $out: temporaryCollectionName },
])
.toArray();
const temporaryCollection = db.collection(temporaryCollectionName);
const migratedCount = await temporaryCollection.countDocuments();
if (migratedCount !== totalUsers) {
throw new Error(`Migrated user count mismatch: ${migratedCount} !== ${totalUsers}`);
}
await users.rename(backupCollectionName);
await temporaryCollection.rename('users');
const integrity = await verifyReferences(db);
if (!integrity.ok) {
throw new Error(`Reference integrity check failed: ${JSON.stringify(integrity)}`);
}
if (!options.keepBackup) {
await db.collection(backupCollectionName).drop();
}
console.log(
JSON.stringify(
{
totalUsers,
migratedCount,
mode: 'apply',
keepBackup: options.keepBackup,
backupCollectionName,
integrity,
ok: true,
},
null,
2
)
);
} finally {
await client.close();
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});