()
| 41 | const PROJECTS_SET_KEY = 'session:projects'; |
| 42 | |
| 43 | async function main() { |
| 44 | const dryRun = process.argv.includes('--dry-run'); |
| 45 | const redis = getRedisCache(); |
| 46 | |
| 47 | console.log( |
| 48 | `[migrate-sessions] starting${dryRun ? ' (DRY RUN — no writes)' : ''}` |
| 49 | ); |
| 50 | |
| 51 | const jobs = await sessionsQueue.getJobs(['delayed', 'waiting']); |
| 52 | console.log(`[migrate-sessions] found ${jobs.length} legacy session jobs`); |
| 53 | |
| 54 | const counts = { |
| 55 | migrated: 0, |
| 56 | blobMissing: 0, |
| 57 | alreadyMigrated: 0, |
| 58 | parseFailed: 0, |
| 59 | }; |
| 60 | |
| 61 | for (const job of jobs) { |
| 62 | const data = job.data as EventsQueuePayloadCreateSessionEnd | undefined; |
| 63 | const payload = data?.payload; |
| 64 | if (!payload?.projectId || !payload.deviceId || !payload.sessionId) { |
| 65 | counts.parseFailed++; |
| 66 | continue; |
| 67 | } |
| 68 | const { projectId, deviceId, sessionId } = payload; |
| 69 | |
| 70 | const existsAlready = await redis.exists(sessionKey(projectId, deviceId)); |
| 71 | if (existsAlready) { |
| 72 | counts.alreadyMigrated++; |
| 73 | continue; |
| 74 | } |
| 75 | |
| 76 | const blob = await redis.get(`session:${sessionId}`); |
| 77 | if (!blob) { |
| 78 | counts.blobMissing++; |
| 79 | continue; |
| 80 | } |
| 81 | |
| 82 | const session = getSafeJson<IClickhouseSession>(blob); |
| 83 | if (!session) { |
| 84 | counts.parseFailed++; |
| 85 | continue; |
| 86 | } |
| 87 | |
| 88 | const nowMs = Date.now(); |
| 89 | |
| 90 | if (dryRun) { |
| 91 | counts.migrated++; |
| 92 | continue; |
| 93 | } |
| 94 | |
| 95 | const multi = redis.multi(); |
| 96 | multi.set(sessionKey(projectId, deviceId), blob); |
| 97 | multi.zadd(wallclockSetKey(projectId), nowMs.toString(), deviceId); |
| 98 | multi.sadd(PROJECTS_SET_KEY, projectId); |
| 99 | if (session.profile_id && session.profile_id !== deviceId) { |
| 100 | multi.set(profileIndexKey(projectId, session.profile_id), deviceId); |
no test coverage detected