@vue-skuilder/db 0.2.36 → 0.3.0

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.
Files changed (59) hide show
  1. package/dist/{contentSource-D_E7JaxR.d.ts → contentSource-2zVmcjKA.d.ts} +6 -1
  2. package/dist/core/index.cjs +203 -148
  3. package/dist/core/index.cjs.map +1 -1
  4. package/dist/core/index.d.ts +5 -5
  5. package/dist/core/navigators/Pipeline.mjs +8 -0
  6. package/dist/core/navigators/Pipeline.mjs.map +1 -1
  7. package/dist/core/navigators/generators/prescribed.mjs +29 -11
  8. package/dist/core/navigators/generators/prescribed.mjs.map +1 -1
  9. package/dist/core/versionStamps.mjs +1 -1
  10. package/dist/{dataLayerProvider-BDshhSp_.d.ts → dataLayerProvider-rGyLQ93v.d.ts} +1 -1
  11. package/dist/diagnostics/index.d.ts +3 -3
  12. package/dist/impl/common/BaseUserDB.mjs +32 -15
  13. package/dist/impl/common/BaseUserDB.mjs.map +1 -1
  14. package/dist/impl/couch/CourseSyncService.mjs +111 -11
  15. package/dist/impl/couch/CourseSyncService.mjs.map +1 -1
  16. package/dist/impl/couch/PouchDataLayerProvider.mjs +16 -1
  17. package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -1
  18. package/dist/impl/couch/courseAPI.mjs +24 -10
  19. package/dist/impl/couch/courseAPI.mjs.map +1 -1
  20. package/dist/impl/couch/courseDB.mjs +19 -9
  21. package/dist/impl/couch/courseDB.mjs.map +1 -1
  22. package/dist/impl/couch/index.cjs +297 -141
  23. package/dist/impl/couch/index.cjs.map +1 -1
  24. package/dist/impl/couch/index.d.ts +27 -4
  25. package/dist/impl/couch/index.mjs +20 -3
  26. package/dist/impl/couch/index.mjs.map +1 -1
  27. package/dist/impl/couch/updateQueue.mjs +69 -46
  28. package/dist/impl/couch/updateQueue.mjs.map +1 -1
  29. package/dist/impl/static/index.cjs +147 -93
  30. package/dist/impl/static/index.cjs.map +1 -1
  31. package/dist/impl/static/index.d.ts +4 -4
  32. package/dist/{index-BLDpFYG3.d.ts → index-C745YB_6.d.ts} +1 -1
  33. package/dist/index.cjs +345 -171
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.d.ts +23 -10
  36. package/dist/index.mjs +2 -1
  37. package/dist/study/SessionController.mjs +4 -0
  38. package/dist/study/SessionController.mjs.map +1 -1
  39. package/dist/{types-DChCz22D.d.ts → types-DF0JuPbs.d.ts} +1 -1
  40. package/dist/{types-legacy-fT5Y1Wuy.d.ts → types-legacy-DdVjg81H.d.ts} +1 -1
  41. package/dist/util/packer/index.d.ts +3 -3
  42. package/dist/util/perfMarks.mjs +30 -0
  43. package/dist/util/perfMarks.mjs.map +1 -0
  44. package/package.json +3 -3
  45. package/src/core/interfaces/courseDB.ts +6 -0
  46. package/src/core/navigators/Pipeline.ts +8 -0
  47. package/src/core/navigators/generators/prescribed.ts +42 -16
  48. package/src/impl/common/BaseUserDB.ts +42 -23
  49. package/src/impl/couch/CourseSyncService.ts +149 -22
  50. package/src/impl/couch/PouchDataLayerProvider.ts +14 -1
  51. package/src/impl/couch/courseAPI.ts +26 -12
  52. package/src/impl/couch/courseDB.ts +25 -12
  53. package/src/impl/couch/index.ts +16 -5
  54. package/src/impl/couch/updateQueue.ts +86 -82
  55. package/src/study/SessionController.ts +4 -0
  56. package/src/util/index.ts +1 -0
  57. package/src/util/perfMarks.ts +35 -0
  58. package/tests/impl/courseSync.test.ts +139 -0
  59. package/tests/impl/updateQueue.test.ts +57 -0
package/dist/index.cjs CHANGED
@@ -1582,6 +1582,12 @@ var init_prescribed = __esm({
1582
1582
  PrescribedCardsGenerator = class extends ContentNavigator {
1583
1583
  name;
1584
1584
  config;
1585
+ /**
1586
+ * Course-wide reads that don't change within a navigator's lifetime (the
1587
+ * navigator is cached per CourseDB, minutes), loaded once, not per run.
1588
+ */
1589
+ _cardsByTag = null;
1590
+ _hierarchyConfigs = null;
1585
1591
  constructor(user, course, strategyData) {
1586
1592
  super(user, course, strategyData);
1587
1593
  this.name = strategyData.name || "Prescribed Cards";
@@ -1614,20 +1620,7 @@ var init_prescribed = __esm({
1614
1620
  const allSupportIds = dedupe(this.config.groups.flatMap((g) => g.supportCardIds ?? []));
1615
1621
  const allRelevantIds = dedupe([...allTargetIds, ...allSupportIds]);
1616
1622
  const tagsByCard = allRelevantIds.length > 0 ? await this.course.getAppliedTagsBatch(allRelevantIds) : /* @__PURE__ */ new Map();
1617
- const courseTagDocs = await this.course.getCourseTagStubs().catch(
1618
- () => ({
1619
- rows: [],
1620
- offset: 0,
1621
- total_rows: 0
1622
- })
1623
- );
1624
- const cardsByTag = /* @__PURE__ */ new Map();
1625
- for (const row of courseTagDocs.rows ?? []) {
1626
- const tagDoc = row.doc;
1627
- if (tagDoc?.name && Array.isArray(tagDoc.taggedCards)) {
1628
- cardsByTag.set(tagDoc.name, [...tagDoc.taggedCards]);
1629
- }
1630
- }
1623
+ const cardsByTag = await this.loadCardsByTag();
1631
1624
  const nextState = {
1632
1625
  updatedAt: isoNow(),
1633
1626
  groups: {}
@@ -1867,7 +1860,33 @@ var init_prescribed = __esm({
1867
1860
  return { groups: [] };
1868
1861
  }
1869
1862
  }
1870
- async loadHierarchyConfigs() {
1863
+ /** Tag name → tagged card IDs, from the course's tag docs (once per instance). */
1864
+ loadCardsByTag() {
1865
+ if (!this._cardsByTag) {
1866
+ this._cardsByTag = this.course.getCourseTagStubs().then((docs) => {
1867
+ const cardsByTag = /* @__PURE__ */ new Map();
1868
+ for (const row of docs.rows ?? []) {
1869
+ const tagDoc = row.doc;
1870
+ if (tagDoc?.name && Array.isArray(tagDoc.taggedCards)) {
1871
+ cardsByTag.set(tagDoc.name, [...tagDoc.taggedCards]);
1872
+ }
1873
+ }
1874
+ return cardsByTag;
1875
+ }).catch((e) => {
1876
+ this._cardsByTag = null;
1877
+ logger.debug(`[Prescribed] Failed to load tag docs: ${e}`);
1878
+ return /* @__PURE__ */ new Map();
1879
+ });
1880
+ }
1881
+ return this._cardsByTag;
1882
+ }
1883
+ loadHierarchyConfigs() {
1884
+ if (!this._hierarchyConfigs) {
1885
+ this._hierarchyConfigs = this.fetchHierarchyConfigs();
1886
+ }
1887
+ return this._hierarchyConfigs;
1888
+ }
1889
+ async fetchHierarchyConfigs() {
1871
1890
  try {
1872
1891
  const strategies = await this.course.getAllNavigationStrategies();
1873
1892
  return strategies.filter((s) => s.implementingClass === "hierarchyDefinition").map((s) => {
@@ -1881,6 +1900,7 @@ var init_prescribed = __esm({
1881
1900
  }
1882
1901
  });
1883
1902
  } catch (e) {
1903
+ this._hierarchyConfigs = null;
1884
1904
  logger.debug(`[Prescribed] Failed to load hierarchy configs: ${e}`);
1885
1905
  return [];
1886
1906
  }
@@ -3604,7 +3624,7 @@ var FRAMEWORK_VERSION, hostAppVersion, DEFAULT_STRATEGY_HASH;
3604
3624
  var init_versionStamps = __esm({
3605
3625
  "src/core/versionStamps.ts"() {
3606
3626
  "use strict";
3607
- FRAMEWORK_VERSION = true ? "0.2.36" : "dev";
3627
+ FRAMEWORK_VERSION = true ? "0.3.0" : "dev";
3608
3628
  DEFAULT_STRATEGY_HASH = "default";
3609
3629
  }
3610
3630
  });
@@ -3747,8 +3767,10 @@ var init_updateQueue = __esm({
3747
3767
  init_logger();
3748
3768
  UpdateQueue = class extends Loggable {
3749
3769
  _className = "UpdateQueue";
3750
- pendingUpdates = {};
3751
- inprogressUpdates = {};
3770
+ /** Updates not yet taken by a write, per doc. */
3771
+ pending = /* @__PURE__ */ new Map();
3772
+ /** Docs with a drain loop running. */
3773
+ draining = /* @__PURE__ */ new Set();
3752
3774
  readDB;
3753
3775
  // Database for read operations
3754
3776
  writeDB;
@@ -3766,6 +3788,9 @@ var init_updateQueue = __esm({
3766
3788
  * **Error Handling Pattern:**
3767
3789
  * - This method does NOT create documents if they don't exist
3768
3790
  * - Callers are responsible for handling 404 errors and creating documents
3791
+ * - A rejected update is dropped from the queue: a caller that creates the
3792
+ * doc after a 404 has already applied its change and must not see it
3793
+ * re-applied by a later update to the same doc
3769
3794
  * - This design maintains separation of concerns (UpdateQueue handles conflicts, callers handle lifecycle)
3770
3795
  *
3771
3796
  * @example
@@ -3782,12 +3807,16 @@ var init_updateQueue = __esm({
3782
3807
  */
3783
3808
  update(id, update) {
3784
3809
  logger.debug(`Update requested on doc: ${id}`);
3785
- if (this.pendingUpdates[id]) {
3786
- this.pendingUpdates[id].push(update);
3787
- } else {
3788
- this.pendingUpdates[id] = [update];
3789
- }
3790
- return this.applyUpdates(id);
3810
+ return new Promise((resolve, reject) => {
3811
+ const queue = this.pending.get(id) ?? [];
3812
+ queue.push({
3813
+ update,
3814
+ resolve,
3815
+ reject
3816
+ });
3817
+ this.pending.set(id, queue);
3818
+ if (!this.draining.has(id)) void this.drain(id);
3819
+ });
3791
3820
  }
3792
3821
  constructor(readDB, writeDB) {
3793
3822
  super();
@@ -3798,64 +3827,56 @@ var init_updateQueue = __esm({
3798
3827
  logger.debug(`db info: ${JSON.stringify(i)}`);
3799
3828
  });
3800
3829
  }
3801
- async applyUpdates(id) {
3802
- logger.debug(`Applying updates on doc: ${id}`);
3803
- if (this.inprogressUpdates[id]) {
3804
- while (this.inprogressUpdates[id]) {
3805
- await new Promise((resolve) => setTimeout(resolve, Math.random() * 50));
3830
+ /** Writes the doc's queued updates, batch by batch, until none are left. */
3831
+ async drain(id) {
3832
+ this.draining.add(id);
3833
+ try {
3834
+ let batch;
3835
+ while ((batch = this.pending.get(id)) && batch.length > 0) {
3836
+ this.pending.delete(id);
3837
+ try {
3838
+ const doc = await this.write(
3839
+ id,
3840
+ batch.map((p) => p.update)
3841
+ );
3842
+ batch.forEach((p) => p.resolve(doc));
3843
+ } catch (e) {
3844
+ batch.forEach((p) => p.reject(e));
3845
+ }
3806
3846
  }
3807
- return this.applyUpdates(id);
3808
- } else {
3809
- if (this.pendingUpdates[id] && this.pendingUpdates[id].length > 0) {
3810
- this.inprogressUpdates[id] = true;
3811
- const MAX_RETRIES = 5;
3812
- for (let i = 0; i < MAX_RETRIES; i++) {
3813
- try {
3814
- const doc = await this.readDB.get(id);
3815
- let updatedDoc = { ...doc };
3816
- const updatesToApply = [...this.pendingUpdates[id]];
3817
- for (const update of updatesToApply) {
3818
- if (typeof update === "function") {
3819
- updatedDoc = { ...updatedDoc, ...update(updatedDoc) };
3820
- } else {
3821
- updatedDoc = {
3822
- ...updatedDoc,
3823
- ...update
3824
- };
3825
- }
3826
- }
3827
- await this.writeDB.put(updatedDoc);
3828
- this.pendingUpdates[id].splice(0, updatesToApply.length);
3829
- if (this.pendingUpdates[id].length === 0) {
3830
- this.inprogressUpdates[id] = false;
3831
- delete this.inprogressUpdates[id];
3832
- } else {
3833
- return this.applyUpdates(id);
3834
- }
3835
- return updatedDoc;
3836
- } catch (e) {
3837
- if (e.name === "conflict" && i < MAX_RETRIES - 1) {
3838
- logger.warn(`Conflict on update for doc ${id}, retry #${i + 1}`);
3839
- await new Promise((res) => setTimeout(res, 50 * Math.random()));
3840
- } else if (e.name === "not_found" && i === 0) {
3841
- logger.warn(`Update failed for ${id} - does not exist. Throwing to caller.`);
3842
- delete this.inprogressUpdates[id];
3843
- throw e;
3844
- } else {
3845
- delete this.inprogressUpdates[id];
3846
- if (this.pendingUpdates[id]) {
3847
- delete this.pendingUpdates[id];
3848
- }
3849
- logger.error(`Error on attemped update (retry ${i}): ${JSON.stringify(e)}`);
3850
- throw e;
3851
- }
3852
- }
3847
+ } finally {
3848
+ this.draining.delete(id);
3849
+ }
3850
+ }
3851
+ /** One read-apply-put of `updates`, retried on conflict against a fresh read. */
3852
+ async write(id, updates) {
3853
+ logger.debug(`Applying ${updates.length} update(s) on doc: ${id}`);
3854
+ const MAX_RETRIES = 5;
3855
+ for (let i = 0; i < MAX_RETRIES; i++) {
3856
+ try {
3857
+ const doc = await this.readDB.get(id);
3858
+ let updatedDoc = {
3859
+ ...doc
3860
+ };
3861
+ for (const update of updates) {
3862
+ updatedDoc = typeof update === "function" ? { ...updatedDoc, ...update(updatedDoc) } : { ...updatedDoc, ...update };
3863
+ }
3864
+ const res = await this.writeDB.put(updatedDoc);
3865
+ return { ...updatedDoc, _rev: res.rev };
3866
+ } catch (e) {
3867
+ if (e.name === "conflict" && i < MAX_RETRIES - 1) {
3868
+ logger.warn(`Conflict on update for doc ${id}, retry #${i + 1}`);
3869
+ await new Promise((res) => setTimeout(res, 50 * Math.random()));
3870
+ } else if (e.name === "not_found" && i === 0) {
3871
+ logger.warn(`Update failed for ${id} - does not exist. Throwing to caller.`);
3872
+ throw e;
3873
+ } else {
3874
+ logger.error(`Error on attemped update (retry ${i}): ${JSON.stringify(e)}`);
3875
+ throw e;
3853
3876
  }
3854
- throw new Error(`UpdateQueue failed for doc ${id} after ${MAX_RETRIES} retries.`);
3855
- } else {
3856
- throw new Error(`Empty Updates Queue Triggered`);
3857
3877
  }
3858
3878
  }
3879
+ throw new Error(`UpdateQueue failed for doc ${id} after ${MAX_RETRIES} retries.`);
3859
3880
  }
3860
3881
  };
3861
3882
  }
@@ -4707,9 +4728,9 @@ var init_CardHydrationService = __esm({
4707
4728
  import_common10 = require("@vue-skuilder/common");
4708
4729
  init_logger();
4709
4730
  CardHydrationService = class {
4710
- constructor(getViewComponent, getCourseDB3, getItemsToHydrate) {
4731
+ constructor(getViewComponent, getCourseDB2, getItemsToHydrate) {
4711
4732
  this.getViewComponent = getViewComponent;
4712
- this.getCourseDB = getCourseDB3;
4733
+ this.getCourseDB = getCourseDB2;
4713
4734
  this.getItemsToHydrate = getItemsToHydrate;
4714
4735
  }
4715
4736
  hydratedCards = /* @__PURE__ */ new Map();
@@ -6567,6 +6588,29 @@ var init_dataDirectory = __esm({
6567
6588
  }
6568
6589
  });
6569
6590
 
6591
+ // src/util/perfMarks.ts
6592
+ function perfMark(name, detail) {
6593
+ try {
6594
+ globalThis.performance?.mark(name, detail ? { detail } : void 0);
6595
+ } catch {
6596
+ }
6597
+ }
6598
+ function perfMeasure(name, start, end, detail) {
6599
+ try {
6600
+ globalThis.performance?.measure(name, {
6601
+ start,
6602
+ ...end !== void 0 ? { end } : {},
6603
+ ...detail ? { detail } : {}
6604
+ });
6605
+ } catch {
6606
+ }
6607
+ }
6608
+ var init_perfMarks = __esm({
6609
+ "src/util/perfMarks.ts"() {
6610
+ "use strict";
6611
+ }
6612
+ });
6613
+
6570
6614
  // src/util/index.ts
6571
6615
  var init_util2 = __esm({
6572
6616
  "src/util/index.ts"() {
@@ -6575,6 +6619,7 @@ var init_util2 = __esm({
6575
6619
  init_packer();
6576
6620
  init_migrator();
6577
6621
  init_dataDirectory();
6622
+ init_perfMarks();
6578
6623
  }
6579
6624
  });
6580
6625
 
@@ -6988,6 +7033,7 @@ var init_Pipeline = __esm({
6988
7033
  import_common11 = require("@vue-skuilder/common");
6989
7034
  init_navigators();
6990
7035
  init_logger();
7036
+ init_perfMarks();
6991
7037
  init_orchestration();
6992
7038
  init_PipelineDebugger();
6993
7039
  init_diversityRerank();
@@ -7191,6 +7237,13 @@ var init_Pipeline = __esm({
7191
7237
  logger.info(
7192
7238
  `[Pipeline:timing] total=${(tFilter - t0).toFixed(0)}ms (context=${(tContext - t0).toFixed(0)} generate=${(tGenerate - tContext).toFixed(0)} hydrate=${(tHydrate - tGenerate).toFixed(0)} filter=${(tFilter - tHydrate).toFixed(0)})`
7193
7239
  );
7240
+ perfMeasure("sk:pipeline-run", t0, tFilter, {
7241
+ context: Math.round(tContext - t0),
7242
+ generate: Math.round(tGenerate - tContext),
7243
+ hydrate: Math.round(tHydrate - tGenerate),
7244
+ filter: Math.round(tFilter - tHydrate),
7245
+ binding: this.course?.readsLocal === void 0 ? "unknown" : this.course.readsLocal ? "local" : "remote"
7246
+ });
7194
7247
  const topScores = result.slice(0, 3).map((c) => c.score);
7195
7248
  logExecutionSummary(
7196
7249
  this.generator.name,
@@ -8841,6 +8894,7 @@ var init_SessionController = __esm({
8841
8894
  init_studySession();
8842
8895
  init_recording();
8843
8896
  init_util2();
8897
+ init_perfMarks();
8844
8898
  init_navigators();
8845
8899
  init_Pipeline();
8846
8900
  init_versionStamps();
@@ -9102,6 +9156,7 @@ var init_SessionController = __esm({
9102
9156
  );
9103
9157
  }
9104
9158
  clearStaleSessionDebugState();
9159
+ perfMark("sk:session-prepare-start");
9105
9160
  const wellIndicated = await this.getWeightedContent();
9106
9161
  this._recordRuns("bootstrap");
9107
9162
  this._wellIndicatedRemaining = wellIndicated;
@@ -9111,6 +9166,8 @@ var init_SessionController = __esm({
9111
9166
  );
9112
9167
  }
9113
9168
  await this.hydrationService.ensureHydratedCards();
9169
+ perfMark("sk:session-prepared");
9170
+ perfMeasure("sk:session-prepare", "sk:session-prepare-start", "sk:session-prepared");
9114
9171
  startSessionTracking(this.sessionId, this.supplyQ.length, this.failedQ.length);
9115
9172
  this._openDocPromise = this._openSessionDoc();
9116
9173
  this._intervalHandle = setInterval(() => {
@@ -10871,6 +10928,18 @@ Currently logged-in as ${this._username}.`
10871
10928
  update(id, update) {
10872
10929
  return this.updateQueue.update(id, update);
10873
10930
  }
10931
+ /**
10932
+ * Create a default doc after a 404. Concurrent first reads (e.g. two
10933
+ * components on a brand-new user) both see the 404 and both create; the
10934
+ * loser's conflict just means the doc now exists, which is what it wanted.
10935
+ */
10936
+ async putDefaultUnlessCreated(doc) {
10937
+ try {
10938
+ await this.localDB.put(doc);
10939
+ } catch (e) {
10940
+ if (e.status !== 409) throw e;
10941
+ }
10942
+ }
10874
10943
  async getCourseRegistrationsDoc() {
10875
10944
  logger.debug(`Fetching courseRegistrations for ${this.getUsername()}`);
10876
10945
  let ret;
@@ -10887,7 +10956,7 @@ Currently logged-in as ${this._username}.`
10887
10956
  `Cannot read course registrations for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to create an empty registration doc \u2014 that would report an existing user as unregistered, and then lose to their real document once sync resumes.`
10888
10957
  );
10889
10958
  }
10890
- await this.localDB.put({
10959
+ await this.putDefaultUnlessCreated({
10891
10960
  _id: _BaseUser.DOC_IDS.COURSE_REGISTRATIONS,
10892
10961
  courses: [],
10893
10962
  studyWeight: {}
@@ -11134,7 +11203,7 @@ Currently logged-in as ${this._username}.`
11134
11203
  `Cannot read config for ${this._username}: the local mirror is unavailable (hydration state '${this._hydration.state}'). Refusing to write a default config over what may be an existing one.`
11135
11204
  );
11136
11205
  }
11137
- await this.localDB.put(defaultConfig);
11206
+ await this.putDefaultUnlessCreated(defaultConfig);
11138
11207
  return this.getConfig();
11139
11208
  } else {
11140
11209
  logger.error(`Error setting user default config:`, e);
@@ -11395,22 +11464,20 @@ Currently logged-in as ${this._username}.`
11395
11464
  async putCardRecord(record) {
11396
11465
  const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);
11397
11466
  record.timeStamp = import_moment7.default.utc(record.timeStamp).toString();
11398
- try {
11399
- const cardHistory = await this.update(
11400
- cardHistoryID,
11401
- function(h) {
11402
- h.records.push(record);
11403
- h.bestInterval = h.bestInterval || 0;
11404
- if (areQuestionRecords(h)) {
11405
- h.lapses = getLapses(h.records);
11406
- h.streak = getStreak(h.records);
11407
- } else {
11408
- h.lapses = h.lapses || 0;
11409
- h.streak = h.streak || 0;
11410
- }
11411
- return h;
11412
- }
11413
- );
11467
+ const append = (h) => {
11468
+ h.records.push(record);
11469
+ h.bestInterval = h.bestInterval || 0;
11470
+ if (areQuestionRecords(h)) {
11471
+ h.lapses = getLapses(h.records);
11472
+ h.streak = getStreak(h.records);
11473
+ } else {
11474
+ h.lapses = h.lapses || 0;
11475
+ h.streak = h.streak || 0;
11476
+ }
11477
+ return h;
11478
+ };
11479
+ const appendToExisting = async () => {
11480
+ const cardHistory = await this.update(cardHistoryID, append);
11414
11481
  cardHistory.records = cardHistory.records.map((record2) => {
11415
11482
  const ret = {
11416
11483
  ...record2
@@ -11419,6 +11486,9 @@ Currently logged-in as ${this._username}.`
11419
11486
  return ret;
11420
11487
  });
11421
11488
  return cardHistory;
11489
+ };
11490
+ try {
11491
+ return await appendToExisting();
11422
11492
  } catch (e) {
11423
11493
  const reason = e;
11424
11494
  if (reason.status === 404) {
@@ -11435,6 +11505,9 @@ Currently logged-in as ${this._username}.`
11435
11505
  const putResult = await this.writeDB.put(initCardHistory);
11436
11506
  return { ...initCardHistory, _rev: putResult.rev };
11437
11507
  } catch (creationError) {
11508
+ if (creationError.name === "conflict") {
11509
+ return appendToExisting();
11510
+ }
11438
11511
  throw new Error(
11439
11512
  `Failed to create CardHistory for ${cardHistoryID}. Reason: ${creationError}`
11440
11513
  );
@@ -11841,14 +11914,26 @@ async function addCard(courseID, course, id_displayable_data, id_view, elo, tags
11841
11914
  }
11842
11915
  return card;
11843
11916
  }
11917
+ function invalidateCourseConfigCache(courseID) {
11918
+ courseConfigCache.delete(courseID);
11919
+ }
11844
11920
  async function getCredentialledCourseConfig(courseID) {
11845
- try {
11921
+ const hit = courseConfigCache.get(courseID);
11922
+ if (hit && Date.now() - hit.at < COURSE_CONFIG_TTL_MS) {
11923
+ return structuredClone(await hit.config);
11924
+ }
11925
+ const config = (async () => {
11846
11926
  const db = getCourseDB(courseID);
11847
11927
  const ret = await db.get("CourseConfig");
11848
11928
  ret.courseID = courseID;
11849
- logger.info(`Returning course config: ${JSON.stringify(ret)}`);
11929
+ logger.debug(`Fetched course config for ${courseID}`);
11850
11930
  return ret;
11931
+ })();
11932
+ courseConfigCache.set(courseID, { at: Date.now(), config });
11933
+ try {
11934
+ return structuredClone(await config);
11851
11935
  } catch (e) {
11936
+ courseConfigCache.delete(courseID);
11852
11937
  logger.error(`Error fetching config for ${courseID}:`, e);
11853
11938
  throw e;
11854
11939
  }
@@ -11913,20 +11998,11 @@ function getTagID(tagName) {
11913
11998
  return tagPrefix + tagName;
11914
11999
  }
11915
12000
  }
11916
- function getCourseDB(courseID) {
11917
- const dbName = `coursedb-${courseID}`;
11918
- return new pouchdb_setup_default(
11919
- ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + dbName,
11920
- createPouchDBConfig()
11921
- );
11922
- }
11923
- var import_common14, import_common15, import_common16, import_uuid, AlreadyTaggedErr;
12001
+ var import_common14, import_common15, import_common16, import_uuid, COURSE_CONFIG_TTL_MS, courseConfigCache, AlreadyTaggedErr;
11924
12002
  var init_courseAPI = __esm({
11925
12003
  "src/impl/couch/courseAPI.ts"() {
11926
12004
  "use strict";
11927
- init_pouchdb_setup();
11928
12005
  init_couch();
11929
- init_factory();
11930
12006
  import_common14 = require("@vue-skuilder/common");
11931
12007
  import_common15 = require("@vue-skuilder/common");
11932
12008
  init_courseDB();
@@ -11935,6 +12011,8 @@ var init_courseAPI = __esm({
11935
12011
  init_common();
11936
12012
  init_logger();
11937
12013
  import_uuid = require("uuid");
12014
+ COURSE_CONFIG_TTL_MS = 5 * 60 * 1e3;
12015
+ courseConfigCache = /* @__PURE__ */ new Map();
11938
12016
  AlreadyTaggedErr = class extends Error {
11939
12017
  constructor(message) {
11940
12018
  super(message);
@@ -12662,21 +12740,10 @@ var init_PipelineAssembler = __esm({
12662
12740
  function randIntWeightedTowardZero(n) {
12663
12741
  return Math.floor(Math.random() * Math.random() * Math.random() * n);
12664
12742
  }
12665
- async function getCourseTagStubs(courseID) {
12666
- logger.debug(`Getting tag stubs for course: ${courseID}`);
12667
- const stubs = await filterAllDocsByPrefix2(
12668
- getCourseDB2(courseID),
12669
- "TAG" /* TAG */.valueOf() + "-"
12670
- );
12671
- stubs.rows.forEach((row) => {
12672
- logger.debug(` Tag stub for doc: ${row.id}`);
12673
- });
12674
- return stubs;
12675
- }
12676
12743
  async function createTag(courseID, tagName, author) {
12677
12744
  logger.debug(`Creating tag: ${tagName}...`);
12678
12745
  const tagID = getTagID(tagName);
12679
- const courseDB = getCourseDB2(courseID);
12746
+ const courseDB = getCourseDB(courseID);
12680
12747
  const resp = await courseDB.put({
12681
12748
  course: courseID,
12682
12749
  docType: "TAG" /* TAG */,
@@ -12691,45 +12758,41 @@ async function createTag(courseID, tagName, author) {
12691
12758
  }
12692
12759
  async function updateTag(tag) {
12693
12760
  const prior = await getTag(tag.course, tag.name);
12694
- return await getCourseDB2(tag.course).put({
12761
+ return await getCourseDB(tag.course).put({
12695
12762
  ...tag,
12696
12763
  _rev: prior._rev
12697
12764
  });
12698
12765
  }
12699
12766
  async function getTag(courseID, tagName) {
12700
12767
  const tagID = getTagID(tagName);
12701
- const courseDB = getCourseDB2(courseID);
12768
+ const courseDB = getCourseDB(courseID);
12702
12769
  return courseDB.get(tagID);
12703
12770
  }
12704
12771
  async function removeTagFromCard(courseID, cardID, tagID) {
12705
12772
  tagID = getTagID(tagID);
12706
- const courseDB = getCourseDB2(courseID);
12773
+ const courseDB = getCourseDB(courseID);
12707
12774
  const tag = await courseDB.get(tagID);
12708
12775
  tag.taggedCards = tag.taggedCards.filter((taggedID) => {
12709
12776
  return cardID !== taggedID;
12710
12777
  });
12711
12778
  return courseDB.put(tag);
12712
12779
  }
12713
- async function getAppliedTags(id_course, id_card) {
12714
- const db = getCourseDB2(id_course);
12715
- const result = await db.query("getTags", {
12716
- startkey: id_card,
12717
- endkey: id_card
12718
- // include_docs: true
12719
- });
12720
- return result;
12721
- }
12722
12780
  async function updateCredentialledCourseConfig(courseID, config) {
12723
12781
  logger.debug(`Updating course config:
12724
12782
 
12725
12783
  ${JSON.stringify(config)}
12726
12784
  `);
12727
- const db = getCourseDB2(courseID);
12785
+ const db = getCourseDB(courseID);
12786
+ invalidateCourseConfigCache(courseID);
12728
12787
  const old = await getCredentialledCourseConfig(courseID);
12729
- return await db.put({
12730
- ...config,
12731
- _rev: old._rev
12732
- });
12788
+ try {
12789
+ return await db.put({
12790
+ ...config,
12791
+ _rev: old._rev
12792
+ });
12793
+ } finally {
12794
+ invalidateCourseConfigCache(courseID);
12795
+ }
12733
12796
  }
12734
12797
  function isSuccessRow(row) {
12735
12798
  return "doc" in row && row.doc !== null && row.doc !== void 0;
@@ -12826,9 +12889,13 @@ var init_courseDB = __esm({
12826
12889
  * values may be stale, so read-modify-write cycles must go through
12827
12890
  * the remote DB to avoid conflicts).
12828
12891
  */
12892
+ /** Reads go to this device's replica (perf marks report it as the session's binding). */
12893
+ get readsLocal() {
12894
+ return this.db !== this.remoteDB;
12895
+ }
12829
12896
  constructor(id, userLookup, localDB) {
12830
12897
  this.id = id;
12831
- const remote = getCourseDB2(this.id);
12898
+ const remote = getCourseDB(this.id);
12832
12899
  this.remoteDB = remote;
12833
12900
  this.db = localDB ?? remote;
12834
12901
  this._getCurrentUser = userLookup;
@@ -13032,12 +13099,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
13032
13099
  }
13033
13100
  }
13034
13101
  async getAppliedTags(cardId) {
13035
- const ret = await getAppliedTags(this.id, cardId);
13036
- if (ret) {
13037
- return ret;
13038
- } else {
13039
- throw new Error(`Failed to find tags for card ${this.id}-${cardId}`);
13040
- }
13102
+ return this.db.query("getTags", { startkey: cardId, endkey: cardId });
13041
13103
  }
13042
13104
  async getAppliedTagsBatch(cardIds) {
13043
13105
  if (cardIds.length === 0) {
@@ -13094,7 +13156,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
13094
13156
  return await updateTag(tag);
13095
13157
  }
13096
13158
  async getCourseTagStubs() {
13097
- return getCourseTagStubs(this.id);
13159
+ return filterAllDocsByPrefix2(this.db, "TAG" /* TAG */.valueOf() + "-");
13098
13160
  }
13099
13161
  async addNote(codeCourse, shape, data, author, tags, uploads, elo = (0, import_common18.blankCourseElo)()) {
13100
13162
  try {
@@ -14198,11 +14260,14 @@ function createPouchDBConfig() {
14198
14260
  }
14199
14261
  return pouchDBincludeCredentialsConfig;
14200
14262
  }
14201
- function getCourseDB2(courseID) {
14202
- return new pouchdb_setup_default(
14203
- ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + "coursedb-" + courseID,
14204
- createPouchDBConfig()
14205
- );
14263
+ function getCourseDB(courseID) {
14264
+ const url = ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + "coursedb-" + courseID;
14265
+ let db = courseDBHandles.get(url);
14266
+ if (!db) {
14267
+ db = new pouchdb_setup_default(url, { ...createPouchDBConfig(), skip_setup: true });
14268
+ courseDBHandles.set(url, db);
14269
+ }
14270
+ return db;
14206
14271
  }
14207
14272
  function filterAllDocsByPrefix2(db, prefix, opts) {
14208
14273
  const options = {
@@ -14221,7 +14286,7 @@ function getStartAndEndKeys2(key) {
14221
14286
  endkey: key + "\uFFF0"
14222
14287
  };
14223
14288
  }
14224
- var import_cross_fetch2, import_moment9, GUEST_LOCAL_DB, localUserDB, pouchDBincludeCredentialsConfig, REVIEW_TIME_FORMAT2;
14289
+ var import_cross_fetch2, import_moment9, GUEST_LOCAL_DB, localUserDB, pouchDBincludeCredentialsConfig, courseDBHandles, REVIEW_TIME_FORMAT2;
14225
14290
  var init_couch = __esm({
14226
14291
  "src/impl/couch/index.ts"() {
14227
14292
  "use strict";
@@ -14245,6 +14310,7 @@ var init_couch = __esm({
14245
14310
  return pouchdb_setup_default.fetch(url, opts);
14246
14311
  }
14247
14312
  };
14313
+ courseDBHandles = /* @__PURE__ */ new Map();
14248
14314
  REVIEW_TIME_FORMAT2 = "YYYY-MM-DD--kk:mm:ss-SSS";
14249
14315
  }
14250
14316
  });
@@ -14254,13 +14320,15 @@ var CourseSyncService_exports = {};
14254
14320
  __export(CourseSyncService_exports, {
14255
14321
  CourseSyncService: () => CourseSyncService
14256
14322
  });
14257
- var DEFAULT_REPLICATION, CourseSyncService;
14323
+ var SYNC_MARKER_ID, DEFAULT_REPLICATION, CourseSyncService;
14258
14324
  var init_CourseSyncService = __esm({
14259
14325
  "src/impl/couch/CourseSyncService.ts"() {
14260
14326
  "use strict";
14261
14327
  init_pouchdb_setup();
14262
14328
  init_couch();
14263
14329
  init_logger();
14330
+ init_perfMarks();
14331
+ SYNC_MARKER_ID = "_local/sk-course-sync-complete";
14264
14332
  DEFAULT_REPLICATION = {
14265
14333
  batchSize: 1e3,
14266
14334
  batchesLimit: 5
@@ -14331,19 +14399,7 @@ var init_CourseSyncService = __esm({
14331
14399
  async ensureSynced(courseId, forceEnabled) {
14332
14400
  const existing = this.entries.get(courseId);
14333
14401
  if (existing?.status.state === "ready" && existing.localDB) {
14334
- const stale = await this.isLocalEpochStale(courseId, existing.localDB);
14335
- if (!stale) {
14336
- return;
14337
- }
14338
- logger.info(
14339
- `[CourseSyncService] Remote DB epoch changed for course ${courseId} \u2014 destroying stale local replica`
14340
- );
14341
- try {
14342
- await existing.localDB.destroy();
14343
- } catch {
14344
- }
14345
- existing.localDB = null;
14346
- existing.readyPromise = null;
14402
+ return;
14347
14403
  }
14348
14404
  if (existing?.status.state === "disabled") {
14349
14405
  return;
@@ -14357,9 +14413,104 @@ var init_CourseSyncService = __esm({
14357
14413
  readyPromise: null
14358
14414
  };
14359
14415
  this.entries.set(courseId, entry);
14360
- entry.readyPromise = this.performSync(courseId, entry, forceEnabled);
14416
+ entry.readyPromise = this.startSync(courseId, entry, forceEnabled);
14361
14417
  return entry.readyPromise;
14362
14418
  }
14419
+ /**
14420
+ * A replica completed on an earlier page load is ready now, refreshed in the
14421
+ * background; anything else goes through a full performSync.
14422
+ */
14423
+ async startSync(courseId, entry, forceEnabled) {
14424
+ const localDB = new pouchdb_setup_default(this.localDBName(courseId));
14425
+ if (await this.hasSyncMarker(localDB)) {
14426
+ entry.localDB = localDB;
14427
+ entry.status = { state: "ready" };
14428
+ entry.readyPromise = null;
14429
+ perfMark("sk:course-sync-ready", { courseId, from: "marker" });
14430
+ logger.info(
14431
+ `[CourseSyncService] Using this device's replica of course ${courseId}; refreshing in the background`
14432
+ );
14433
+ void this.refreshInBackground(courseId, entry, forceEnabled);
14434
+ return;
14435
+ }
14436
+ return this.performSync(courseId, entry, forceEnabled);
14437
+ }
14438
+ /**
14439
+ * Bring a ready replica up to date without taking it away from readers.
14440
+ * Failures leave it ready (and outdated).
14441
+ */
14442
+ async refreshInBackground(courseId, entry, forceEnabled) {
14443
+ const localDB = entry.localDB;
14444
+ try {
14445
+ if (!forceEnabled && !await this.checkLocalSyncEnabled(courseId)) {
14446
+ await this.clearSyncMarker(localDB);
14447
+ logger.info(
14448
+ `[CourseSyncService] Local sync no longer enabled for course ${courseId}; replica kept for this page only`
14449
+ );
14450
+ return;
14451
+ }
14452
+ if (await this.isLocalEpochStale(courseId, localDB)) {
14453
+ await this.clearSyncMarker(localDB);
14454
+ logger.info(
14455
+ `[CourseSyncService] Remote DB recreated for course ${courseId}: keeping the outdated replica for this page; it is rebuilt on the next page load`
14456
+ );
14457
+ return;
14458
+ }
14459
+ const start = Date.now();
14460
+ const result = await this.replicate(this.getRemoteDB(courseId), localDB);
14461
+ const syncTimeMs = Date.now() - start;
14462
+ const warmStart = Date.now();
14463
+ await this.warmViewIndices(localDB);
14464
+ const viewWarmTimeMs = Date.now() - warmStart;
14465
+ await this.writeSyncMarker(localDB);
14466
+ entry.status = {
14467
+ state: "ready",
14468
+ docsReplicated: result.docs_written,
14469
+ syncTimeMs,
14470
+ viewWarmTimeMs
14471
+ };
14472
+ perfMark("sk:course-sync-refreshed", {
14473
+ courseId,
14474
+ docs: result.docs_written,
14475
+ syncTimeMs,
14476
+ viewWarmTimeMs
14477
+ });
14478
+ logger.info(
14479
+ `[CourseSyncService] Background refresh of course ${courseId}: ${result.docs_written} docs in ${syncTimeMs}ms, views ${viewWarmTimeMs}ms`
14480
+ );
14481
+ } catch (e) {
14482
+ logger.warn(
14483
+ `[CourseSyncService] Background refresh of course ${courseId} failed; replica kept as is: ${e}`
14484
+ );
14485
+ }
14486
+ }
14487
+ async hasSyncMarker(localDB) {
14488
+ try {
14489
+ await localDB.get(SYNC_MARKER_ID);
14490
+ return true;
14491
+ } catch {
14492
+ return false;
14493
+ }
14494
+ }
14495
+ async writeSyncMarker(localDB) {
14496
+ try {
14497
+ let _rev;
14498
+ try {
14499
+ _rev = (await localDB.get(SYNC_MARKER_ID))._rev;
14500
+ } catch {
14501
+ }
14502
+ await localDB.put({ _id: SYNC_MARKER_ID, _rev, completedAt: (/* @__PURE__ */ new Date()).toISOString() });
14503
+ } catch (e) {
14504
+ logger.warn(`[CourseSyncService] Could not write sync marker: ${e}`);
14505
+ }
14506
+ }
14507
+ async clearSyncMarker(localDB) {
14508
+ try {
14509
+ const marker = await localDB.get(SYNC_MARKER_ID);
14510
+ await localDB.remove(marker);
14511
+ } catch {
14512
+ }
14513
+ }
14363
14514
  /**
14364
14515
  * Get the local PouchDB for a course, or null if not available.
14365
14516
  *
@@ -14424,6 +14575,11 @@ var init_CourseSyncService = __esm({
14424
14575
  );
14425
14576
  const result = await this.replicate(remoteDB, localDB);
14426
14577
  const syncTimeMs = Date.now() - syncStart;
14578
+ perfMark("sk:course-sync-replicated", {
14579
+ courseId,
14580
+ docs: result.docs_written,
14581
+ ms: syncTimeMs
14582
+ });
14427
14583
  logger.info(
14428
14584
  `[CourseSyncService] Replication complete for course ${courseId}: ${result.docs_written} docs in ${syncTimeMs}ms`
14429
14585
  );
@@ -14434,12 +14590,14 @@ var init_CourseSyncService = __esm({
14434
14590
  logger.info(
14435
14591
  `[CourseSyncService] View indices warmed for course ${courseId} in ${viewWarmTimeMs}ms`
14436
14592
  );
14593
+ await this.writeSyncMarker(localDB);
14437
14594
  entry.status = {
14438
14595
  state: "ready",
14439
14596
  docsReplicated: result.docs_written,
14440
14597
  syncTimeMs,
14441
14598
  viewWarmTimeMs
14442
14599
  };
14600
+ perfMark("sk:course-sync-ready", { courseId, from: "sync", viewWarmTimeMs });
14443
14601
  } catch (e) {
14444
14602
  const errorMsg = e instanceof Error ? e.message : String(e);
14445
14603
  logger.error(
@@ -14527,7 +14685,8 @@ var init_CourseSyncService = __esm({
14527
14685
  try {
14528
14686
  localEpoch = await localDB.get("db-epoch");
14529
14687
  } catch {
14530
- return true;
14688
+ const info = await localDB.info();
14689
+ return info.doc_count > 0 || !!info.update_seq;
14531
14690
  }
14532
14691
  return remoteEpoch.epoch !== localEpoch.epoch;
14533
14692
  } catch {
@@ -14538,7 +14697,7 @@ var init_CourseSyncService = __esm({
14538
14697
  * Get a remote PouchDB handle for a course.
14539
14698
  */
14540
14699
  getRemoteDB(courseId) {
14541
- return getCourseDB2(courseId);
14700
+ return getCourseDB(courseId);
14542
14701
  }
14543
14702
  /**
14544
14703
  * Local DB naming convention.
@@ -14574,6 +14733,13 @@ var init_PouchDataLayerProvider = __esm({
14574
14733
  // the scoped list of courseIDs for a UI focused on a specific course
14575
14734
  // or group of courses
14576
14735
  _courseIDs = [];
14736
+ /**
14737
+ * One CourseDB per course, so its caches (navigator, ELO pool, tags) last
14738
+ * across sessions and card hydration. Rebuilt when the local replica it reads
14739
+ * from changes (becomes ready, or is replaced); a session keeps the instance
14740
+ * it started with.
14741
+ */
14742
+ _courseDBs = /* @__PURE__ */ new Map();
14577
14743
  constructor(coursIDs) {
14578
14744
  if (coursIDs) {
14579
14745
  this._courseIDs = coursIDs;
@@ -14605,7 +14771,11 @@ var init_PouchDataLayerProvider = __esm({
14605
14771
  }
14606
14772
  getCourseDB(courseId) {
14607
14773
  const localDB = CourseSyncService.getInstance().getLocalDB(courseId);
14608
- return new CourseDB(courseId, async () => this.getUserDB(), localDB ?? void 0);
14774
+ const cached = this._courseDBs.get(courseId);
14775
+ if (cached && cached.localDB === localDB) return cached.db;
14776
+ const db = new CourseDB(courseId, async () => this.getUserDB(), localDB ?? void 0);
14777
+ this._courseDBs.set(courseId, { db, localDB });
14778
+ return db;
14609
14779
  }
14610
14780
  /**
14611
14781
  * Trigger local sync for a course. Call during app initialization or
@@ -16421,6 +16591,8 @@ __export(index_exports, {
16421
16591
  newInterval: () => newInterval,
16422
16592
  newSessionId: () => newSessionId,
16423
16593
  parseCardHistoryID: () => parseCardHistoryID,
16594
+ perfMark: () => perfMark,
16595
+ perfMeasure: () => perfMeasure,
16424
16596
  pipelineDebugAPI: () => pipelineDebugAPI,
16425
16597
  planPipeline: () => planPipeline,
16426
16598
  processCustomQuestionsData: () => processCustomQuestionsData,
@@ -16865,6 +17037,8 @@ init_userDBKeys();
16865
17037
  newInterval,
16866
17038
  newSessionId,
16867
17039
  parseCardHistoryID,
17040
+ perfMark,
17041
+ perfMeasure,
16868
17042
  pipelineDebugAPI,
16869
17043
  planPipeline,
16870
17044
  processCustomQuestionsData,