File size: 2,201 Bytes
8d88d9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type { Migration } from ".";
import { collections } from "$lib/server/database";
import { ObjectId, type WithId } from "mongodb";
import type { Conversation } from "$lib/types/Conversation";
import {
	MessageUpdateType,
	MessageWebSearchUpdateType,
	type MessageUpdate,
} from "$lib/types/MessageUpdate";
import type { Message } from "$lib/types/Message";
import { logger } from "$lib/server/logger";

// -----------

/** Converts the old message update to the new schema */
function convertMessageUpdate(message: Message, update: MessageUpdate): MessageUpdate | null {
	try {
		// trim final websearch update, and sources update

		if (update.type === "webSearch") {
			if (update.subtype === MessageWebSearchUpdateType.Sources) {
				return {
					type: MessageUpdateType.WebSearch,
					subtype: MessageWebSearchUpdateType.Sources,
					message: update.message,
					sources: update.sources.map(({ link, title }) => ({ link, title })),
				};
			} else if (update.subtype === MessageWebSearchUpdateType.Finished) {
				return {
					type: MessageUpdateType.WebSearch,
					subtype: MessageWebSearchUpdateType.Finished,
				};
			}
		}

		return update;
	} catch (error) {
		logger.error(error, "Error converting message update during migration. Skipping it..");
		return null;
	}
}

const trimMessageUpdates: Migration = {
	_id: new ObjectId("000000000000000000000006"),
	name: "Trim message updates to reduce stored size",
	up: async () => {
		const allConversations = collections.conversations.find({});

		let conversation: WithId<Pick<Conversation, "messages">> | null = null;
		while ((conversation = await allConversations.tryNext())) {
			const messages = conversation.messages.map((message) => {
				// Convert all of the existing updates to the new schema
				const updates = message.updates
					?.map((update) => convertMessageUpdate(message, update))
					.filter((update): update is MessageUpdate => Boolean(update));

				return { ...message, updates };
			});

			// Set the new messages array
			await collections.conversations.updateOne({ _id: conversation._id }, { $set: { messages } });
		}

		return true;
	},
	runEveryTime: false,
};

export default trimMessageUpdates;