forked from CherryHQ/cherry-studio-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopicService.ts
More file actions
1411 lines (1232 loc) Β· 42 KB
/
TopicService.ts
File metadata and controls
1411 lines (1232 loc) Β· 42 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
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* TopicService - Unified topic management service with optimistic updates
*
* Design Principles:
* 1. Singleton Pattern - Global unique instance with shared cache
* 2. Current Topic Cache - Cache only the active topic to minimize memory
* 3. Type Safety - Full generic support with automatic type inference
* 4. Observer Pattern - Integrated with React's useSyncExternalStore
* 5. Optimistic Updates - Immediate UI response with background persistence
*
* Architecture:
* ```
* React Components
* β useCurrentTopic / useTopic
* React Hooks (useSyncExternalStore)
* β subscribe / getSnapshot
* TopicService (This File)
* β’ Current Topic Cache (single Topic object)
* β’ Subscription Management (Map<topicId, Set<callback>>)
* β’ Request Queue (Concurrency Control)
* β’ Error Handling + Logging
* β
* topicDatabase β SQLite
* ```
*
* @example Basic Usage
* ```typescript
* // Get current topic
* const currentTopic = topicService.getCurrentTopic()
*
* // Create new topic (optimistic)
* const newTopic = await topicService.createTopic(assistant)
*
* // Subscribe to current topic changes
* const unsubscribe = topicService.subscribeCurrentTopic(() => {
* console.log('Current topic changed!')
* })
* ```
*/
import { topicDatabase } from '@database'
import { t } from 'i18next'
import { loggerService } from '@/services/LoggerService'
import { preferenceService } from '@/services/PreferenceService'
import type { Assistant, Topic } from '@/types/assistant'
import { uuid } from '@/utils'
const logger = loggerService.withContext('TopicService')
/**
* Unsubscribe function returned by subscribe methods
*/
type UnsubscribeFunction = () => void
/**
* TopicService - Singleton service for managing topics with optimistic updates
*/
export class TopicService {
// ==================== Singleton ====================
private static instance: TopicService
private constructor() {
logger.debug('TopicService instance created')
this.initializeCurrentTopic()
}
/**
* Get the singleton instance of TopicService
*/
public static getInstance(): TopicService {
if (!TopicService.instance) {
TopicService.instance = new TopicService()
}
return TopicService.instance
}
// ==================== Core Storage ====================
/**
* Cache for the current active topic
* Always kept in sync with preference 'topic.current_id'
*/
private currentTopicCache: Topic | null = null
/**
* LRU Cache for recently accessed topics
* Max size: 5 topics (in addition to current topic)
*
* Structure: Map<topicId, Topic>
* When cache size exceeds limit, oldest entry is removed
*/
private topicCache = new Map<string, Topic>()
/**
* Maximum number of topics to cache (excluding current topic)
*/
private readonly MAX_CACHE_SIZE = 5
/**
* Access order tracking for LRU eviction
* Most recently accessed at the end
*/
private accessOrder: string[] = []
/**
* Flag indicating if the current topic is being loaded
*/
private isLoadingCurrentTopic = false
/**
* Promise for ongoing current topic load operation
* Prevents duplicate concurrent loads of current topic
*/
private currentTopicLoadPromise: Promise<Topic | null> | null = null
/**
* Promise for ongoing load operations per topic
* Key: topicId, Value: Promise
*/
private loadPromises = new Map<string, Promise<Topic | null>>()
/**
* Cache for all topics (Map for O(1) lookup by ID)
* Key: topic ID
* Value: Topic object
*/
private allTopicsCache = new Map<string, Topic>()
/**
* Timestamp when all topics were last loaded from database
* Used for TTL-based cache invalidation
*/
private allTopicsCacheTimestamp: number | null = null
/**
* Cache time-to-live in milliseconds (5 minutes)
* After this duration, cache is considered stale
*/
private readonly CACHE_TTL = 5 * 60 * 1000
/**
* Flag indicating if all topics are being loaded
*/
private isLoadingAllTopics = false
/**
* Promise for ongoing load all topics operation
* Prevents duplicate concurrent loads
*/
private loadAllTopicsPromise: Promise<Topic[]> | null = null
// ==================== Subscription System ====================
/**
* Subscribers for current topic changes
* These are notified when the current topic changes
*/
private currentTopicSubscribers = new Set<() => void>()
/**
* Subscribers for specific topic changes
* Key: topicId
* Value: Set of callback functions
*/
private topicSubscribers = new Map<string, Set<() => void>>()
/**
* Global subscribers that listen to all topic changes
*/
private globalSubscribers = new Set<() => void>()
/**
* Subscribers for all topics list changes
* These are notified when the topics list changes (create/update/delete)
* Used by useTopics() hook
*/
private allTopicsSubscribers = new Set<() => void>()
// ==================== Concurrency Control ====================
/**
* Update queue to ensure sequential writes for each topic
* Prevents race conditions when the same topic is updated multiple times rapidly
*
* Key: topicId
* Value: Promise of the ongoing update operation
*/
private updateQueue = new Map<string, Promise<void>>()
// ==================== Initialization ====================
/**
* Initialize current topic from preference
* Called during service construction
*/
private async initializeCurrentTopic(): Promise<void> {
try {
const currentTopicId = preferenceService.getCached('topic.current_id')
if (currentTopicId) {
// Load current topic from database
const topic = await topicDatabase.getTopicById(currentTopicId)
if (topic) {
this.currentTopicCache = topic
logger.debug(`Initialized current topic: ${topic.id}`)
}
}
} catch (error) {
logger.error('Failed to initialize current topic:', error as Error)
}
}
// ==================== Public API: Current Topic ====================
/**
* Get the current active topic (synchronous)
*
* Returns the cached current topic immediately.
* If not cached, returns null.
*
* @returns The current topic or null
*/
public getCurrentTopic(): Topic | null {
return this.currentTopicCache
}
/**
* Get the current active topic (async)
*
* Loads from database if not cached.
*
* @returns Promise resolving to the current topic or null
*/
public async getCurrentTopicAsync(): Promise<Topic | null> {
// Return cached value if available
if (this.currentTopicCache) {
return this.currentTopicCache
}
// If already loading, wait for the ongoing load
if (this.isLoadingCurrentTopic && this.currentTopicLoadPromise) {
return await this.currentTopicLoadPromise
}
// Load from database
this.isLoadingCurrentTopic = true
this.currentTopicLoadPromise = this.loadCurrentTopicFromDatabase()
try {
const topic = await this.currentTopicLoadPromise
return topic
} finally {
this.isLoadingCurrentTopic = false
this.currentTopicLoadPromise = null
}
}
/**
* Switch to a different topic (optimistic)
*
* Updates UI immediately, then persists to preference store.
* Automatically moves the old current topic to LRU cache.
* Uses LRU cache when available to avoid database queries.
*
* @param topicId - The topic ID to switch to
*/
public async switchToTopic(topicId: string): Promise<void> {
try {
// Load topic using getTopic() which uses LRU cache
const topic = await this.getTopic(topicId)
if (!topic) {
throw new Error(`Topic with ID ${topicId} not found`)
}
// Save old topic for rollback and LRU caching
const oldTopic = this.currentTopicCache
// Remove new topic from LRU cache (it will become current topic)
if (this.topicCache.has(topicId)) {
this.topicCache.delete(topicId)
const index = this.accessOrder.indexOf(topicId)
if (index > -1) {
this.accessOrder.splice(index, 1)
}
logger.debug(`Removed new current topic from LRU cache: ${topicId}`)
}
// Optimistic update: update cache immediately
this.currentTopicCache = topic
// Move old current topic to LRU cache (if exists and different from new topic)
if (oldTopic && oldTopic.id !== topicId) {
this.addToCache(oldTopic.id, oldTopic)
logger.debug(`Moved previous current topic to LRU cache: ${oldTopic.id}`)
}
// Notify subscribers (UI updates immediately)
this.notifyCurrentTopicSubscribers()
try {
// Persist to preference store
await preferenceService.set('topic.current_id', topicId)
logger.info(`Switched to topic: ${topicId}`)
} catch (error) {
// Rollback on failure
logger.error('Failed to switch topic, rolling back:', error as Error)
this.currentTopicCache = oldTopic
// Rollback LRU cache changes
if (oldTopic && oldTopic.id !== topicId) {
this.topicCache.delete(oldTopic.id)
const index = this.accessOrder.indexOf(oldTopic.id)
if (index > -1) {
this.accessOrder.splice(index, 1)
}
}
this.notifyCurrentTopicSubscribers()
throw error
}
} catch (error) {
logger.error('Failed to switch topic:', error as Error)
throw error
}
}
// ==================== Public API: CRUD Operations ====================
/**
* Create a new topic (optimistic)
*
* Creates topic immediately in memory, then persists to database.
*
* @param assistant - The assistant for this topic
* @returns The created topic
*/
public async createTopic(assistant: Assistant): Promise<Topic> {
const newTopic: Topic = {
id: uuid(),
assistantId: assistant.id,
name: t('topics.new_topic'),
createdAt: Date.now(),
updatedAt: Date.now()
}
logger.info('Creating new topic (optimistic):', newTopic.id)
// Optimistic: return immediately
// Background: save to database
this.performTopicCreate(newTopic).catch(error => {
logger.error('Failed to persist new topic:', error as Error)
// Note: We don't rollback here because the topic has already been returned
// The UI has already updated. Consider implementing a retry mechanism.
})
return newTopic
}
/**
* Update a topic (optimistic)
*
* Updates immediately in cache if it's the current topic, then persists.
*
* @param topicId - The topic ID to update
* @param updates - Partial topic data to update
*/
public async updateTopic(topicId: string, updates: Partial<Omit<Topic, 'id'>>): Promise<void> {
// Wait for any ongoing update to the same topic
const previousUpdate = this.updateQueue.get(topicId)
if (previousUpdate) {
await previousUpdate
}
// Execute current update
const currentUpdate = this.performTopicUpdate(topicId, updates)
this.updateQueue.set(topicId, currentUpdate)
try {
await currentUpdate
} finally {
// Clean up queue
if (this.updateQueue.get(topicId) === currentUpdate) {
this.updateQueue.delete(topicId)
}
}
}
/**
* Rename a topic (optimistic)
*
* Convenience method for updating topic name.
*
* @param topicId - The topic ID to rename
* @param newName - The new name
*/
public async renameTopic(topicId: string, newName: string): Promise<void> {
await this.updateTopic(topicId, {
name: newName.trim(),
updatedAt: Date.now()
})
logger.info('Renamed topic:', topicId, newName)
}
/**
* Delete a topic (optimistic)
*
* Removes from cache if it's the current topic, then deletes from database.
*
* @param topicId - The topic ID to delete
*/
public async deleteTopic(topicId: string): Promise<void> {
logger.info('Deleting topic (optimistic):', topicId)
// If deleting current topic, clear cache
const isCurrentTopic = this.currentTopicCache?.id === topicId
const oldTopic = isCurrentTopic ? this.currentTopicCache : null
const oldCachedTopic = this.allTopicsCache.get(topicId)
if (isCurrentTopic) {
this.currentTopicCache = null
this.notifyCurrentTopicSubscribers()
}
// Remove from allTopicsCache if it exists
if (this.allTopicsCache.has(topicId)) {
this.allTopicsCache.delete(topicId)
logger.verbose(`Removed topic from cache: ${topicId}`)
}
try {
// Delete from database
await topicDatabase.deleteTopicById(topicId)
// Notify topic-specific subscribers
this.notifyTopicSubscribers(topicId)
this.notifyGlobalSubscribers()
this.notifyAllTopicsSubscribers()
logger.info('Topic deleted successfully:', topicId)
} catch (error) {
// Rollback if failed
if (isCurrentTopic && oldTopic) {
logger.error('Failed to delete topic, rolling back:', error as Error)
this.currentTopicCache = oldTopic
this.notifyCurrentTopicSubscribers()
}
// Rollback cache
if (oldCachedTopic) {
this.allTopicsCache.set(topicId, oldCachedTopic)
}
throw error
}
}
// ==================== Public API: Query Operations ====================
/**
* Get a topic by ID with LRU caching (async)
*
* This method implements smart caching:
* 1. Check if it's the current topic β return from currentTopicCache
* 2. Check LRU cache β return if cached
* 3. Load from database β cache and return
*
* @param topicId - The topic ID
* @returns Promise resolving to the topic or null
*/
public async getTopic(topicId: string): Promise<Topic | null> {
// 1. Check if it's the current topic
if (this.currentTopicCache?.id === topicId) {
logger.verbose(`Returning current topic from cache: ${topicId}`)
return this.currentTopicCache
}
// 2. Check LRU cache
if (this.topicCache.has(topicId)) {
logger.verbose(`LRU cache hit for topic: ${topicId}`)
const topic = this.topicCache.get(topicId)!
this.updateAccessOrder(topicId)
return topic
}
// 3. Check if already loading
if (this.loadPromises.has(topicId)) {
logger.verbose(`Waiting for ongoing load: ${topicId}`)
return await this.loadPromises.get(topicId)!
}
// 4. Load from database
logger.debug(`Loading topic from database: ${topicId}`)
const loadPromise = this.loadTopicFromDatabase(topicId)
this.loadPromises.set(topicId, loadPromise)
try {
const topic = await loadPromise
return topic
} finally {
this.loadPromises.delete(topicId)
}
}
/**
* Get a topic by ID synchronously (from cache only)
*
* Returns immediately from cache. Returns null if not cached.
*
* @param topicId - The topic ID
* @returns The cached topic or null
*/
public getTopicCached(topicId: string): Topic | null {
// Check current topic
if (this.currentTopicCache?.id === topicId) {
return this.currentTopicCache
}
// Check LRU cache
if (this.topicCache.has(topicId)) {
const topic = this.topicCache.get(topicId)!
this.updateAccessOrder(topicId)
return topic
}
return null
}
/**
* Get the newest topic
*
* @returns The newest topic or null
*/
public async getNewestTopic(): Promise<Topic | null> {
const topic = await topicDatabase.getNewestTopic()
return topic ?? null
}
/**
* Get a topic by ID (alias for getTopic, for backward compatibility)
*
* @param topicId - The topic ID
* @returns The topic or null
* @deprecated Use getTopic() instead
*/
public async getTopicById(topicId: string): Promise<Topic | null> {
return await this.getTopic(topicId)
}
/**
* Get all topics
*
* @returns Array of all topics
*/
public async getTopics(): Promise<Topic[]> {
return await topicDatabase.getTopics()
}
/**
* Get topics by assistant ID
*
* @param assistantId - The assistant ID
* @returns Array of topics for the assistant
*/
public async getTopicsByAssistantId(assistantId: string): Promise<Topic[]> {
return await topicDatabase.getTopicsByAssistantId(assistantId)
}
/**
* Check if a topic is owned by a specific assistant
*
* @param assistantId - The assistant ID
* @param topicId - The topic ID to check
* @returns True if the topic belongs to the assistant
*/
public async isTopicOwnedByAssistant(assistantId: string, topicId: string): Promise<boolean> {
return await topicDatabase.isTopicOwnedByAssistant(assistantId, topicId)
}
/**
* Delete all topics owned by a specific assistant (optimistic)
*
* Removes topics from cache and database. If current topic is deleted,
* it will be cleared from the cache.
*
* @param assistantId - The assistant ID whose topics should be deleted
*/
public async deleteTopicsByAssistantId(assistantId: string): Promise<void> {
logger.info('Deleting all topics for assistant (optimistic):', assistantId)
// Check if current topic belongs to this assistant
const isCurrentTopicAffected =
this.currentTopicCache && (await this.isTopicOwnedByAssistant(assistantId, this.currentTopicCache.id))
const oldCurrentTopic = isCurrentTopicAffected ? this.currentTopicCache : null
// Get all topics for this assistant for cache cleanup
const affectedTopics = await topicDatabase.getTopicsByAssistantId(assistantId)
const affectedTopicIds = new Set(affectedTopics.map(t => t.id))
// Optimistically update cache
if (isCurrentTopicAffected) {
this.currentTopicCache = null
this.notifyCurrentTopicSubscribers()
}
// Remove affected topics from LRU cache
affectedTopicIds.forEach(topicId => {
if (this.topicCache.has(topicId)) {
this.topicCache.delete(topicId)
const index = this.accessOrder.indexOf(topicId)
if (index > -1) {
this.accessOrder.splice(index, 1)
}
}
})
// Remove affected topics from all topics cache
affectedTopicIds.forEach(topicId => {
if (this.allTopicsCache.has(topicId)) {
this.allTopicsCache.delete(topicId)
}
})
try {
// Delete from database
await topicDatabase.deleteTopicsByAssistantId(assistantId)
// Notify subscribers for all affected topics
affectedTopicIds.forEach(topicId => {
this.notifyTopicSubscribers(topicId)
})
this.notifyGlobalSubscribers()
this.notifyAllTopicsSubscribers()
logger.info(`Deleted ${affectedTopicIds.size} topics for assistant: ${assistantId}`)
} catch (error) {
// Rollback on failure
logger.error('Failed to delete topics by assistant, rolling back:', error as Error)
if (isCurrentTopicAffected && oldCurrentTopic) {
this.currentTopicCache = oldCurrentTopic
this.notifyCurrentTopicSubscribers()
}
// Note: We can't easily rollback LRU and allTopicsCache without re-fetching
// This is acceptable since the operation failed at database level
throw error
}
}
// ==================== Public API: Cache Operations ====================
/**
* Get all topics with caching
*
* Loads from cache if available and not stale, otherwise loads from database.
* This is the main method for loading all topics with automatic caching.
*
* @param forceRefresh - Force reload from database even if cache is valid
* @returns Promise resolving to array of all topics
*
* @example
* ```typescript
* const topics = await topicService.getAllTopics()
* ```
*/
public async getAllTopics(forceRefresh = false): Promise<Topic[]> {
// Check if cache is valid
const isCacheValid =
!forceRefresh &&
this.allTopicsCacheTimestamp !== null &&
Date.now() - this.allTopicsCacheTimestamp < this.CACHE_TTL &&
this.allTopicsCache.size > 0
if (isCacheValid) {
logger.verbose('Returning cached topics, cache size:', this.allTopicsCache.size)
return Array.from(this.allTopicsCache.values())
}
// If already loading, wait for ongoing load
if (this.isLoadingAllTopics && this.loadAllTopicsPromise) {
logger.verbose('Waiting for ongoing getAllTopics operation')
return await this.loadAllTopicsPromise
}
// Load from database
return await this.loadAllTopicsFromDatabase()
}
/**
* Get all topics from cache (synchronous)
*
* Returns cached topics immediately. If cache is empty, returns empty array.
* Used by React's useSyncExternalStore for synchronous snapshot.
*
* @returns Array of cached topics
*
* @example
* ```typescript
* const topics = topicService.getAllTopicsCached()
* ```
*/
public getAllTopicsCached(): Topic[] {
return Array.from(this.allTopicsCache.values())
}
/**
* Get a topic from cache by ID (synchronous)
*
* Returns the topic if it exists in cache, otherwise null.
* Does not query database.
*
* @param topicId - The topic ID to retrieve
* @returns The cached topic or null
*
* @example
* ```typescript
* const topic = topicService.getTopicFromCache('topic-123')
* ```
*/
public getTopicFromCache(topicId: string): Topic | null {
return this.allTopicsCache.get(topicId) ?? null
}
/**
* Refresh all topics cache from database
*
* Forces a reload of all topics from database, updating the cache.
* Useful for pull-to-refresh functionality.
*
* @returns Promise resolving to array of refreshed topics
*
* @example
* ```typescript
* await topicService.refreshAllTopicsCache()
* ```
*/
public async refreshAllTopicsCache(): Promise<Topic[]> {
logger.info('Manually refreshing all topics cache')
return await this.getAllTopics(true)
}
/**
* Invalidate all topics cache
*
* Clears the cache and forces next access to reload from database.
* Used for logout or data reset scenarios.
*/
public invalidateCache(): void {
this.allTopicsCache.clear()
this.allTopicsCacheTimestamp = null
logger.info('All topics cache invalidated')
this.notifyAllTopicsSubscribers()
}
/**
* Clear caches and reset loading state
*/
public resetState(): void {
this.currentTopicCache = null
this.topicCache.clear()
this.accessOrder = []
this.isLoadingCurrentTopic = false
this.currentTopicLoadPromise = null
this.loadPromises.clear()
this.allTopicsCache.clear()
this.allTopicsCacheTimestamp = null
this.isLoadingAllTopics = false
this.loadAllTopicsPromise = null
this.updateQueue.clear()
logger.info('TopicService state reset')
}
// ==================== Public API: Subscription ====================
/**
* Subscribe to current topic changes
*
* The callback is invoked whenever the current topic changes.
*
* @param callback - Function to call when current topic changes
* @returns Unsubscribe function
*/
public subscribeCurrentTopic(callback: () => void): UnsubscribeFunction {
this.currentTopicSubscribers.add(callback)
logger.verbose(`Added current topic subscriber, total: ${this.currentTopicSubscribers.size}`)
return () => {
this.currentTopicSubscribers.delete(callback)
logger.verbose(`Removed current topic subscriber, remaining: ${this.currentTopicSubscribers.size}`)
}
}
/**
* Subscribe to changes for a specific topic
*
* @param topicId - The topic ID to watch
* @param callback - Function to call when the topic changes
* @returns Unsubscribe function
*/
public subscribeTopic(topicId: string, callback: () => void): UnsubscribeFunction {
if (!this.topicSubscribers.has(topicId)) {
this.topicSubscribers.set(topicId, new Set())
}
const subscribers = this.topicSubscribers.get(topicId)!
subscribers.add(callback)
logger.verbose(`Added subscriber for topic ${topicId}, total: ${subscribers.size}`)
return () => {
subscribers.delete(callback)
// Clean up empty subscriber sets
if (subscribers.size === 0) {
this.topicSubscribers.delete(topicId)
logger.verbose(`Removed last subscriber for topic ${topicId}, cleaned up`)
} else {
logger.verbose(`Removed subscriber for topic ${topicId}, remaining: ${subscribers.size}`)
}
}
}
/**
* Subscribe to all topic changes
*
* @param callback - Function to call when any topic changes
* @returns Unsubscribe function
*/
public subscribeAll(callback: () => void): UnsubscribeFunction {
this.globalSubscribers.add(callback)
logger.verbose(`Added global subscriber, total: ${this.globalSubscribers.size}`)
return () => {
this.globalSubscribers.delete(callback)
logger.verbose(`Removed global subscriber, remaining: ${this.globalSubscribers.size}`)
}
}
/**
* Subscribe to all topics list changes
*
* The callback is invoked whenever the topics list changes (create/update/delete).
* Used by useTopics() hook with useSyncExternalStore.
*
* @param callback - Function to call when topics list changes
* @returns Unsubscribe function
*
* @example
* ```typescript
* const unsubscribe = topicService.subscribeAllTopics(() => {
* console.log('Topics list updated!')
* })
* ```
*/
public subscribeAllTopics(callback: () => void): UnsubscribeFunction {
this.allTopicsSubscribers.add(callback)
logger.verbose(`Added all topics subscriber, total: ${this.allTopicsSubscribers.size}`)
return () => {
this.allTopicsSubscribers.delete(callback)
logger.verbose(`Removed all topics subscriber, remaining: ${this.allTopicsSubscribers.size}`)
}
}
/**
* Subscribe to changes for a specific topic from cache
*
* Similar to subscribeTopic(), but specifically designed for cache-based subscriptions.
* Used by useTopic(id) hook when reading from cache instead of database.
*
* @param topicId - The topic ID to watch
* @param callback - Function to call when the topic changes in cache
* @returns Unsubscribe function
*
* @example
* ```typescript
* const unsubscribe = topicService.subscribeTopicFromCache('topic-123', () => {
* console.log('Topic updated in cache!')
* })
* ```
*/
public subscribeTopicFromCache(topicId: string, callback: () => void): UnsubscribeFunction {
// Reuse the existing topicSubscribers infrastructure
return this.subscribeTopic(topicId, callback)
}
// ==================== Private Methods: Database Operations ====================
/**
* Load current topic from database
*/
private async loadCurrentTopicFromDatabase(): Promise<Topic | null> {
try {
const currentTopicId = await preferenceService.get('topic.current_id')
if (!currentTopicId) {
logger.debug('No current topic ID in preferences')
return null
}
const topic = await topicDatabase.getTopicById(currentTopicId)
if (topic) {
this.currentTopicCache = topic
logger.debug(`Loaded current topic from database: ${topic.id}`)
return topic
} else {
logger.warn(`Current topic ID ${currentTopicId} not found in database`)
return null
}
} catch (error) {
logger.error('Failed to load current topic from database:', error as Error)
return null
}
}
/**
* Load a topic from database and add to LRU cache
*/
private async loadTopicFromDatabase(topicId: string): Promise<Topic | null> {
try {
const topic = await topicDatabase.getTopicById(topicId)
if (topic) {
// Add to LRU cache
this.addToCache(topicId, topic)
logger.debug(`Loaded topic from database and cached: ${topicId}`)
return topic
} else {
logger.warn(`Topic ${topicId} not found in database`)
return null
}
} catch (error) {
logger.error(`Failed to load topic ${topicId} from database:`, error as Error)
return null
}
}
/**
* Load all topics from database and update cache
*
* This method is called when cache is invalid or forced refresh is requested.
* It prevents duplicate concurrent loads using a promise flag.
*/
private async loadAllTopicsFromDatabase(): Promise<Topic[]> {
// If already loading, wait for the ongoing operation
if (this.isLoadingAllTopics && this.loadAllTopicsPromise) {
logger.verbose('Waiting for ongoing loadAllTopics operation')
return await this.loadAllTopicsPromise
}
// Start loading
this.isLoadingAllTopics = true
this.loadAllTopicsPromise = (async () => {
try {
logger.info('Loading all topics from database')
const topics = await topicDatabase.getTopics()
// Update cache
this.allTopicsCache.clear()
topics.forEach(topic => {
this.allTopicsCache.set(topic.id, topic)
})
// Update timestamp
this.allTopicsCacheTimestamp = Date.now()
logger.info(`Loaded ${topics.length} topics into cache`)
// Notify subscribers
this.notifyAllTopicsSubscribers()
return topics
} catch (error) {
logger.error('Failed to load all topics from database:', error as Error)
throw error
} finally {
this.isLoadingAllTopics = false
this.loadAllTopicsPromise = null
}
})()
return await this.loadAllTopicsPromise
}
/**
* Perform topic creation with error handling
*/
private async performTopicCreate(topic: Topic): Promise<void> {
try {
await topicDatabase.upsertTopics([topic])
logger.debug(`Topic created successfully: ${topic.id}`)
// Update cache if it exists
if (this.allTopicsCache.size > 0 || this.allTopicsCacheTimestamp !== null) {
this.allTopicsCache.set(topic.id, topic)
logger.verbose(`Added new topic to cache: ${topic.id}`)