aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/client/sync/crdt/types.ts
blob: 1dfae1a75c28be783c0bc6be584edf2ae2f9f5cb (plain)
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/**
 * Automerge CRDT Document Type Definitions
 *
 * This module defines Automerge document types for CRDT-based sync.
 * Each entity type has a corresponding Automerge document type that wraps
 * the entity data in an LWW (Last-Write-Wins) Register pattern.
 *
 * Design decisions:
 * - LWW Register for text fields: Simple and predictable conflict resolution
 * - Each entity is stored as a separate Automerge document
 * - Documents are keyed by entity ID
 */

import type { CardStateType, FieldTypeType, RatingType } from "../../db/index";

/**
 * Base CRDT metadata for all documents
 * Used for tracking document state and sync information
 */
export interface CrdtMetadata {
	/** Entity ID (same as the entity's primary key) */
	entityId: string;
	/** Timestamp of last local modification */
	lastModified: number;
	/** Whether the entity has been soft-deleted */
	deleted: boolean;
}

/**
 * CRDT document type for Deck entities
 * Wraps deck data in an Automerge-compatible structure
 */
export interface CrdtDeckDocument {
	meta: CrdtMetadata;
	data: {
		userId: string;
		name: string;
		description: string | null;
		newCardsPerDay: number;
		createdAt: number; // Unix timestamp in ms
		deletedAt: number | null;
	};
}

/**
 * CRDT document type for NoteType entities
 * Wraps note type data in an Automerge-compatible structure
 */
export interface CrdtNoteTypeDocument {
	meta: CrdtMetadata;
	data: {
		userId: string;
		name: string;
		frontTemplate: string;
		backTemplate: string;
		isReversible: boolean;
		createdAt: number;
		deletedAt: number | null;
	};
}

/**
 * CRDT document type for NoteFieldType entities
 * Wraps note field type data in an Automerge-compatible structure
 */
export interface CrdtNoteFieldTypeDocument {
	meta: CrdtMetadata;
	data: {
		noteTypeId: string;
		name: string;
		order: number;
		fieldType: FieldTypeType;
		createdAt: number;
		deletedAt: number | null;
	};
}

/**
 * CRDT document type for Note entities
 * Wraps note data in an Automerge-compatible structure
 */
export interface CrdtNoteDocument {
	meta: CrdtMetadata;
	data: {
		deckId: string;
		noteTypeId: string;
		createdAt: number;
		deletedAt: number | null;
	};
}

/**
 * CRDT document type for NoteFieldValue entities
 * Wraps note field value data in an Automerge-compatible structure
 */
export interface CrdtNoteFieldValueDocument {
	meta: CrdtMetadata;
	data: {
		noteId: string;
		noteFieldTypeId: string;
		value: string;
		createdAt: number;
	};
}

/**
 * CRDT document type for Card entities
 * Wraps card data including FSRS scheduling state
 */
export interface CrdtCardDocument {
	meta: CrdtMetadata;
	data: {
		deckId: string;
		noteId: string;
		isReversed: boolean;
		front: string;
		back: string;

		// FSRS fields
		state: CardStateType;
		due: number; // Unix timestamp in ms
		stability: number;
		difficulty: number;
		elapsedDays: number;
		scheduledDays: number;
		reps: number;
		lapses: number;
		lastReview: number | null;

		createdAt: number;
		deletedAt: number | null;
	};
}

/**
 * CRDT document type for ReviewLog entities
 * ReviewLogs are append-only (no conflicts), but we use CRDT for consistency
 */
export interface CrdtReviewLogDocument {
	meta: CrdtMetadata;
	data: {
		cardId: string;
		userId: string;
		rating: RatingType;
		state: CardStateType;
		scheduledDays: number;
		elapsedDays: number;
		reviewedAt: number;
		durationMs: number | null;
	};
}

/**
 * Union type of all CRDT document types
 */
export type CrdtDocument =
	| CrdtDeckDocument
	| CrdtNoteTypeDocument
	| CrdtNoteFieldTypeDocument
	| CrdtNoteDocument
	| CrdtNoteFieldValueDocument
	| CrdtCardDocument
	| CrdtReviewLogDocument;

/**
 * Entity type identifiers for CRDT documents
 */
export const CrdtEntityType = {
	Deck: "deck",
	NoteType: "noteType",
	NoteFieldType: "noteFieldType",
	Note: "note",
	NoteFieldValue: "noteFieldValue",
	Card: "card",
	ReviewLog: "reviewLog",
} as const;

export type CrdtEntityTypeValue =
	(typeof CrdtEntityType)[keyof typeof CrdtEntityType];

/**
 * Map entity types to their CRDT document types
 */
export interface CrdtDocumentMap {
	deck: CrdtDeckDocument;
	noteType: CrdtNoteTypeDocument;
	noteFieldType: CrdtNoteFieldTypeDocument;
	note: CrdtNoteDocument;
	noteFieldValue: CrdtNoteFieldValueDocument;
	card: CrdtCardDocument;
	reviewLog: CrdtReviewLogDocument;
}

/**
 * Document ID format for Automerge documents
 * Format: `{entityType}:{entityId}`
 */
export interface DocumentId {
	entityType: CrdtEntityTypeValue;
	entityId: string;
}

/**
 * Create a document ID string from entity type and ID
 */
export function createDocumentId(
	entityType: CrdtEntityTypeValue,
	entityId: string,
): string {
	return `${entityType}:${entityId}`;
}

/**
 * Parse a document ID string into entity type and ID
 */
export function parseDocumentId(documentId: string): DocumentId | null {
	const [entityType, entityId] = documentId.split(":");
	if (!entityType || !entityId) {
		return null;
	}

	const validTypes = Object.values(CrdtEntityType);
	if (!validTypes.includes(entityType as CrdtEntityTypeValue)) {
		return null;
	}

	return {
		entityType: entityType as CrdtEntityTypeValue,
		entityId,
	};
}

/**
 * Create CRDT metadata for a new document
 */
export function createCrdtMetadata(entityId: string): CrdtMetadata {
	return {
		entityId,
		lastModified: Date.now(),
		deleted: false,
	};
}

/**
 * Create CRDT metadata for a deleted document
 */
export function createDeletedCrdtMetadata(entityId: string): CrdtMetadata {
	return {
		entityId,
		lastModified: Date.now(),
		deleted: true,
	};
}