@vue-skuilder/db 0.2.36 → 0.2.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/index.cjs +91 -70
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/navigators/generators/prescribed.mjs +29 -11
- package/dist/core/navigators/generators/prescribed.mjs.map +1 -1
- package/dist/core/versionStamps.mjs +1 -1
- package/dist/impl/common/BaseUserDB.mjs +14 -2
- package/dist/impl/common/BaseUserDB.mjs.map +1 -1
- package/dist/impl/couch/CourseSyncService.mjs +88 -10
- package/dist/impl/couch/CourseSyncService.mjs.map +1 -1
- package/dist/impl/couch/PouchDataLayerProvider.mjs +16 -1
- package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -1
- package/dist/impl/couch/courseAPI.mjs +24 -10
- package/dist/impl/couch/courseAPI.mjs.map +1 -1
- package/dist/impl/couch/courseDB.mjs +15 -9
- package/dist/impl/couch/courseDB.mjs.map +1 -1
- package/dist/impl/couch/index.cjs +163 -62
- package/dist/impl/couch/index.cjs.map +1 -1
- package/dist/impl/couch/index.d.ts +22 -1
- package/dist/impl/couch/index.mjs +20 -3
- package/dist/impl/couch/index.mjs.map +1 -1
- package/dist/impl/static/index.cjs +39 -15
- package/dist/impl/static/index.cjs.map +1 -1
- package/dist/index.cjs +202 -92
- package/dist/index.cjs.map +1 -1
- package/package.json +3 -3
- package/src/core/navigators/generators/prescribed.ts +42 -16
- package/src/impl/common/BaseUserDB.ts +15 -2
- package/src/impl/couch/CourseSyncService.ts +130 -20
- package/src/impl/couch/PouchDataLayerProvider.ts +14 -1
- package/src/impl/couch/courseAPI.ts +26 -12
- package/src/impl/couch/courseDB.ts +20 -12
- package/src/impl/couch/index.ts +16 -5
- package/tests/impl/courseSync.test.ts +139 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CourseSyncService.mjs","names":["pouch"],"sources":["../../../src/impl/couch/CourseSyncService.ts"],"sourcesContent":["import pouch from './pouchdb-setup';\nimport { getCourseDB } from '.';\nimport { logger } from '../../util/logger';\nimport type { CourseConfig } from '@vue-skuilder/common';\n\n// ============================================================================\n// COURSE SYNC SERVICE\n// ============================================================================\n//\n// Manages client-side PouchDB replicas of course databases.\n//\n// Courses opt in to local sync via CourseConfig.localSync.enabled. When\n// enabled, the service performs a one-shot replication from remote CouchDB\n// to a local PouchDB on first visit, then incremental sync on subsequent\n// visits. Pipeline scoring, tag hydration, and card lookup then run against\n// the local replica — eliminating network round trips from the study-session\n// hot path.\n//\n// Read/write split:\n// Local DB = read-only snapshot (pipeline, filters, card lookup)\n// Remote DB = all writes (ELO updates, tag mutations, admin ops)\n//\n// This avoids propagating per-interaction ELO write noise to every syncing\n// client. Each client's local snapshot refreshes on the next page load.\n//\n// Live replication is intentionally NOT supported. The remote course DB\n// receives high-frequency ELO updates from all concurrent users — live\n// sync would cause constant re-indexing of local PouchDB views.\n//\n// ============================================================================\n\n/**\n * Sync state for a single course database.\n */\nexport type CourseSyncState =\n | 'not-started'\n | 'checking-config'\n | 'syncing'\n | 'warming-views'\n | 'ready'\n | 'disabled'\n | 'error';\n\n/**\n * Detailed sync status for observability.\n */\nexport interface CourseSyncStatus {\n state: CourseSyncState;\n /** Number of documents replicated (set after sync completes) */\n docsReplicated?: number;\n /** Total replication time in ms */\n syncTimeMs?: number;\n /** View warming time in ms */\n viewWarmTimeMs?: number;\n /** Error message if state is 'error' */\n error?: string;\n}\n\n/**\n * Internal tracking entry per course.\n */\ninterface SyncEntry {\n localDB: PouchDB.Database | null;\n status: CourseSyncStatus;\n /** Promise that resolves when sync is complete (or rejects on failure) */\n readyPromise: Promise<void> | null;\n}\n\n/**\n * Service that manages local PouchDB replicas of course databases.\n *\n * Usage:\n * ```typescript\n * const syncService = CourseSyncService.getInstance();\n *\n * // Trigger sync (typically on app load / pre-session)\n * await syncService.ensureSynced(courseId);\n *\n * // Get local DB for reads (returns null if sync not ready/enabled)\n * const localDB = syncService.getLocalDB(courseId);\n * ```\n *\n * The service is a singleton — course sync state is shared across the app.\n */\n/**\n * Tuning knobs for one-shot remote→local replication.\n * Defaults are chosen for one-shot snapshot replication of bounded course\n * corpora (text/JSON docs, no large attachments). PouchDB's built-in\n * defaults (100/10) target live continuous sync — too conservative for\n * cold-load UX on a course of a few thousand docs.\n *\n * Apps with smaller/larger corpora can override via\n * `initializeDataLayer({ options: { courseSync: { replication: {...} } } })`.\n */\nexport interface ReplicationOptions {\n /** Docs per `_bulk_get` HTTP request. Higher = fewer roundtrips. */\n batchSize?: number;\n /** Concurrent batches in flight. */\n batchesLimit?: number;\n}\n\nconst DEFAULT_REPLICATION: Required<ReplicationOptions> = {\n batchSize: 1000,\n batchesLimit: 5,\n};\n\nexport class CourseSyncService {\n private static instance: CourseSyncService | null = null;\n\n private entries: Map<string, SyncEntry> = new Map();\n private replicationOptions: Required<ReplicationOptions> = DEFAULT_REPLICATION;\n\n private constructor() {}\n\n static getInstance(): CourseSyncService {\n if (!CourseSyncService.instance) {\n CourseSyncService.instance = new CourseSyncService();\n }\n return CourseSyncService.instance;\n }\n\n /**\n * Apply replication tuning. Typically called once from `initializeDataLayer`.\n * Partial overrides merge with defaults.\n */\n configure(opts: { replication?: ReplicationOptions }): void {\n if (opts.replication) {\n this.replicationOptions = {\n ...DEFAULT_REPLICATION,\n ...opts.replication,\n };\n logger.info(\n `[CourseSyncService] Replication configured: ` +\n `batch_size=${this.replicationOptions.batchSize}, ` +\n `batches_limit=${this.replicationOptions.batchesLimit}`\n );\n }\n }\n\n /**\n * Reset the singleton (for testing).\n */\n static resetInstance(): void {\n if (CourseSyncService.instance) {\n // Close all local DBs\n for (const [, entry] of CourseSyncService.instance.entries) {\n if (entry.localDB) {\n entry.localDB.close().catch(() => {});\n }\n }\n CourseSyncService.instance.entries.clear();\n }\n CourseSyncService.instance = null;\n }\n\n // --------------------------------------------------------------------------\n // Public API\n // --------------------------------------------------------------------------\n\n /**\n * Ensure a course's local replica is synced.\n *\n * On first call for a course:\n * 1. Fetches CourseConfig from remote to check localSync.enabled\n * 2. If enabled, performs one-shot replication remote → local\n * 3. Pre-warms PouchDB view indices (elo, getTags)\n *\n * On subsequent calls: returns immediately if already synced, or awaits\n * the in-flight sync if one is in progress.\n *\n * Safe to call multiple times — concurrent calls coalesce to one sync.\n *\n * @param courseId - The course to sync\n * @param forceEnabled - Skip the CourseConfig check and sync regardless.\n * Useful when the caller already knows local sync is desired (e.g.,\n * LettersPractice hardcodes this).\n */\n async ensureSynced(courseId: string, forceEnabled?: boolean): Promise<void> {\n const existing = this.entries.get(courseId);\n\n // Already synced — but check if the remote DB has been recreated\n // (e.g., after a dev reseed). The seed script writes a `db-epoch`\n // doc; if the remote epoch differs from our local copy, the local\n // replica is stale and must be destroyed before re-syncing.\n if (existing?.status.state === 'ready' && existing.localDB) {\n const stale = await this.isLocalEpochStale(courseId, existing.localDB);\n if (!stale) {\n return;\n }\n logger.info(\n `[CourseSyncService] Remote DB epoch changed for course ${courseId} — destroying stale local replica`\n );\n try {\n await existing.localDB.destroy();\n } catch {\n // Ignore cleanup errors\n }\n existing.localDB = null;\n existing.readyPromise = null;\n // Fall through to start a fresh sync\n }\n\n // Already disabled\n if (existing?.status.state === 'disabled') {\n return;\n }\n\n // Sync in flight — coalesce\n if (existing?.readyPromise) {\n return existing.readyPromise;\n }\n\n // Start a new sync\n const entry: SyncEntry = {\n localDB: null,\n status: { state: 'not-started' },\n readyPromise: null,\n };\n this.entries.set(courseId, entry);\n\n entry.readyPromise = this.performSync(courseId, entry, forceEnabled);\n return entry.readyPromise;\n }\n\n /**\n * Get the local PouchDB for a course, or null if not available.\n *\n * Returns null when:\n * - Local sync is not enabled for this course\n * - Sync has not been triggered yet\n * - Sync is still in progress\n * - Sync failed\n */\n getLocalDB(courseId: string): PouchDB.Database | null {\n const entry = this.entries.get(courseId);\n if (entry?.status.state === 'ready' && entry.localDB) {\n return entry.localDB;\n }\n return null;\n }\n\n /**\n * Check whether a course has a ready local replica.\n */\n isReady(courseId: string): boolean {\n return this.entries.get(courseId)?.status.state === 'ready';\n }\n\n /**\n * Get detailed sync status for a course.\n */\n getStatus(courseId: string): CourseSyncStatus {\n return (\n this.entries.get(courseId)?.status ?? { state: 'not-started' }\n );\n }\n\n // --------------------------------------------------------------------------\n // Internal\n // --------------------------------------------------------------------------\n\n private async performSync(\n courseId: string,\n entry: SyncEntry,\n forceEnabled?: boolean\n ): Promise<void> {\n try {\n // Step 1: Check if local sync is enabled for this course\n if (!forceEnabled) {\n entry.status = { state: 'checking-config' };\n const enabled = await this.checkLocalSyncEnabled(courseId);\n if (!enabled) {\n entry.status = { state: 'disabled' };\n entry.readyPromise = null;\n logger.debug(\n `[CourseSyncService] Local sync disabled for course ${courseId}`\n );\n return;\n }\n }\n\n // Step 2: Create local PouchDB and replicate\n entry.status = { state: 'syncing' };\n const localDBName = this.localDBName(courseId);\n let localDB = new pouch(localDBName);\n\n // Check for stale local replica before replicating. If the remote DB\n // was wiped and recreated (e.g., `yarn db:seed`), the local PouchDB\n // has documents at rev 1-oldHash while the remote has 1-newHash for\n // the same _ids. PouchDB replication treats this as a conflict rather\n // than an update, and the stale revision can win — causing partial or\n // incorrect data. Destroying the stale local DB avoids this entirely.\n const stale = await this.isLocalEpochStale(courseId, localDB);\n if (stale) {\n logger.info(\n `[CourseSyncService] Stale local DB detected for course ${courseId} — destroying before sync`\n );\n await localDB.destroy();\n localDB = new pouch(localDBName);\n }\n\n entry.localDB = localDB;\n\n const remoteDB = this.getRemoteDB(courseId);\n const syncStart = Date.now();\n\n logger.info(\n `[CourseSyncService] Starting one-shot replication for course ${courseId} ` +\n `(batch_size=${this.replicationOptions.batchSize}, ` +\n `batches_limit=${this.replicationOptions.batchesLimit})`\n );\n\n const result = await this.replicate(remoteDB, localDB);\n const syncTimeMs = Date.now() - syncStart;\n\n logger.info(\n `[CourseSyncService] Replication complete for course ${courseId}: ` +\n `${result.docs_written} docs in ${syncTimeMs}ms`\n );\n\n // Step 3: Pre-warm view indices\n entry.status = { state: 'warming-views' };\n const warmStart = Date.now();\n await this.warmViewIndices(localDB);\n const viewWarmTimeMs = Date.now() - warmStart;\n\n logger.info(\n `[CourseSyncService] View indices warmed for course ${courseId} in ${viewWarmTimeMs}ms`\n );\n\n // Done\n entry.status = {\n state: 'ready',\n docsReplicated: result.docs_written,\n syncTimeMs,\n viewWarmTimeMs,\n };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n logger.error(\n `[CourseSyncService] Sync failed for course ${courseId}: ${errorMsg}`\n );\n entry.status = { state: 'error', error: errorMsg };\n entry.readyPromise = null;\n\n // Clean up the local DB on failure — don't leave a partial replica\n if (entry.localDB) {\n try {\n await entry.localDB.destroy();\n } catch {\n // Ignore cleanup errors\n }\n entry.localDB = null;\n }\n }\n }\n\n /**\n * Check CourseConfig.localSync.enabled on the remote DB.\n */\n private async checkLocalSyncEnabled(courseId: string): Promise<boolean> {\n try {\n const remoteDB = this.getRemoteDB(courseId);\n const config = await remoteDB.get<CourseConfig>('CourseConfig');\n return config.localSync?.enabled === true;\n } catch (e) {\n logger.warn(\n `[CourseSyncService] Could not read CourseConfig for ${courseId}, ` +\n `assuming local sync disabled: ${e}`\n );\n return false;\n }\n }\n\n /**\n * One-shot replication from remote to local.\n */\n private replicate(\n source: PouchDB.Database,\n target: PouchDB.Database\n ): Promise<PouchDB.Replication.ReplicationResultComplete<object>> {\n return new Promise((resolve, reject) => {\n void pouch.replicate(source, target, {\n // One-shot, not live. Local is a read-only snapshot.\n batch_size: this.replicationOptions.batchSize,\n batches_limit: this.replicationOptions.batchesLimit,\n })\n .on('complete', (info) => {\n resolve(info);\n })\n .on('error', (err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Pre-warm PouchDB view indices by running a minimal query against each\n * design doc. This forces PouchDB to build the MapReduce index now\n * (during a loading phase) rather than on first pipeline query.\n */\n private async warmViewIndices(localDB: PouchDB.Database): Promise<void> {\n const viewsToWarm = ['elo', 'getTags'];\n\n for (const viewName of viewsToWarm) {\n try {\n await localDB.query(viewName, { limit: 1 });\n logger.debug(\n `[CourseSyncService] Warmed view index: ${viewName}`\n );\n } catch (e) {\n // View might not exist in this course DB — that's OK.\n // Not all courses have all design docs.\n logger.debug(\n `[CourseSyncService] Could not warm view ${viewName}: ${e}`\n );\n }\n }\n }\n\n /**\n * Check whether the local replica's `db-epoch` doc matches the remote.\n *\n * The seed script (and optionally upload-cards) writes a `db-epoch`\n * document with a numeric timestamp. If the remote epoch differs from\n * the local copy, the remote DB was recreated (e.g., `yarn db:seed`)\n * and the local PouchDB is stale.\n *\n * Returns `true` if stale (epoch mismatch or remote has epoch but local\n * doesn't). Returns `false` (not stale) if epochs match, or if the\n * remote doesn't have an epoch doc at all (backwards compat).\n */\n private async isLocalEpochStale(\n courseId: string,\n localDB: PouchDB.Database\n ): Promise<boolean> {\n try {\n const remoteDB = this.getRemoteDB(courseId);\n const remoteEpoch = await remoteDB.get<{ epoch: number }>('db-epoch');\n\n let localEpoch: { epoch: number } | null = null;\n try {\n localEpoch = await localDB.get<{ epoch: number }>('db-epoch');\n } catch {\n // Local doesn't have the epoch doc — stale\n return true;\n }\n\n return remoteEpoch.epoch !== localEpoch.epoch;\n } catch {\n // Remote doesn't have db-epoch — no epoch tracking, not stale\n return false;\n }\n }\n\n /**\n * Get a remote PouchDB handle for a course.\n */\n private getRemoteDB(courseId: string): PouchDB.Database {\n return getCourseDB(courseId);\n }\n\n /**\n * Local DB naming convention.\n */\n private localDBName(courseId: string): string {\n return `coursedb-local-${courseId}`;\n }\n}"],"mappings":";;;;;AAqGA,MAAM,sBAAoD;CACxD,WAAW;CACX,cAAc;CACf;AAED,IAAa,oBAAb,MAAa,kBAAkB;CAC7B,OAAe,WAAqC;CAEpD,0BAA0C,IAAI,KAAK;CACnD,qBAA2D;CAE3D,cAAsB;CAEtB,OAAO,cAAiC;AACtC,MAAI,CAAC,kBAAkB,SACrB,mBAAkB,WAAW,IAAI,mBAAmB;AAEtD,SAAO,kBAAkB;;;;;;CAO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;AAC5C,SAAO,kBAAkB"}
|
|
1
|
+
{"version":3,"file":"CourseSyncService.mjs","names":["pouch"],"sources":["../../../src/impl/couch/CourseSyncService.ts"],"sourcesContent":["import pouch from './pouchdb-setup';\nimport { getCourseDB } from '.';\nimport { logger } from '../../util/logger';\nimport type { CourseConfig } from '@vue-skuilder/common';\n\n// ============================================================================\n// COURSE SYNC SERVICE\n// ============================================================================\n//\n// Manages client-side PouchDB replicas of course databases.\n//\n// Courses opt in to local sync via CourseConfig.localSync.enabled. When\n// enabled, the service performs a one-shot replication from remote CouchDB\n// to a local PouchDB on first visit, then incremental sync on subsequent\n// visits. Pipeline scoring, tag hydration, and card lookup then run against\n// the local replica — eliminating network round trips from the study-session\n// hot path.\n//\n// Read/write split:\n// Local DB = read-only snapshot (pipeline, filters, card lookup)\n// Remote DB = all writes (ELO updates, tag mutations, admin ops)\n//\n// This avoids propagating per-interaction ELO write noise to every syncing\n// client. Each client's local snapshot refreshes on the next page load.\n//\n// A replica that completed a sync on an earlier page load carries a\n// `_local/` marker, and is handed out as ready immediately; its refresh\n// (epoch check, incremental pull, view warming) runs in the background, into\n// the same DB. Sessions may therefore start on the previous visit's data and\n// catch up seconds later. If that refresh finds the remote DB recreated (an\n// epoch change), the replica is NOT destroyed under running readers: the\n// marker is dropped, this page keeps the outdated copy, and the next page\n// load rebuilds it from scratch (the path a device without a replica takes).\n//\n// Live replication is intentionally NOT supported. The remote course DB\n// receives high-frequency ELO updates from all concurrent users — live\n// sync would cause constant re-indexing of local PouchDB views.\n//\n// ============================================================================\n\n/**\n * Sync state for a single course database.\n */\nexport type CourseSyncState =\n | 'not-started'\n | 'checking-config'\n | 'syncing'\n | 'warming-views'\n | 'ready'\n | 'disabled'\n | 'error';\n\n/**\n * Written into the local replica when a sync completes. `_local/` docs don't\n * replicate, so it describes this device's copy.\n */\nconst SYNC_MARKER_ID = '_local/sk-course-sync-complete';\n\n/**\n * Detailed sync status for observability.\n */\nexport interface CourseSyncStatus {\n state: CourseSyncState;\n /** Number of documents replicated (set after sync completes) */\n docsReplicated?: number;\n /** Total replication time in ms */\n syncTimeMs?: number;\n /** View warming time in ms */\n viewWarmTimeMs?: number;\n /** Error message if state is 'error' */\n error?: string;\n}\n\n/**\n * Internal tracking entry per course.\n */\ninterface SyncEntry {\n localDB: PouchDB.Database | null;\n status: CourseSyncStatus;\n /** Promise that resolves when sync is complete (or rejects on failure) */\n readyPromise: Promise<void> | null;\n}\n\n/**\n * Service that manages local PouchDB replicas of course databases.\n *\n * Usage:\n * ```typescript\n * const syncService = CourseSyncService.getInstance();\n *\n * // Trigger sync (typically on app load / pre-session)\n * await syncService.ensureSynced(courseId);\n *\n * // Get local DB for reads (returns null if sync not ready/enabled)\n * const localDB = syncService.getLocalDB(courseId);\n * ```\n *\n * The service is a singleton — course sync state is shared across the app.\n */\n/**\n * Tuning knobs for one-shot remote→local replication.\n * Defaults are chosen for one-shot snapshot replication of bounded course\n * corpora (text/JSON docs, no large attachments). PouchDB's built-in\n * defaults (100/10) target live continuous sync — too conservative for\n * cold-load UX on a course of a few thousand docs.\n *\n * Apps with smaller/larger corpora can override via\n * `initializeDataLayer({ options: { courseSync: { replication: {...} } } })`.\n */\nexport interface ReplicationOptions {\n /** Docs per `_bulk_get` HTTP request. Higher = fewer roundtrips. */\n batchSize?: number;\n /** Concurrent batches in flight. */\n batchesLimit?: number;\n}\n\nconst DEFAULT_REPLICATION: Required<ReplicationOptions> = {\n batchSize: 1000,\n batchesLimit: 5,\n};\n\nexport class CourseSyncService {\n private static instance: CourseSyncService | null = null;\n\n private entries: Map<string, SyncEntry> = new Map();\n private replicationOptions: Required<ReplicationOptions> = DEFAULT_REPLICATION;\n\n private constructor() {}\n\n static getInstance(): CourseSyncService {\n if (!CourseSyncService.instance) {\n CourseSyncService.instance = new CourseSyncService();\n }\n return CourseSyncService.instance;\n }\n\n /**\n * Apply replication tuning. Typically called once from `initializeDataLayer`.\n * Partial overrides merge with defaults.\n */\n configure(opts: { replication?: ReplicationOptions }): void {\n if (opts.replication) {\n this.replicationOptions = {\n ...DEFAULT_REPLICATION,\n ...opts.replication,\n };\n logger.info(\n `[CourseSyncService] Replication configured: ` +\n `batch_size=${this.replicationOptions.batchSize}, ` +\n `batches_limit=${this.replicationOptions.batchesLimit}`\n );\n }\n }\n\n /**\n * Reset the singleton (for testing).\n */\n static resetInstance(): void {\n if (CourseSyncService.instance) {\n // Close all local DBs\n for (const [, entry] of CourseSyncService.instance.entries) {\n if (entry.localDB) {\n entry.localDB.close().catch(() => {});\n }\n }\n CourseSyncService.instance.entries.clear();\n }\n CourseSyncService.instance = null;\n }\n\n // --------------------------------------------------------------------------\n // Public API\n // --------------------------------------------------------------------------\n\n /**\n * Ensure a course's local replica is synced.\n *\n * On first call for a course:\n * 1. Fetches CourseConfig from remote to check localSync.enabled\n * 2. If enabled, performs one-shot replication remote → local\n * 3. Pre-warms PouchDB view indices (elo, getTags)\n *\n * On subsequent calls: returns immediately if already synced, or awaits\n * the in-flight sync if one is in progress.\n *\n * Safe to call multiple times — concurrent calls coalesce to one sync.\n *\n * @param courseId - The course to sync\n * @param forceEnabled - Skip the CourseConfig check and sync regardless.\n * Useful when the caller already knows local sync is desired (e.g.,\n * LettersPractice hardcodes this).\n */\n async ensureSynced(courseId: string, forceEnabled?: boolean): Promise<void> {\n const existing = this.entries.get(courseId);\n\n // Ready on this page load. Its epoch was checked on the way (by\n // performSync, or by the background refresh, which keeps an outdated\n // replica rather than destroy it under running sessions).\n if (existing?.status.state === 'ready' && existing.localDB) {\n return;\n }\n\n // Already disabled\n if (existing?.status.state === 'disabled') {\n return;\n }\n\n // Sync in flight — coalesce\n if (existing?.readyPromise) {\n return existing.readyPromise;\n }\n\n // Start a new sync\n const entry: SyncEntry = {\n localDB: null,\n status: { state: 'not-started' },\n readyPromise: null,\n };\n this.entries.set(courseId, entry);\n\n entry.readyPromise = this.startSync(courseId, entry, forceEnabled);\n return entry.readyPromise;\n }\n\n /**\n * A replica completed on an earlier page load is ready now, refreshed in the\n * background; anything else goes through a full performSync.\n */\n private async startSync(\n courseId: string,\n entry: SyncEntry,\n forceEnabled?: boolean\n ): Promise<void> {\n const localDB = new pouch(this.localDBName(courseId));\n if (await this.hasSyncMarker(localDB)) {\n entry.localDB = localDB;\n entry.status = { state: 'ready' };\n entry.readyPromise = null;\n logger.info(\n `[CourseSyncService] Using this device's replica of course ${courseId}; refreshing in the background`\n );\n void this.refreshInBackground(courseId, entry, forceEnabled);\n return;\n }\n return this.performSync(courseId, entry, forceEnabled);\n }\n\n /**\n * Bring a ready replica up to date without taking it away from readers.\n * Failures leave it ready (and outdated).\n */\n private async refreshInBackground(\n courseId: string,\n entry: SyncEntry,\n forceEnabled?: boolean\n ): Promise<void> {\n const localDB = entry.localDB!;\n try {\n if (!forceEnabled && !(await this.checkLocalSyncEnabled(courseId))) {\n await this.clearSyncMarker(localDB);\n logger.info(\n `[CourseSyncService] Local sync no longer enabled for course ${courseId}; replica kept for this page only`\n );\n return;\n }\n\n if (await this.isLocalEpochStale(courseId, localDB)) {\n await this.clearSyncMarker(localDB);\n logger.info(\n `[CourseSyncService] Remote DB recreated for course ${courseId}: keeping the outdated replica ` +\n `for this page; it is rebuilt on the next page load`\n );\n return;\n }\n\n const start = Date.now();\n const result = await this.replicate(this.getRemoteDB(courseId), localDB);\n const syncTimeMs = Date.now() - start;\n const warmStart = Date.now();\n await this.warmViewIndices(localDB);\n const viewWarmTimeMs = Date.now() - warmStart;\n await this.writeSyncMarker(localDB);\n entry.status = {\n state: 'ready',\n docsReplicated: result.docs_written,\n syncTimeMs,\n viewWarmTimeMs,\n };\n logger.info(\n `[CourseSyncService] Background refresh of course ${courseId}: ` +\n `${result.docs_written} docs in ${syncTimeMs}ms, views ${viewWarmTimeMs}ms`\n );\n } catch (e) {\n logger.warn(\n `[CourseSyncService] Background refresh of course ${courseId} failed; replica kept as is: ${e}`\n );\n }\n }\n\n private async hasSyncMarker(localDB: PouchDB.Database): Promise<boolean> {\n try {\n await localDB.get(SYNC_MARKER_ID);\n return true;\n } catch {\n return false;\n }\n }\n\n private async writeSyncMarker(localDB: PouchDB.Database): Promise<void> {\n try {\n let _rev: string | undefined;\n try {\n _rev = (await localDB.get(SYNC_MARKER_ID))._rev;\n } catch {\n // First completion on this device.\n }\n await localDB.put({ _id: SYNC_MARKER_ID, _rev, completedAt: new Date().toISOString() });\n } catch (e) {\n // Costs the next page load the full-sync path, not correctness.\n logger.warn(`[CourseSyncService] Could not write sync marker: ${e}`);\n }\n }\n\n private async clearSyncMarker(localDB: PouchDB.Database): Promise<void> {\n try {\n const marker = await localDB.get(SYNC_MARKER_ID);\n await localDB.remove(marker);\n } catch {\n // Absent already.\n }\n }\n\n /**\n * Get the local PouchDB for a course, or null if not available.\n *\n * Returns null when:\n * - Local sync is not enabled for this course\n * - Sync has not been triggered yet\n * - Sync is still in progress\n * - Sync failed\n */\n getLocalDB(courseId: string): PouchDB.Database | null {\n const entry = this.entries.get(courseId);\n if (entry?.status.state === 'ready' && entry.localDB) {\n return entry.localDB;\n }\n return null;\n }\n\n /**\n * Check whether a course has a ready local replica.\n */\n isReady(courseId: string): boolean {\n return this.entries.get(courseId)?.status.state === 'ready';\n }\n\n /**\n * Get detailed sync status for a course.\n */\n getStatus(courseId: string): CourseSyncStatus {\n return (\n this.entries.get(courseId)?.status ?? { state: 'not-started' }\n );\n }\n\n // --------------------------------------------------------------------------\n // Internal\n // --------------------------------------------------------------------------\n\n private async performSync(\n courseId: string,\n entry: SyncEntry,\n forceEnabled?: boolean\n ): Promise<void> {\n try {\n // Step 1: Check if local sync is enabled for this course\n if (!forceEnabled) {\n entry.status = { state: 'checking-config' };\n const enabled = await this.checkLocalSyncEnabled(courseId);\n if (!enabled) {\n entry.status = { state: 'disabled' };\n entry.readyPromise = null;\n logger.debug(\n `[CourseSyncService] Local sync disabled for course ${courseId}`\n );\n return;\n }\n }\n\n // Step 2: Create local PouchDB and replicate\n entry.status = { state: 'syncing' };\n const localDBName = this.localDBName(courseId);\n let localDB = new pouch(localDBName);\n\n // Check for stale local replica before replicating. If the remote DB\n // was wiped and recreated (e.g., `yarn db:seed`), the local PouchDB\n // has documents at rev 1-oldHash while the remote has 1-newHash for\n // the same _ids. PouchDB replication treats this as a conflict rather\n // than an update, and the stale revision can win — causing partial or\n // incorrect data. Destroying the stale local DB avoids this entirely.\n const stale = await this.isLocalEpochStale(courseId, localDB);\n if (stale) {\n logger.info(\n `[CourseSyncService] Stale local DB detected for course ${courseId} — destroying before sync`\n );\n await localDB.destroy();\n localDB = new pouch(localDBName);\n }\n\n entry.localDB = localDB;\n\n const remoteDB = this.getRemoteDB(courseId);\n const syncStart = Date.now();\n\n logger.info(\n `[CourseSyncService] Starting one-shot replication for course ${courseId} ` +\n `(batch_size=${this.replicationOptions.batchSize}, ` +\n `batches_limit=${this.replicationOptions.batchesLimit})`\n );\n\n const result = await this.replicate(remoteDB, localDB);\n const syncTimeMs = Date.now() - syncStart;\n\n logger.info(\n `[CourseSyncService] Replication complete for course ${courseId}: ` +\n `${result.docs_written} docs in ${syncTimeMs}ms`\n );\n\n // Step 3: Pre-warm view indices\n entry.status = { state: 'warming-views' };\n const warmStart = Date.now();\n await this.warmViewIndices(localDB);\n const viewWarmTimeMs = Date.now() - warmStart;\n\n logger.info(\n `[CourseSyncService] View indices warmed for course ${courseId} in ${viewWarmTimeMs}ms`\n );\n\n await this.writeSyncMarker(localDB);\n\n // Done\n entry.status = {\n state: 'ready',\n docsReplicated: result.docs_written,\n syncTimeMs,\n viewWarmTimeMs,\n };\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : String(e);\n logger.error(\n `[CourseSyncService] Sync failed for course ${courseId}: ${errorMsg}`\n );\n entry.status = { state: 'error', error: errorMsg };\n entry.readyPromise = null;\n\n // Clean up the local DB on failure — don't leave a partial replica\n if (entry.localDB) {\n try {\n await entry.localDB.destroy();\n } catch {\n // Ignore cleanup errors\n }\n entry.localDB = null;\n }\n }\n }\n\n /**\n * Check CourseConfig.localSync.enabled on the remote DB.\n */\n private async checkLocalSyncEnabled(courseId: string): Promise<boolean> {\n try {\n const remoteDB = this.getRemoteDB(courseId);\n const config = await remoteDB.get<CourseConfig>('CourseConfig');\n return config.localSync?.enabled === true;\n } catch (e) {\n logger.warn(\n `[CourseSyncService] Could not read CourseConfig for ${courseId}, ` +\n `assuming local sync disabled: ${e}`\n );\n return false;\n }\n }\n\n /**\n * One-shot replication from remote to local.\n */\n private replicate(\n source: PouchDB.Database,\n target: PouchDB.Database\n ): Promise<PouchDB.Replication.ReplicationResultComplete<object>> {\n return new Promise((resolve, reject) => {\n void pouch.replicate(source, target, {\n // One-shot, not live. Local is a read-only snapshot.\n batch_size: this.replicationOptions.batchSize,\n batches_limit: this.replicationOptions.batchesLimit,\n })\n .on('complete', (info) => {\n resolve(info);\n })\n .on('error', (err) => {\n reject(err);\n });\n });\n }\n\n /**\n * Pre-warm PouchDB view indices by running a minimal query against each\n * design doc. This forces PouchDB to build the MapReduce index now\n * (during a loading phase) rather than on first pipeline query.\n */\n private async warmViewIndices(localDB: PouchDB.Database): Promise<void> {\n const viewsToWarm = ['elo', 'getTags'];\n\n for (const viewName of viewsToWarm) {\n try {\n await localDB.query(viewName, { limit: 1 });\n logger.debug(\n `[CourseSyncService] Warmed view index: ${viewName}`\n );\n } catch (e) {\n // View might not exist in this course DB — that's OK.\n // Not all courses have all design docs.\n logger.debug(\n `[CourseSyncService] Could not warm view ${viewName}: ${e}`\n );\n }\n }\n }\n\n /**\n * Check whether the local replica's `db-epoch` doc matches the remote.\n *\n * The seed script (and optionally upload-cards) writes a `db-epoch`\n * document with a numeric timestamp. If the remote epoch differs from\n * the local copy, the remote DB was recreated (e.g., `yarn db:seed`)\n * and the local PouchDB is stale.\n *\n * Returns `true` if stale (epoch mismatch or remote has epoch but local\n * doesn't). Returns `false` (not stale) if epochs match, or if the\n * remote doesn't have an epoch doc at all (backwards compat).\n */\n private async isLocalEpochStale(\n courseId: string,\n localDB: PouchDB.Database\n ): Promise<boolean> {\n try {\n const remoteDB = this.getRemoteDB(courseId);\n const remoteEpoch = await remoteDB.get<{ epoch: number }>('db-epoch');\n\n let localEpoch: { epoch: number } | null = null;\n try {\n localEpoch = await localDB.get<{ epoch: number }>('db-epoch');\n } catch {\n // Local doesn't have the epoch doc — stale\n return true;\n }\n\n return remoteEpoch.epoch !== localEpoch.epoch;\n } catch {\n // Remote doesn't have db-epoch — no epoch tracking, not stale\n return false;\n }\n }\n\n /**\n * Get a remote PouchDB handle for a course.\n */\n private getRemoteDB(courseId: string): PouchDB.Database {\n return getCourseDB(courseId);\n }\n\n /**\n * Local DB naming convention.\n */\n private localDBName(courseId: string): string {\n return `coursedb-local-${courseId}`;\n }\n}"],"mappings":";;;;;;;;;AAwDA,MAAM,iBAAiB;AA4DvB,MAAM,sBAAoD;CACxD,WAAW;CACX,cAAc;CACf;AAED,IAAa,oBAAb,MAAa,kBAAkB;CAC7B,OAAe,WAAqC;CAEpD,0BAA0C,IAAI,KAAK;CACnD,qBAA2D;CAE3D,cAAsB;CAEtB,OAAO,cAAiC;AACtC,MAAI,CAAC,kBAAkB,SACrB,mBAAkB,WAAW,IAAI,mBAAmB;AAEtD,SAAO,kBAAkB;;;;;;CAO3B,UAAU,MAAkD;AAC1D,MAAI,KAAK,aAAa;AACpB,QAAK,qBAAqB;IACxB,GAAG;IACH,GAAG,KAAK;IACT;AACD,UAAO,KACL,0DACgB,KAAK,mBAAmB,UAAU,kBAC/B,KAAK,mBAAmB,eAC5C;;;;;;CAOL,OAAO,gBAAsB;AAC3B,MAAI,kBAAkB,UAAU;AAE9B,QAAK,MAAM,GAAG,UAAU,kBAAkB,SAAS,QACjD,KAAI,MAAM,QACR,OAAM,QAAQ,OAAO,CAAC,YAAY,GAAG;AAGzC,qBAAkB,SAAS,QAAQ,OAAO;;AAE5C,oBAAkB,WAAW;;;;;;;;;;;;;;;;;;;;CAyB/B,MAAM,aAAa,UAAkB,cAAuC;EAC1E,MAAM,WAAW,KAAK,QAAQ,IAAI,SAAS;AAK3C,M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AI;AAGF,WADe,MADE,KAAK,YAAY,SAAS,CACb,IAAkB,eAAe,EACjD,WAAW,YAAY;WAC9B,GAAG;AACV,UAAO,KACL,uDAAuD,SAAS,kCAC7B,IACpC;AACD,UAAO;;;;;;CAOX,UACE,QACA,QACgE;AAChE,SAAO,IAAI,SAAS,SAAS,WAAW;AACjCA,yBAAM,UAAU,QAAQ,QAAQ;IAEnC,YAAY,KAAK,mBAAmB;IACpC,eAAe,KAAK,mBAAmB;IACxC,CAAC,CACC,GAAG,aAAa,SAAS;AACxB,YAAQ,KAAK;KACb,CACD,GAAG,UAAU,QAAQ;AACpB,WAAO,IAAI;KACX;IACJ;;;;;;;CAQJ,MAAc,gBAAgB,SAA0C;AAGtE,OAAK,MAAM,YAFS,CAAC,OAAO,UAAU,CAGpC,KAAI;AACF,SAAM,QAAQ,MAAM,UAAU,EAAE,OAAO,GAAG,CAAC;AAC3C,UAAO,MACL,0CAA0C,WAC3C;WACM,GAAG;AAGV,UAAO,MACL,2CAA2C,SAAS,IAAI,IACzD;;;;;;;;;;;;;;;CAiBP,MAAc,kBACZ,UACA,SACkB;AAClB,MAAI;GAEF,MAAM,cAAc,MADH,KAAK,YAAY,SAAS,CACR,IAAuB,WAAW;GAErE,IAAI,aAAuC;AAC3C,OAAI;AACF,iBAAa,MAAM,QAAQ,IAAuB,WAAW;WACvD;AAEN,WAAO;;AAGT,UAAO,YAAY,UAAU,WAAW;UAClC;AAEN,UAAO;;;;;;CAOX,YAAoB,UAAoC;AACtD,SAAO,YAAY,SAAS;;;;;CAM9B,YAAoB,UAA0B;AAC5C,SAAO,kBAAkB"}
|
|
@@ -13,6 +13,13 @@ var CouchDataLayerProvider = class {
|
|
|
13
13
|
userDB;
|
|
14
14
|
currentUsername = "";
|
|
15
15
|
_courseIDs = [];
|
|
16
|
+
/**
|
|
17
|
+
* One CourseDB per course, so its caches (navigator, ELO pool, tags) last
|
|
18
|
+
* across sessions and card hydration. Rebuilt when the local replica it reads
|
|
19
|
+
* from changes (becomes ready, or is replaced); a session keeps the instance
|
|
20
|
+
* it started with.
|
|
21
|
+
*/
|
|
22
|
+
_courseDBs = /* @__PURE__ */ new Map();
|
|
16
23
|
constructor(coursIDs) {
|
|
17
24
|
if (coursIDs) this._courseIDs = coursIDs;
|
|
18
25
|
}
|
|
@@ -38,7 +45,15 @@ var CouchDataLayerProvider = class {
|
|
|
38
45
|
return this.userDB;
|
|
39
46
|
}
|
|
40
47
|
getCourseDB(courseId) {
|
|
41
|
-
|
|
48
|
+
const localDB = CourseSyncService.getInstance().getLocalDB(courseId);
|
|
49
|
+
const cached = this._courseDBs.get(courseId);
|
|
50
|
+
if (cached && cached.localDB === localDB) return cached.db;
|
|
51
|
+
const db = new CourseDB(courseId, async () => this.getUserDB(), localDB ?? void 0);
|
|
52
|
+
this._courseDBs.set(courseId, {
|
|
53
|
+
db,
|
|
54
|
+
localDB
|
|
55
|
+
});
|
|
56
|
+
return db;
|
|
42
57
|
}
|
|
43
58
|
/**
|
|
44
59
|
* Trigger local sync for a course. Call during app initialization or
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PouchDataLayerProvider.mjs","names":[],"sources":["../../../src/impl/couch/PouchDataLayerProvider.ts"],"sourcesContent":["// db/src/impl/couch/PouchDataLayerProvider.ts\n\nimport {\n AdminDBInterface,\n ClassroomDBInterface,\n CoursesDBInterface,\n CourseDBInterface,\n DataLayerProvider,\n UserDBInterface,\n} from '../../core/interfaces';\nimport { logger } from '../../util/logger';\nimport { initializeDataDirectory } from '../../util/dataDirectory';\n\nimport { AdminDB } from './adminDB';\nimport { StudentClassroomDB, TeacherClassroomDB } from './classroomDB';\nimport { CourseDB, CoursesDB } from './courseDB';\nimport { CourseSyncService } from './CourseSyncService';\n\nimport { BaseUser } from '../common';\nimport { CouchDBSyncStrategy } from './CouchDBSyncStrategy';\n\nexport class CouchDataLayerProvider implements DataLayerProvider {\n private initialized: boolean = false;\n private userDB!: UserDBInterface;\n private currentUsername: string = '';\n\n // the scoped list of courseIDs for a UI focused on a specific course\n // or group of courses\n private _courseIDs: string[] = [];\n\n constructor(coursIDs?: string[]) {\n if (coursIDs) {\n this._courseIDs = coursIDs;\n }\n }\n\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n // Check if we are in a Node.js environment\n const isNodeEnvironment =\n typeof process !== 'undefined' && process.versions != null && process.versions.node != null;\n\n if (isNodeEnvironment) {\n logger.info(\n 'CouchDataLayerProvider: Running in Node.js environment, creating guest UserDB for testing.'\n );\n await initializeDataDirectory();\n // In Node.js (testing) environment, create a guest user instance\n const syncStrategy = new CouchDBSyncStrategy();\n this.userDB = await BaseUser.instance(syncStrategy);\n } else {\n // Assume browser-like environment, proceed with user session logic\n // Let CouchDBSyncStrategy.getCurrentUsername() handle both logged-in and guest users\n const syncStrategy = new CouchDBSyncStrategy();\n this.userDB = await BaseUser.instance(syncStrategy);\n this.currentUsername = this.userDB.getUsername();\n logger.debug(`Current username: ${this.currentUsername}`);\n }\n\n this.initialized = true;\n }\n\n async teardown(): Promise<void> {\n // Close connections, etc.\n this.initialized = false;\n }\n\n getUserDB(): UserDBInterface {\n return this.userDB;\n }\n\n getCourseDB(courseId: string): CourseDBInterface {\n // If the CourseSyncService has a ready local replica for this course,\n // pass it to CourseDB so reads (pipeline, card hydration) run locally.\n // Writes always go to the remote DB (handled inside CourseDB).\n const localDB = CourseSyncService.getInstance().getLocalDB(courseId);\n return new CourseDB(courseId, async () => this.getUserDB(), localDB ?? undefined);\n }\n\n /**\n * Trigger local sync for a course. Call during app initialization or\n * pre-session loading for courses that opt in via CourseConfig.localSync.\n *\n * Safe to call multiple times — concurrent calls coalesce. Returns when\n * sync is complete (or immediately if already synced / disabled).\n *\n * @param courseId - The course to sync locally\n * @param forceEnabled - Skip CourseConfig check and sync regardless.\n * Use when the caller already knows local sync is desired.\n */\n async ensureCourseSynced(courseId: string, forceEnabled?: boolean): Promise<void> {\n return CourseSyncService.getInstance().ensureSynced(courseId, forceEnabled);\n }\n\n getCoursesDB(): CoursesDBInterface {\n return new CoursesDB(this._courseIDs);\n }\n\n async getClassroomDB(\n classId: string,\n type: 'student' | 'teacher'\n ): Promise<ClassroomDBInterface> {\n if (type === 'student') {\n return await StudentClassroomDB.factory(classId, this.getUserDB());\n } else {\n return await TeacherClassroomDB.factory(classId);\n }\n }\n\n getAdminDB(): AdminDBInterface {\n return new AdminDB();\n }\n\n isReadOnly(): boolean {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;AAqBA,IAAa,yBAAb,MAAiE;CAC/D,cAA+B;CAC/B;CACA,kBAAkC;CAIlC,aAA+B,EAAE;
|
|
1
|
+
{"version":3,"file":"PouchDataLayerProvider.mjs","names":[],"sources":["../../../src/impl/couch/PouchDataLayerProvider.ts"],"sourcesContent":["// db/src/impl/couch/PouchDataLayerProvider.ts\n\nimport {\n AdminDBInterface,\n ClassroomDBInterface,\n CoursesDBInterface,\n CourseDBInterface,\n DataLayerProvider,\n UserDBInterface,\n} from '../../core/interfaces';\nimport { logger } from '../../util/logger';\nimport { initializeDataDirectory } from '../../util/dataDirectory';\n\nimport { AdminDB } from './adminDB';\nimport { StudentClassroomDB, TeacherClassroomDB } from './classroomDB';\nimport { CourseDB, CoursesDB } from './courseDB';\nimport { CourseSyncService } from './CourseSyncService';\n\nimport { BaseUser } from '../common';\nimport { CouchDBSyncStrategy } from './CouchDBSyncStrategy';\n\nexport class CouchDataLayerProvider implements DataLayerProvider {\n private initialized: boolean = false;\n private userDB!: UserDBInterface;\n private currentUsername: string = '';\n\n // the scoped list of courseIDs for a UI focused on a specific course\n // or group of courses\n private _courseIDs: string[] = [];\n\n /**\n * One CourseDB per course, so its caches (navigator, ELO pool, tags) last\n * across sessions and card hydration. Rebuilt when the local replica it reads\n * from changes (becomes ready, or is replaced); a session keeps the instance\n * it started with.\n */\n private _courseDBs = new Map<string, { db: CourseDB; localDB: PouchDB.Database | null }>();\n\n constructor(coursIDs?: string[]) {\n if (coursIDs) {\n this._courseIDs = coursIDs;\n }\n }\n\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n // Check if we are in a Node.js environment\n const isNodeEnvironment =\n typeof process !== 'undefined' && process.versions != null && process.versions.node != null;\n\n if (isNodeEnvironment) {\n logger.info(\n 'CouchDataLayerProvider: Running in Node.js environment, creating guest UserDB for testing.'\n );\n await initializeDataDirectory();\n // In Node.js (testing) environment, create a guest user instance\n const syncStrategy = new CouchDBSyncStrategy();\n this.userDB = await BaseUser.instance(syncStrategy);\n } else {\n // Assume browser-like environment, proceed with user session logic\n // Let CouchDBSyncStrategy.getCurrentUsername() handle both logged-in and guest users\n const syncStrategy = new CouchDBSyncStrategy();\n this.userDB = await BaseUser.instance(syncStrategy);\n this.currentUsername = this.userDB.getUsername();\n logger.debug(`Current username: ${this.currentUsername}`);\n }\n\n this.initialized = true;\n }\n\n async teardown(): Promise<void> {\n // Close connections, etc.\n this.initialized = false;\n }\n\n getUserDB(): UserDBInterface {\n return this.userDB;\n }\n\n getCourseDB(courseId: string): CourseDBInterface {\n // If the CourseSyncService has a ready local replica for this course,\n // pass it to CourseDB so reads (pipeline, card hydration) run locally.\n // Writes always go to the remote DB (handled inside CourseDB).\n const localDB = CourseSyncService.getInstance().getLocalDB(courseId);\n const cached = this._courseDBs.get(courseId);\n if (cached && cached.localDB === localDB) return cached.db;\n\n const db = new CourseDB(courseId, async () => this.getUserDB(), localDB ?? undefined);\n this._courseDBs.set(courseId, { db, localDB });\n return db;\n }\n\n /**\n * Trigger local sync for a course. Call during app initialization or\n * pre-session loading for courses that opt in via CourseConfig.localSync.\n *\n * Safe to call multiple times — concurrent calls coalesce. Returns when\n * sync is complete (or immediately if already synced / disabled).\n *\n * @param courseId - The course to sync locally\n * @param forceEnabled - Skip CourseConfig check and sync regardless.\n * Use when the caller already knows local sync is desired.\n */\n async ensureCourseSynced(courseId: string, forceEnabled?: boolean): Promise<void> {\n return CourseSyncService.getInstance().ensureSynced(courseId, forceEnabled);\n }\n\n getCoursesDB(): CoursesDBInterface {\n return new CoursesDB(this._courseIDs);\n }\n\n async getClassroomDB(\n classId: string,\n type: 'student' | 'teacher'\n ): Promise<ClassroomDBInterface> {\n if (type === 'student') {\n return await StudentClassroomDB.factory(classId, this.getUserDB());\n } else {\n return await TeacherClassroomDB.factory(classId);\n }\n }\n\n getAdminDB(): AdminDBInterface {\n return new AdminDB();\n }\n\n isReadOnly(): boolean {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;AAqBA,IAAa,yBAAb,MAAiE;CAC/D,cAA+B;CAC/B;CACA,kBAAkC;CAIlC,aAA+B,EAAE;;;;;;;CAQjC,6BAAqB,IAAI,KAAiE;CAE1F,YAAY,UAAqB;AAC/B,MAAI,SACF,MAAK,aAAa;;CAItB,MAAM,aAA4B;AAChC,MAAI,KAAK,YAAa;AAMtB,MAFE,OAAO,YAAY,eAAe,QAAQ,YAAY,QAAQ,QAAQ,SAAS,QAAQ,MAElE;AACrB,UAAO,KACL,6FACD;AACD,SAAM,yBAAyB;GAE/B,MAAM,eAAe,IAAI,qBAAqB;AAC9C,QAAK,SAAS,MAAM,SAAS,SAAS,aAAa;SAC9C;GAGL,MAAM,eAAe,IAAI,qBAAqB;AAC9C,QAAK,SAAS,MAAM,SAAS,SAAS,aAAa;AACnD,QAAK,kBAAkB,KAAK,OAAO,aAAa;AAChD,UAAO,MAAM,qBAAqB,KAAK,kBAAkB;;AAG3D,OAAK,cAAc;;CAGrB,MAAM,WAA0B;AAE9B,OAAK,cAAc;;CAGrB,YAA6B;AAC3B,SAAO,KAAK;;CAGd,YAAY,UAAqC;EAI/C,MAAM,UAAU,kBAAkB,aAAa,CAAC,WAAW,SAAS;EACpE,MAAM,SAAS,KAAK,WAAW,IAAI,SAAS;AAC5C,MAAI,UAAU,OAAO,YAAY,QAAS,QAAO,OAAO;EAExD,MAAM,KAAK,IAAI,SAAS,UAAU,YAAY,KAAK,WAAW,EAAE,WAAW,KAAA,EAAU;AACrF,OAAK,WAAW,IAAI,UAAU;GAAE;GAAI;GAAS,CAAC;AAC9C,SAAO;;;;;;;;;;;;;CAcT,MAAM,mBAAmB,UAAkB,cAAuC;AAChF,SAAO,kBAAkB,aAAa,CAAC,aAAa,UAAU,aAAa;;CAG7E,eAAmC;AACjC,SAAO,IAAI,UAAU,KAAK,WAAW;;CAGvC,MAAM,eACJ,SACA,MAC+B;AAC/B,MAAI,SAAS,UACX,QAAO,MAAM,mBAAmB,QAAQ,SAAS,KAAK,WAAW,CAAC;MAElE,QAAO,MAAM,mBAAmB,QAAQ,QAAQ;;CAIpD,aAA+B;AAC7B,SAAO,IAAI,SAAS;;CAGtB,aAAsB;AACpB,SAAO"}
|
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import "../../_virtual/_rolldown/runtime.mjs";
|
|
2
2
|
import { logger } from "../../util/logger.mjs";
|
|
3
|
-
import { ENV } from "../../factory.mjs";
|
|
4
|
-
import pouchdb_setup_default from "./pouchdb-setup.mjs";
|
|
5
3
|
import { DocType, DocTypePrefixes } from "../../core/types/types-legacy.mjs";
|
|
6
4
|
import { CourseDB, createTag } from "./courseDB.mjs";
|
|
7
5
|
import { BaseUser } from "../common/BaseUserDB.mjs";
|
|
8
|
-
import {
|
|
6
|
+
import { getCourseDB } from "./index.mjs";
|
|
9
7
|
import { NameSpacer, blankCourseElo, prepareNote55, toCourseElo } from "@vue-skuilder/common";
|
|
10
8
|
import { v4 } from "uuid";
|
|
11
9
|
//#region src/impl/couch/courseAPI.ts
|
|
@@ -96,13 +94,33 @@ async function addCard(courseID, course, id_displayable_data, id_view, elo, tags
|
|
|
96
94
|
}
|
|
97
95
|
return card;
|
|
98
96
|
}
|
|
97
|
+
/**
|
|
98
|
+
* CourseConfig reads, cached per course for a few minutes: a study session reads
|
|
99
|
+
* it several times per pipeline run and per card. An edit made elsewhere shows
|
|
100
|
+
* up after the TTL (or a reload); writes through this client invalidate.
|
|
101
|
+
*/
|
|
102
|
+
const COURSE_CONFIG_TTL_MS = 300 * 1e3;
|
|
103
|
+
const courseConfigCache = /* @__PURE__ */ new Map();
|
|
104
|
+
function invalidateCourseConfigCache(courseID) {
|
|
105
|
+
courseConfigCache.delete(courseID);
|
|
106
|
+
}
|
|
99
107
|
async function getCredentialledCourseConfig(courseID) {
|
|
100
|
-
|
|
108
|
+
const hit = courseConfigCache.get(courseID);
|
|
109
|
+
if (hit && Date.now() - hit.at < COURSE_CONFIG_TTL_MS) return structuredClone(await hit.config);
|
|
110
|
+
const config = (async () => {
|
|
101
111
|
const ret = await getCourseDB(courseID).get("CourseConfig");
|
|
102
112
|
ret.courseID = courseID;
|
|
103
|
-
logger.
|
|
113
|
+
logger.debug(`Fetched course config for ${courseID}`);
|
|
104
114
|
return ret;
|
|
115
|
+
})();
|
|
116
|
+
courseConfigCache.set(courseID, {
|
|
117
|
+
at: Date.now(),
|
|
118
|
+
config
|
|
119
|
+
});
|
|
120
|
+
try {
|
|
121
|
+
return structuredClone(await config);
|
|
105
122
|
} catch (e) {
|
|
123
|
+
courseConfigCache.delete(courseID);
|
|
106
124
|
logger.error(`Error fetching config for ${courseID}:`, e);
|
|
107
125
|
throw e;
|
|
108
126
|
}
|
|
@@ -173,11 +191,7 @@ function getTagID(tagName) {
|
|
|
173
191
|
if (tagName.indexOf(tagPrefix) === 0) return tagName;
|
|
174
192
|
else return tagPrefix + tagName;
|
|
175
193
|
}
|
|
176
|
-
function getCourseDB(courseID) {
|
|
177
|
-
const dbName = `coursedb-${courseID}`;
|
|
178
|
-
return new pouchdb_setup_default(ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + dbName, createPouchDBConfig());
|
|
179
|
-
}
|
|
180
194
|
//#endregion
|
|
181
|
-
export { addNote55, addTagToCard, getCredentialledCourseConfig, getTagID };
|
|
195
|
+
export { addNote55, addTagToCard, getCredentialledCourseConfig, getTagID, invalidateCourseConfigCache };
|
|
182
196
|
|
|
183
197
|
//# sourceMappingURL=courseAPI.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"courseAPI.mjs","names":["uuidv4","pouch"],"sources":["../../../src/impl/couch/courseAPI.ts"],"sourcesContent":["import pouch from './pouchdb-setup';\nimport { createPouchDBConfig } from '.';\nimport { ENV } from '@db/factory';\n// import { DataShape } from '../..base-course/Interfaces/DataShape';\nimport { NameSpacer, ShapeDescriptor } from '@vue-skuilder/common';\nimport { CourseConfig, DataShape } from '@vue-skuilder/common';\nimport { CourseElo, blankCourseElo, toCourseElo } from '@vue-skuilder/common';\nimport { CourseDB, createTag } from './courseDB';\nimport { CardData, DisplayableData, DocType, Tag, DocTypePrefixes } from '../../core/types/types-legacy';\nimport { prepareNote55 } from '@vue-skuilder/common';\nimport { BaseUser } from '../common';\nimport { logger } from '@db/util/logger';\nimport { v4 as uuidv4 } from 'uuid';\n\n/**\n *\n * @param courseID id of the course (quilt) being added to\n * @param codeCourse\n * @param shape\n * @param data the datashape data - data required for this shape\n * @param author\n * @param uploads optional additional media uploads: img0, img1, ..., aud0, aud1,...\n * @returns\n */\nexport async function addNote55(\n courseID: string,\n codeCourse: string,\n shape: DataShape,\n data: unknown,\n author: string,\n tags: string[],\n uploads?: { [x: string]: PouchDB.Core.FullAttachment },\n elo: CourseElo = blankCourseElo()\n): Promise<PouchDB.Core.Response> {\n const db = getCourseDB(courseID);\n const payload = prepareNote55(courseID, codeCourse, shape, data, author, tags, uploads);\n const _id = `${DocTypePrefixes[DocType.DISPLAYABLE_DATA]}-${uuidv4()}`;\n const result = await db.put<DisplayableData>({ ...payload, _id });\n\n const dataShapeId = NameSpacer.getDataShapeString({\n course: codeCourse,\n dataShape: shape.name,\n });\n\n if (result.ok) {\n try {\n // create cards\n await createCards(courseID, dataShapeId, result.id, tags, elo, author);\n } catch (error) {\n // Handle CouchDB errors which often have a 'reason' property\n let errorMessage = 'Unknown error';\n if (error instanceof Error) {\n errorMessage = error.message;\n } else if (error && typeof error === 'object' && 'reason' in error) {\n errorMessage = error.reason as string;\n } else if (error && typeof error === 'object' && 'message' in error) {\n errorMessage = error.message as string;\n } else {\n errorMessage = String(error);\n }\n\n logger.error(`[addNote55] Failed to create cards for note ${result.id}: ${errorMessage}`);\n // Add info to result to indicate card creation failed\n (result as any).cardCreationFailed = true;\n (result as any).cardCreationError = errorMessage;\n }\n } else {\n logger.error(`[addNote55] Error adding note. Result: ${JSON.stringify(result)}`);\n }\n\n return result;\n}\n\nasync function createCards(\n courseID: string,\n datashapeID: PouchDB.Core.DocumentId,\n noteID: PouchDB.Core.DocumentId,\n tags: string[],\n elo: CourseElo = blankCourseElo(),\n author: string\n): Promise<void> {\n const cfg = await getCredentialledCourseConfig(courseID);\n const dsDescriptor = NameSpacer.getDataShapeDescriptor(datashapeID);\n let questionViewTypes: string[] = [];\n\n for (const ds of cfg.dataShapes) {\n if (ds.name === datashapeID) {\n questionViewTypes = ds.questionTypes;\n }\n }\n\n if (questionViewTypes.length === 0) {\n const errorMsg = `No questionViewTypes found for datashapeID: ${datashapeID} in course config. Cards cannot be created.`;\n logger.error(errorMsg);\n throw new Error(errorMsg);\n }\n\n for (const questionView of questionViewTypes) {\n await createCard(questionView, courseID, dsDescriptor, noteID, tags, elo, author);\n }\n}\n\nasync function createCard(\n questionViewName: string,\n courseID: string,\n dsDescriptor: ShapeDescriptor,\n noteID: string,\n tags: string[],\n elo: CourseElo = blankCourseElo(),\n author: string\n): Promise<void> {\n const qDescriptor = NameSpacer.getQuestionDescriptor(questionViewName);\n const cfg = await getCredentialledCourseConfig(courseID);\n\n for (const rQ of cfg.questionTypes) {\n if (rQ.name === questionViewName) {\n for (const view of rQ.viewList) {\n await addCard(\n courseID,\n dsDescriptor.course,\n [noteID],\n NameSpacer.getViewString({\n course: qDescriptor.course,\n questionType: qDescriptor.questionType,\n view,\n }),\n elo,\n tags,\n author\n );\n }\n }\n }\n}\n\n/**\n *\n * Adds a card to the DB. This function is called\n * as a side effect of adding either a View or\n * DisplayableData item.\n * @param course The name of the course that the card belongs to\n * @param id_displayable_data C/PouchDB ID of the data used to hydrate the view\n * @param id_view C/PouchDB ID of the view used to display the card\n *\n * @package\n */\nasync function addCard(\n courseID: string,\n course: string,\n id_displayable_data: PouchDB.Core.DocumentId[],\n id_view: PouchDB.Core.DocumentId,\n elo: CourseElo,\n tags: string[],\n author: string\n): Promise<PouchDB.Core.Response> {\n const db = getCourseDB(courseID);\n const _id = `${DocTypePrefixes[DocType.CARD]}-${uuidv4()}`;\n const card = await db.put<CardData>({\n _id,\n course,\n id_displayable_data,\n id_view,\n docType: DocType.CARD,\n elo: elo || toCourseElo(990 + Math.round(20 * Math.random())),\n author,\n });\n for (const tag of tags) {\n logger.info(`adding tag: ${tag} to card ${card.id}`);\n await addTagToCard(courseID, card.id, tag, author, false);\n }\n return card;\n}\n\nexport async function getCredentialledCourseConfig(courseID: string): Promise<CourseConfig> {\n try {\n const db = getCourseDB(courseID);\n const ret = await db.get<CourseConfig>('CourseConfig');\n ret.courseID = courseID;\n logger.info(`Returning course config: ${JSON.stringify(ret)}`);\n return ret;\n } catch (e) {\n logger.error(`Error fetching config for ${courseID}:`, e);\n throw e;\n }\n}\n\n/**\n Assciates a tag with a card.\n\n NB: DB stores tags as separate documents, with a list of card IDs.\n Consider renaming to `addCardToTag` to reflect this.\n\n NB: tags are created if they don't already exist\n\n @param updateELO whether to update the ELO of the card with the new tag. Default true.\n @package\n*/\nexport async function addTagToCard(\n courseID: string,\n cardID: string,\n tagID: string,\n author: string,\n updateELO: boolean = true\n): Promise<PouchDB.Core.Response> {\n // todo: possible future perf. hit if tags have large #s of taggedCards.\n // In this case, should be converted to a server-request\n const prefixedTagID = getTagID(tagID);\n const courseDB = getCourseDB(courseID);\n const courseApi = new CourseDB(courseID, async () => {\n const dummySyncStrategy = {\n setupRemoteDB: () => null as any,\n startSync: () => {},\n canCreateAccount: () => false,\n canAuthenticate: () => false,\n getCurrentUsername: async () => 'DummyUser',\n };\n return BaseUser.Dummy(dummySyncStrategy);\n });\n try {\n logger.info(`Applying tag ${tagID} to card ${courseID + '-' + cardID}...`);\n const tag = await courseDB.get<Tag>(prefixedTagID);\n if (!tag.taggedCards.includes(cardID)) {\n tag.taggedCards.push(cardID);\n\n if (updateELO) {\n try {\n const eloData = await courseApi.getCardEloData([cardID]);\n const elo = eloData[0];\n elo.tags[tagID] = {\n count: 0,\n score: elo.global.score, // todo: or 1000?\n };\n await updateCardElo(courseID, cardID, elo);\n } catch (error) {\n logger.error('Failed to update ELO data for card:', cardID, error);\n }\n }\n\n return courseDB.put<Tag>(tag);\n } else throw new AlreadyTaggedErr(`Card ${cardID} is already tagged with ${tagID}`);\n } catch (e) {\n if (e instanceof AlreadyTaggedErr) {\n throw e;\n }\n\n await createTag(courseID, tagID, author);\n return addTagToCard(courseID, cardID, tagID, author, updateELO);\n }\n}\n\nasync function updateCardElo(courseID: string, cardID: string, elo: CourseElo) {\n if (elo) {\n // checking against null, undefined, NaN\n const cDB = getCourseDB(courseID);\n const card = await cDB.get<CardData>(cardID);\n logger.debug(`Replacing ${JSON.stringify(card.elo)} with ${JSON.stringify(elo)}`);\n card.elo = elo;\n return cDB.put(card); // race conditions - is it important? probably not (net-zero effect)\n }\n}\n\nclass AlreadyTaggedErr extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AlreadyTaggedErr';\n }\n}\n\nexport function getTagID(tagName: string): string {\n const tagPrefix = DocType.TAG.valueOf() + '-';\n if (tagName.indexOf(tagPrefix) === 0) {\n return tagName;\n } else {\n return tagPrefix + tagName;\n }\n}\n\nexport function getCourseDB(courseID: string): PouchDB.Database {\n const dbName = `coursedb-${courseID}`;\n return new pouch(\n ENV.COUCHDB_SERVER_PROTOCOL + '://' + ENV.COUCHDB_SERVER_URL + dbName,\n createPouchDBConfig()\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwBA,eAAsB,UACpB,UACA,YACA,OACA,MACA,QACA,MACA,SACA,MAAiB,gBAAgB,EACD;CAChC,MAAM,KAAK,YAAY,SAAS;CAChC,MAAM,UAAU,cAAc,UAAU,YAAY,OAAO,MAAM,QAAQ,M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,SAAS,YAAY;AAC3B,QAAO,IAAIC,sBACT,IAAI,0BAA0B,QAAQ,IAAI,qBAAqB,QAC/D,qBAAqB,CACtB"}
|
|
1
|
+
{"version":3,"file":"courseAPI.mjs","names":["uuidv4"],"sources":["../../../src/impl/couch/courseAPI.ts"],"sourcesContent":["import { getCourseDB } from '.';\n// import { DataShape } from '../..base-course/Interfaces/DataShape';\nimport { NameSpacer, ShapeDescriptor } from '@vue-skuilder/common';\nimport { CourseConfig, DataShape } from '@vue-skuilder/common';\nimport { CourseElo, blankCourseElo, toCourseElo } from '@vue-skuilder/common';\nimport { CourseDB, createTag } from './courseDB';\nimport { CardData, DisplayableData, DocType, Tag, DocTypePrefixes } from '../../core/types/types-legacy';\nimport { prepareNote55 } from '@vue-skuilder/common';\nimport { BaseUser } from '../common';\nimport { logger } from '@db/util/logger';\nimport { v4 as uuidv4 } from 'uuid';\n\n/**\n *\n * @param courseID id of the course (quilt) being added to\n * @param codeCourse\n * @param shape\n * @param data the datashape data - data required for this shape\n * @param author\n * @param uploads optional additional media uploads: img0, img1, ..., aud0, aud1,...\n * @returns\n */\nexport async function addNote55(\n courseID: string,\n codeCourse: string,\n shape: DataShape,\n data: unknown,\n author: string,\n tags: string[],\n uploads?: { [x: string]: PouchDB.Core.FullAttachment },\n elo: CourseElo = blankCourseElo()\n): Promise<PouchDB.Core.Response> {\n const db = getCourseDB(courseID);\n const payload = prepareNote55(courseID, codeCourse, shape, data, author, tags, uploads);\n const _id = `${DocTypePrefixes[DocType.DISPLAYABLE_DATA]}-${uuidv4()}`;\n const result = await db.put<DisplayableData>({ ...payload, _id });\n\n const dataShapeId = NameSpacer.getDataShapeString({\n course: codeCourse,\n dataShape: shape.name,\n });\n\n if (result.ok) {\n try {\n // create cards\n await createCards(courseID, dataShapeId, result.id, tags, elo, author);\n } catch (error) {\n // Handle CouchDB errors which often have a 'reason' property\n let errorMessage = 'Unknown error';\n if (error instanceof Error) {\n errorMessage = error.message;\n } else if (error && typeof error === 'object' && 'reason' in error) {\n errorMessage = error.reason as string;\n } else if (error && typeof error === 'object' && 'message' in error) {\n errorMessage = error.message as string;\n } else {\n errorMessage = String(error);\n }\n\n logger.error(`[addNote55] Failed to create cards for note ${result.id}: ${errorMessage}`);\n // Add info to result to indicate card creation failed\n (result as any).cardCreationFailed = true;\n (result as any).cardCreationError = errorMessage;\n }\n } else {\n logger.error(`[addNote55] Error adding note. Result: ${JSON.stringify(result)}`);\n }\n\n return result;\n}\n\nasync function createCards(\n courseID: string,\n datashapeID: PouchDB.Core.DocumentId,\n noteID: PouchDB.Core.DocumentId,\n tags: string[],\n elo: CourseElo = blankCourseElo(),\n author: string\n): Promise<void> {\n const cfg = await getCredentialledCourseConfig(courseID);\n const dsDescriptor = NameSpacer.getDataShapeDescriptor(datashapeID);\n let questionViewTypes: string[] = [];\n\n for (const ds of cfg.dataShapes) {\n if (ds.name === datashapeID) {\n questionViewTypes = ds.questionTypes;\n }\n }\n\n if (questionViewTypes.length === 0) {\n const errorMsg = `No questionViewTypes found for datashapeID: ${datashapeID} in course config. Cards cannot be created.`;\n logger.error(errorMsg);\n throw new Error(errorMsg);\n }\n\n for (const questionView of questionViewTypes) {\n await createCard(questionView, courseID, dsDescriptor, noteID, tags, elo, author);\n }\n}\n\nasync function createCard(\n questionViewName: string,\n courseID: string,\n dsDescriptor: ShapeDescriptor,\n noteID: string,\n tags: string[],\n elo: CourseElo = blankCourseElo(),\n author: string\n): Promise<void> {\n const qDescriptor = NameSpacer.getQuestionDescriptor(questionViewName);\n const cfg = await getCredentialledCourseConfig(courseID);\n\n for (const rQ of cfg.questionTypes) {\n if (rQ.name === questionViewName) {\n for (const view of rQ.viewList) {\n await addCard(\n courseID,\n dsDescriptor.course,\n [noteID],\n NameSpacer.getViewString({\n course: qDescriptor.course,\n questionType: qDescriptor.questionType,\n view,\n }),\n elo,\n tags,\n author\n );\n }\n }\n }\n}\n\n/**\n *\n * Adds a card to the DB. This function is called\n * as a side effect of adding either a View or\n * DisplayableData item.\n * @param course The name of the course that the card belongs to\n * @param id_displayable_data C/PouchDB ID of the data used to hydrate the view\n * @param id_view C/PouchDB ID of the view used to display the card\n *\n * @package\n */\nasync function addCard(\n courseID: string,\n course: string,\n id_displayable_data: PouchDB.Core.DocumentId[],\n id_view: PouchDB.Core.DocumentId,\n elo: CourseElo,\n tags: string[],\n author: string\n): Promise<PouchDB.Core.Response> {\n const db = getCourseDB(courseID);\n const _id = `${DocTypePrefixes[DocType.CARD]}-${uuidv4()}`;\n const card = await db.put<CardData>({\n _id,\n course,\n id_displayable_data,\n id_view,\n docType: DocType.CARD,\n elo: elo || toCourseElo(990 + Math.round(20 * Math.random())),\n author,\n });\n for (const tag of tags) {\n logger.info(`adding tag: ${tag} to card ${card.id}`);\n await addTagToCard(courseID, card.id, tag, author, false);\n }\n return card;\n}\n\n/**\n * CourseConfig reads, cached per course for a few minutes: a study session reads\n * it several times per pipeline run and per card. An edit made elsewhere shows\n * up after the TTL (or a reload); writes through this client invalidate.\n */\nconst COURSE_CONFIG_TTL_MS = 5 * 60 * 1000;\nconst courseConfigCache = new Map<string, { at: number; config: Promise<CourseConfig> }>();\n\nexport function invalidateCourseConfigCache(courseID: string): void {\n courseConfigCache.delete(courseID);\n}\n\nexport async function getCredentialledCourseConfig(courseID: string): Promise<CourseConfig> {\n const hit = courseConfigCache.get(courseID);\n if (hit && Date.now() - hit.at < COURSE_CONFIG_TTL_MS) {\n // A copy: callers mutate configs (e.g. before writing them back).\n return structuredClone(await hit.config);\n }\n\n const config = (async () => {\n const db = getCourseDB(courseID);\n const ret = await db.get<CourseConfig>('CourseConfig');\n ret.courseID = courseID;\n logger.debug(`Fetched course config for ${courseID}`);\n return ret;\n })();\n courseConfigCache.set(courseID, { at: Date.now(), config });\n try {\n return structuredClone(await config);\n } catch (e) {\n courseConfigCache.delete(courseID);\n logger.error(`Error fetching config for ${courseID}:`, e);\n throw e;\n }\n}\n\n/**\n Assciates a tag with a card.\n\n NB: DB stores tags as separate documents, with a list of card IDs.\n Consider renaming to `addCardToTag` to reflect this.\n\n NB: tags are created if they don't already exist\n\n @param updateELO whether to update the ELO of the card with the new tag. Default true.\n @package\n*/\nexport async function addTagToCard(\n courseID: string,\n cardID: string,\n tagID: string,\n author: string,\n updateELO: boolean = true\n): Promise<PouchDB.Core.Response> {\n // todo: possible future perf. hit if tags have large #s of taggedCards.\n // In this case, should be converted to a server-request\n const prefixedTagID = getTagID(tagID);\n const courseDB = getCourseDB(courseID);\n const courseApi = new CourseDB(courseID, async () => {\n const dummySyncStrategy = {\n setupRemoteDB: () => null as any,\n startSync: () => {},\n canCreateAccount: () => false,\n canAuthenticate: () => false,\n getCurrentUsername: async () => 'DummyUser',\n };\n return BaseUser.Dummy(dummySyncStrategy);\n });\n try {\n logger.info(`Applying tag ${tagID} to card ${courseID + '-' + cardID}...`);\n const tag = await courseDB.get<Tag>(prefixedTagID);\n if (!tag.taggedCards.includes(cardID)) {\n tag.taggedCards.push(cardID);\n\n if (updateELO) {\n try {\n const eloData = await courseApi.getCardEloData([cardID]);\n const elo = eloData[0];\n elo.tags[tagID] = {\n count: 0,\n score: elo.global.score, // todo: or 1000?\n };\n await updateCardElo(courseID, cardID, elo);\n } catch (error) {\n logger.error('Failed to update ELO data for card:', cardID, error);\n }\n }\n\n return courseDB.put<Tag>(tag);\n } else throw new AlreadyTaggedErr(`Card ${cardID} is already tagged with ${tagID}`);\n } catch (e) {\n if (e instanceof AlreadyTaggedErr) {\n throw e;\n }\n\n await createTag(courseID, tagID, author);\n return addTagToCard(courseID, cardID, tagID, author, updateELO);\n }\n}\n\nasync function updateCardElo(courseID: string, cardID: string, elo: CourseElo) {\n if (elo) {\n // checking against null, undefined, NaN\n const cDB = getCourseDB(courseID);\n const card = await cDB.get<CardData>(cardID);\n logger.debug(`Replacing ${JSON.stringify(card.elo)} with ${JSON.stringify(elo)}`);\n card.elo = elo;\n return cDB.put(card); // race conditions - is it important? probably not (net-zero effect)\n }\n}\n\nclass AlreadyTaggedErr extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AlreadyTaggedErr';\n }\n}\n\nexport function getTagID(tagName: string): string {\n const tagPrefix = DocType.TAG.valueOf() + '-';\n if (tagName.indexOf(tagPrefix) === 0) {\n return tagName;\n } else {\n return tagPrefix + tagName;\n }\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,UACpB,UACA,YACA,OACA,MACA,QACA,MACA,SACA,MAAiB,gBAAgB,EACD;CAChC,MAAM,KAAK,YAAY,SAAS;CAChC,MAAM,UAAU,cAAc,UAAU,YAAY,OAAO,MAAM,QAAQ,MAAM,QAAQ;CACvF,MAAM,MAAM,GAAG,gBAAgB,QAAQ,kBAAkB,GAAGA,IAAQ;CACpE,MAAM,SAAS,MAAM,GAAG,IAAqB;EAAE,GAAG;EAAS;EAAK,CAAC;CAEjE,MAAM,cAAc,WAAW,mBAAmB;EAChD,QAAQ;EACR,WAAW,MAAM;EAClB,CAAC;AAEF,KAAI,OAAO,GACT,KAAI;AAEF,QAAM,YAAY,UAAU,aAAa,OAAO,IAAI,MAAM,KAAK,OAAO;UAC/D,OAAO;EAEd,IAAI,eAAe;AACnB,MAAI,iBAAiB,MACnB,gBAAe,MAAM;WACZ,SAAS,OAAO,UAAU,YAAY,YAAY,MAC3D,gBAAe,MAAM;WACZ,SAAS,OAAO,UAAU,YAAY,aAAa,MAC5D,gBAAe,MAAM;MAErB,gBAAe,OAAO,MAAM;AAG9B,SAAO,MAAM,+CAA+C,OAAO,GAAG,IAAI,eAAe;AAExF,SAAe,qBAAqB;AACpC,SAAe,oBAAoB;;KAGtC,QAAO,MAAM,0CAA0C,KAAK,UAAU,OAAO,GAAG;AAGlF,QAAO;;AAGT,eAAe,YACb,UACA,aACA,QACA,MACA,MAAiB,gBAAgB,EACjC,QACe;CACf,MAAM,MAAM,MAAM,6BAA6B,SAAS;CACxD,MAAM,eAAe,WAAW,uBAAuB,YAAY;CACnE,IAAI,oBAA8B,EAAE;AAEpC,MAAK,MAAM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AQ,MAAM;;AAItE,UAAO,SAAS,IAAS,IAAI;QACxB,OAAM,IAAI,iBAAiB,QAAQ,OAAO,0BAA0B,QAAQ;UAC5E,GAAG;AACV,MAAI,aAAa,iBACf,OAAM;AAGR,QAAM,UAAU,UAAU,OAAO,OAAO;AACxC,SAAO,aAAa,UAAU,QAAQ,OAAO,QAAQ,UAAU;;;AAInE,eAAe,cAAc,UAAkB,QAAgB,KAAgB;AAC7E,KAAI,KAAK;EAEP,MAAM,MAAM,YAAY,SAAS;EACjC,MAAM,OAAO,MAAM,IAAI,IAAc,OAAO;AAC5C,SAAO,MAAM,aAAa,KAAK,UAAU,KAAK,IAAI,CAAC,QAAQ,KAAK,UAAU,IAAI,GAAG;AACjF,OAAK,MAAM;AACX,SAAO,IAAI,IAAI,KAAK;;;AAIxB,IAAM,mBAAN,cAA+B,MAAM;CACnC,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;;;AAIhB,SAAgB,SAAS,SAAyB;CAChD,MAAM,YAAY,QAAQ,IAAI,SAAS,GAAG;AAC1C,KAAI,QAAQ,QAAQ,UAAU,KAAK,EACjC,QAAO;KAEP,QAAO,YAAY"}
|
|
@@ -7,7 +7,7 @@ import UpdateQueue from "./updateQueue.mjs";
|
|
|
7
7
|
import { GET_CACHED } from "./clientCache.mjs";
|
|
8
8
|
import { createDefaultPipeline } from "../../core/navigators/defaults.mjs";
|
|
9
9
|
import { PipelineAssembler } from "../../core/navigators/PipelineAssembler.mjs";
|
|
10
|
-
import { addNote55, addTagToCard, getCredentialledCourseConfig, getTagID } from "./courseAPI.mjs";
|
|
10
|
+
import { addNote55, addTagToCard, getCredentialledCourseConfig, getTagID, invalidateCourseConfigCache } from "./courseAPI.mjs";
|
|
11
11
|
import { filterAllDocsByPrefix, getCourseDB } from "./index.mjs";
|
|
12
12
|
import { EloToNumber, Status, blankCourseElo, toCourseElo } from "@vue-skuilder/common";
|
|
13
13
|
//#region src/impl/couch/courseDB.ts
|
|
@@ -253,9 +253,10 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
|
|
|
253
253
|
}
|
|
254
254
|
}
|
|
255
255
|
async getAppliedTags(cardId) {
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
256
|
+
return this.db.query("getTags", {
|
|
257
|
+
startkey: cardId,
|
|
258
|
+
endkey: cardId
|
|
259
|
+
});
|
|
259
260
|
}
|
|
260
261
|
async getAppliedTagsBatch(cardIds) {
|
|
261
262
|
if (cardIds.length === 0) return /* @__PURE__ */ new Map();
|
|
@@ -297,7 +298,7 @@ above:\n${above.rows.map((r) => `\t${r.id}-${r.key}\n`)}`;
|
|
|
297
298
|
return await updateTag(tag);
|
|
298
299
|
}
|
|
299
300
|
async getCourseTagStubs() {
|
|
300
|
-
return
|
|
301
|
+
return filterAllDocsByPrefix(this.db, DocType.TAG.valueOf() + "-");
|
|
301
302
|
}
|
|
302
303
|
async addNote(codeCourse, shape, data, author, tags, uploads, elo = blankCourseElo()) {
|
|
303
304
|
try {
|
|
@@ -714,11 +715,16 @@ async function updateCredentialledCourseConfig(courseID, config) {
|
|
|
714
715
|
${JSON.stringify(config)}
|
|
715
716
|
`);
|
|
716
717
|
const db = getCourseDB(courseID);
|
|
718
|
+
invalidateCourseConfigCache(courseID);
|
|
717
719
|
const old = await getCredentialledCourseConfig(courseID);
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
720
|
+
try {
|
|
721
|
+
return await db.put({
|
|
722
|
+
...config,
|
|
723
|
+
_rev: old._rev
|
|
724
|
+
});
|
|
725
|
+
} finally {
|
|
726
|
+
invalidateCourseConfigCache(courseID);
|
|
727
|
+
}
|
|
722
728
|
}
|
|
723
729
|
function isSuccessRow(row) {
|
|
724
730
|
return "doc" in row && row.doc !== null && row.doc !== void 0;
|