@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
@@ -1,6 +1,6 @@
1
1
  import { Status, CourseConfig, SkuilderCourseData as SkuilderCourseData$1, CourseElo, DataShape, TagFilter } from '@vue-skuilder/common';
2
2
  import { Moment } from 'moment';
3
- import { S as SkuilderCourseData, i as DocTypePrefixes, D as DocType, Q as QualifiedCardID, T as TagStub, a as Tag, e as CardHistory, c as CardRecord, d as QuestionRecord } from './types-legacy-fT5Y1Wuy.js';
3
+ import { S as SkuilderCourseData, f as DocTypePrefixes, D as DocType, Q as QualifiedCardID, T as TagStub, a as Tag, e as CardHistory, c as CardRecord, d as QuestionRecord } from './types-legacy-DdVjg81H.js';
4
4
 
5
5
  interface DataLayerResult {
6
6
  status: Status;
@@ -106,6 +106,11 @@ interface CourseInfo {
106
106
  registeredUsers: number;
107
107
  }
108
108
  interface CourseDBInterface extends NavigationStrategyManager, StudyContentSource {
109
+ /**
110
+ * Whether reads go to a local replica rather than the server. Optional: only
111
+ * implementations with both (couch) report it; perf marks read it.
112
+ */
113
+ readonly readsLocal?: boolean;
109
114
  /**
110
115
  * Get course config
111
116
  */
@@ -1578,6 +1578,12 @@ var init_prescribed = __esm({
1578
1578
  PrescribedCardsGenerator = class extends ContentNavigator {
1579
1579
  name;
1580
1580
  config;
1581
+ /**
1582
+ * Course-wide reads that don't change within a navigator's lifetime (the
1583
+ * navigator is cached per CourseDB, minutes), loaded once, not per run.
1584
+ */
1585
+ _cardsByTag = null;
1586
+ _hierarchyConfigs = null;
1581
1587
  constructor(user, course, strategyData) {
1582
1588
  super(user, course, strategyData);
1583
1589
  this.name = strategyData.name || "Prescribed Cards";
@@ -1610,20 +1616,7 @@ var init_prescribed = __esm({
1610
1616
  const allSupportIds = dedupe(this.config.groups.flatMap((g) => g.supportCardIds ?? []));
1611
1617
  const allRelevantIds = dedupe([...allTargetIds, ...allSupportIds]);
1612
1618
  const tagsByCard = allRelevantIds.length > 0 ? await this.course.getAppliedTagsBatch(allRelevantIds) : /* @__PURE__ */ new Map();
1613
- const courseTagDocs = await this.course.getCourseTagStubs().catch(
1614
- () => ({
1615
- rows: [],
1616
- offset: 0,
1617
- total_rows: 0
1618
- })
1619
- );
1620
- const cardsByTag = /* @__PURE__ */ new Map();
1621
- for (const row of courseTagDocs.rows ?? []) {
1622
- const tagDoc = row.doc;
1623
- if (tagDoc?.name && Array.isArray(tagDoc.taggedCards)) {
1624
- cardsByTag.set(tagDoc.name, [...tagDoc.taggedCards]);
1625
- }
1626
- }
1619
+ const cardsByTag = await this.loadCardsByTag();
1627
1620
  const nextState = {
1628
1621
  updatedAt: isoNow(),
1629
1622
  groups: {}
@@ -1863,7 +1856,33 @@ var init_prescribed = __esm({
1863
1856
  return { groups: [] };
1864
1857
  }
1865
1858
  }
1866
- async loadHierarchyConfigs() {
1859
+ /** Tag name → tagged card IDs, from the course's tag docs (once per instance). */
1860
+ loadCardsByTag() {
1861
+ if (!this._cardsByTag) {
1862
+ this._cardsByTag = this.course.getCourseTagStubs().then((docs) => {
1863
+ const cardsByTag = /* @__PURE__ */ new Map();
1864
+ for (const row of docs.rows ?? []) {
1865
+ const tagDoc = row.doc;
1866
+ if (tagDoc?.name && Array.isArray(tagDoc.taggedCards)) {
1867
+ cardsByTag.set(tagDoc.name, [...tagDoc.taggedCards]);
1868
+ }
1869
+ }
1870
+ return cardsByTag;
1871
+ }).catch((e) => {
1872
+ this._cardsByTag = null;
1873
+ logger.debug(`[Prescribed] Failed to load tag docs: ${e}`);
1874
+ return /* @__PURE__ */ new Map();
1875
+ });
1876
+ }
1877
+ return this._cardsByTag;
1878
+ }
1879
+ loadHierarchyConfigs() {
1880
+ if (!this._hierarchyConfigs) {
1881
+ this._hierarchyConfigs = this.fetchHierarchyConfigs();
1882
+ }
1883
+ return this._hierarchyConfigs;
1884
+ }
1885
+ async fetchHierarchyConfigs() {
1867
1886
  try {
1868
1887
  const strategies = await this.course.getAllNavigationStrategies();
1869
1888
  return strategies.filter((s) => s.implementingClass === "hierarchyDefinition").map((s) => {
@@ -1877,6 +1896,7 @@ var init_prescribed = __esm({
1877
1896
  }
1878
1897
  });
1879
1898
  } catch (e) {
1899
+ this._hierarchyConfigs = null;
1880
1900
  logger.debug(`[Prescribed] Failed to load hierarchy configs: ${e}`);
1881
1901
  return [];
1882
1902
  }
@@ -3755,8 +3775,10 @@ var init_updateQueue = __esm({
3755
3775
  init_logger();
3756
3776
  UpdateQueue = class extends Loggable {
3757
3777
  _className = "UpdateQueue";
3758
- pendingUpdates = {};
3759
- inprogressUpdates = {};
3778
+ /** Updates not yet taken by a write, per doc. */
3779
+ pending = /* @__PURE__ */ new Map();
3780
+ /** Docs with a drain loop running. */
3781
+ draining = /* @__PURE__ */ new Set();
3760
3782
  readDB;
3761
3783
  // Database for read operations
3762
3784
  writeDB;
@@ -3774,6 +3796,9 @@ var init_updateQueue = __esm({
3774
3796
  * **Error Handling Pattern:**
3775
3797
  * - This method does NOT create documents if they don't exist
3776
3798
  * - Callers are responsible for handling 404 errors and creating documents
3799
+ * - A rejected update is dropped from the queue: a caller that creates the
3800
+ * doc after a 404 has already applied its change and must not see it
3801
+ * re-applied by a later update to the same doc
3777
3802
  * - This design maintains separation of concerns (UpdateQueue handles conflicts, callers handle lifecycle)
3778
3803
  *
3779
3804
  * @example
@@ -3790,12 +3815,16 @@ var init_updateQueue = __esm({
3790
3815
  */
3791
3816
  update(id, update) {
3792
3817
  logger.debug(`Update requested on doc: ${id}`);
3793
- if (this.pendingUpdates[id]) {
3794
- this.pendingUpdates[id].push(update);
3795
- } else {
3796
- this.pendingUpdates[id] = [update];
3797
- }
3798
- return this.applyUpdates(id);
3818
+ return new Promise((resolve, reject) => {
3819
+ const queue = this.pending.get(id) ?? [];
3820
+ queue.push({
3821
+ update,
3822
+ resolve,
3823
+ reject
3824
+ });
3825
+ this.pending.set(id, queue);
3826
+ if (!this.draining.has(id)) void this.drain(id);
3827
+ });
3799
3828
  }
3800
3829
  constructor(readDB, writeDB) {
3801
3830
  super();
@@ -3806,64 +3835,56 @@ var init_updateQueue = __esm({
3806
3835
  logger.debug(`db info: ${JSON.stringify(i)}`);
3807
3836
  });
3808
3837
  }
3809
- async applyUpdates(id) {
3810
- logger.debug(`Applying updates on doc: ${id}`);
3811
- if (this.inprogressUpdates[id]) {
3812
- while (this.inprogressUpdates[id]) {
3813
- await new Promise((resolve) => setTimeout(resolve, Math.random() * 50));
3838
+ /** Writes the doc's queued updates, batch by batch, until none are left. */
3839
+ async drain(id) {
3840
+ this.draining.add(id);
3841
+ try {
3842
+ let batch;
3843
+ while ((batch = this.pending.get(id)) && batch.length > 0) {
3844
+ this.pending.delete(id);
3845
+ try {
3846
+ const doc = await this.write(
3847
+ id,
3848
+ batch.map((p) => p.update)
3849
+ );
3850
+ batch.forEach((p) => p.resolve(doc));
3851
+ } catch (e) {
3852
+ batch.forEach((p) => p.reject(e));
3853
+ }
3814
3854
  }
3815
- return this.applyUpdates(id);
3816
- } else {
3817
- if (this.pendingUpdates[id] && this.pendingUpdates[id].length > 0) {
3818
- this.inprogressUpdates[id] = true;
3819
- const MAX_RETRIES = 5;
3820
- for (let i = 0; i < MAX_RETRIES; i++) {
3821
- try {
3822
- const doc = await this.readDB.get(id);
3823
- let updatedDoc = { ...doc };
3824
- const updatesToApply = [...this.pendingUpdates[id]];
3825
- for (const update of updatesToApply) {
3826
- if (typeof update === "function") {
3827
- updatedDoc = { ...updatedDoc, ...update(updatedDoc) };
3828
- } else {
3829
- updatedDoc = {
3830
- ...updatedDoc,
3831
- ...update
3832
- };
3833
- }
3834
- }
3835
- await this.writeDB.put(updatedDoc);
3836
- this.pendingUpdates[id].splice(0, updatesToApply.length);
3837
- if (this.pendingUpdates[id].length === 0) {
3838
- this.inprogressUpdates[id] = false;
3839
- delete this.inprogressUpdates[id];
3840
- } else {
3841
- return this.applyUpdates(id);
3842
- }
3843
- return updatedDoc;
3844
- } catch (e) {
3845
- if (e.name === "conflict" && i < MAX_RETRIES - 1) {
3846
- logger.warn(`Conflict on update for doc ${id}, retry #${i + 1}`);
3847
- await new Promise((res) => setTimeout(res, 50 * Math.random()));
3848
- } else if (e.name === "not_found" && i === 0) {
3849
- logger.warn(`Update failed for ${id} - does not exist. Throwing to caller.`);
3850
- delete this.inprogressUpdates[id];
3851
- throw e;
3852
- } else {
3853
- delete this.inprogressUpdates[id];
3854
- if (this.pendingUpdates[id]) {
3855
- delete this.pendingUpdates[id];
3856
- }
3857
- logger.error(`Error on attemped update (retry ${i}): ${JSON.stringify(e)}`);
3858
- throw e;
3859
- }
3860
- }
3855
+ } finally {
3856
+ this.draining.delete(id);
3857
+ }
3858
+ }
3859
+ /** One read-apply-put of `updates`, retried on conflict against a fresh read. */
3860
+ async write(id, updates) {
3861
+ logger.debug(`Applying ${updates.length} update(s) on doc: ${id}`);
3862
+ const MAX_RETRIES = 5;
3863
+ for (let i = 0; i < MAX_RETRIES; i++) {
3864
+ try {
3865
+ const doc = await this.readDB.get(id);
3866
+ let updatedDoc = {
3867
+ ...doc
3868
+ };
3869
+ for (const update of updates) {
3870
+ updatedDoc = typeof update === "function" ? { ...updatedDoc, ...update(updatedDoc) } : { ...updatedDoc, ...update };
3871
+ }
3872
+ const res = await this.writeDB.put(updatedDoc);
3873
+ return { ...updatedDoc, _rev: res.rev };
3874
+ } catch (e) {
3875
+ if (e.name === "conflict" && i < MAX_RETRIES - 1) {
3876
+ logger.warn(`Conflict on update for doc ${id}, retry #${i + 1}`);
3877
+ await new Promise((res) => setTimeout(res, 50 * Math.random()));
3878
+ } else if (e.name === "not_found" && i === 0) {
3879
+ logger.warn(`Update failed for ${id} - does not exist. Throwing to caller.`);
3880
+ throw e;
3881
+ } else {
3882
+ logger.error(`Error on attemped update (retry ${i}): ${JSON.stringify(e)}`);
3883
+ throw e;
3861
3884
  }
3862
- throw new Error(`UpdateQueue failed for doc ${id} after ${MAX_RETRIES} retries.`);
3863
- } else {
3864
- throw new Error(`Empty Updates Queue Triggered`);
3865
3885
  }
3866
3886
  }
3887
+ throw new Error(`UpdateQueue failed for doc ${id} after ${MAX_RETRIES} retries.`);
3867
3888
  }
3868
3889
  };
3869
3890
  }
@@ -3982,6 +4003,23 @@ var init_WeightedFilter = __esm({
3982
4003
  }
3983
4004
  });
3984
4005
 
4006
+ // src/util/perfMarks.ts
4007
+ function perfMeasure(name, start, end, detail) {
4008
+ try {
4009
+ globalThis.performance?.measure(name, {
4010
+ start,
4011
+ ...end !== void 0 ? { end } : {},
4012
+ ...detail ? { detail } : {}
4013
+ });
4014
+ } catch {
4015
+ }
4016
+ }
4017
+ var init_perfMarks = __esm({
4018
+ "src/util/perfMarks.ts"() {
4019
+ "use strict";
4020
+ }
4021
+ });
4022
+
3985
4023
  // src/core/orchestration/gradient.ts
3986
4024
  function aggregateOutcomesForGradient(outcomes, strategyId) {
3987
4025
  const observations = [];
@@ -4458,6 +4496,7 @@ var init_Pipeline = __esm({
4458
4496
  import_common6 = require("@vue-skuilder/common");
4459
4497
  init_navigators();
4460
4498
  init_logger();
4499
+ init_perfMarks();
4461
4500
  init_orchestration();
4462
4501
  init_PipelineDebugger();
4463
4502
  init_diversityRerank();
@@ -4661,6 +4700,13 @@ var init_Pipeline = __esm({
4661
4700
  logger.info(
4662
4701
  `[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)})`
4663
4702
  );
4703
+ perfMeasure("sk:pipeline-run", t0, tFilter, {
4704
+ context: Math.round(tContext - t0),
4705
+ generate: Math.round(tGenerate - tContext),
4706
+ hydrate: Math.round(tHydrate - tGenerate),
4707
+ filter: Math.round(tFilter - tHydrate),
4708
+ binding: this.course?.readsLocal === void 0 ? "unknown" : this.course.readsLocal ? "local" : "remote"
4709
+ });
4664
4710
  const topScores = result.slice(0, 3).map((c) => c.score);
4665
4711
  logExecutionSummary(
4666
4712
  this.generator.name,
@@ -5668,17 +5714,6 @@ var init_PipelineAssembler = __esm({
5668
5714
  function randIntWeightedTowardZero(n) {
5669
5715
  return Math.floor(Math.random() * Math.random() * Math.random() * n);
5670
5716
  }
5671
- async function getCourseTagStubs(courseID) {
5672
- logger.debug(`Getting tag stubs for course: ${courseID}`);
5673
- const stubs = await filterAllDocsByPrefix2(
5674
- getCourseDB(courseID),
5675
- "TAG" /* TAG */.valueOf() + "-"
5676
- );
5677
- stubs.rows.forEach((row) => {
5678
- logger.debug(` Tag stub for doc: ${row.id}`);
5679
- });
5680
- return stubs;
5681
- }
5682
5717
  async function createTag(courseID, tagName, author) {
5683
5718
  logger.debug(`Creating tag: ${tagName}...`);
5684
5719
  const tagID = getTagID(tagName);
@@ -5716,26 +5751,22 @@ async function removeTagFromCard(courseID, cardID, tagID) {
5716
5751
  });
5717
5752
  return courseDB.put(tag);
5718
5753
  }
5719
- async function getAppliedTags(id_course, id_card) {
5720
- const db = getCourseDB(id_course);
5721
- const result = await db.query("getTags", {
5722
- startkey: id_card,
5723
- endkey: id_card
5724
- // include_docs: true
5725
- });
5726
- return result;
5727
- }
5728
5754
  async function updateCredentialledCourseConfig(courseID, config) {
5729
5755
  logger.debug(`Updating course config:
5730
5756
 
5731
5757
  ${JSON.stringify(config)}
5732
5758
  `);
5733
5759
  const db = getCourseDB(courseID);
5760
+ invalidateCourseConfigCache(courseID);
5734
5761
  const old = await getCredentialledCourseConfig(courseID);
5735
- return await db.put({
5736
- ...config,
5737
- _rev: old._rev
5738
- });
5762
+ try {
5763
+ return await db.put({
5764
+ ...config,
5765
+ _rev: old._rev
5766
+ });
5767
+ } finally {
5768
+ invalidateCourseConfigCache(courseID);
5769
+ }
5739
5770
  }
5740
5771
  function isSuccessRow(row) {
5741
5772
  return "doc" in row && row.doc !== null && row.doc !== void 0;
@@ -5786,6 +5817,10 @@ var init_courseDB = __esm({
5786
5817
  * values may be stale, so read-modify-write cycles must go through
5787
5818
  * the remote DB to avoid conflicts).
5788
5819
  */
5820
+ /** Reads go to this device's replica (perf marks report it as the session's binding). */
5821
+ get readsLocal() {
5822
+ return this.db !== this.remoteDB;
5823
+ }
5789
5824
  constructor(id, userLookup, localDB) {
5790
5825
  this.id = id;
5791
5826
  const remote = getCourseDB(this.id);
@@ -5992,12 +6027,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
5992
6027
  }
5993
6028
  }
5994
6029
  async getAppliedTags(cardId) {
5995
- const ret = await getAppliedTags(this.id, cardId);
5996
- if (ret) {
5997
- return ret;
5998
- } else {
5999
- throw new Error(`Failed to find tags for card ${this.id}-${cardId}`);
6000
- }
6030
+ return this.db.query("getTags", { startkey: cardId, endkey: cardId });
6001
6031
  }
6002
6032
  async getAppliedTagsBatch(cardIds) {
6003
6033
  if (cardIds.length === 0) {
@@ -6054,7 +6084,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
6054
6084
  return await updateTag(tag);
6055
6085
  }
6056
6086
  async getCourseTagStubs() {
6057
- return getCourseTagStubs(this.id);
6087
+ return filterAllDocsByPrefix2(this.db, "TAG" /* TAG */.valueOf() + "-");
6058
6088
  }
6059
6089
  async addNote(codeCourse, shape, data, author, tags, uploads, elo = (0, import_common7.blankCourseElo)()) {
6060
6090
  try {
@@ -8037,6 +8067,18 @@ Currently logged-in as ${this._username}.`
8037
8067
  update(id, update) {
8038
8068
  return this.updateQueue.update(id, update);
8039
8069
  }
8070
+ /**
8071
+ * Create a default doc after a 404. Concurrent first reads (e.g. two
8072
+ * components on a brand-new user) both see the 404 and both create; the
8073
+ * loser's conflict just means the doc now exists, which is what it wanted.
8074
+ */
8075
+ async putDefaultUnlessCreated(doc) {
8076
+ try {
8077
+ await this.localDB.put(doc);
8078
+ } catch (e) {
8079
+ if (e.status !== 409) throw e;
8080
+ }
8081
+ }
8040
8082
  async getCourseRegistrationsDoc() {
8041
8083
  logger.debug(`Fetching courseRegistrations for ${this.getUsername()}`);
8042
8084
  let ret;
@@ -8053,7 +8095,7 @@ Currently logged-in as ${this._username}.`
8053
8095
  `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.`
8054
8096
  );
8055
8097
  }
8056
- await this.localDB.put({
8098
+ await this.putDefaultUnlessCreated({
8057
8099
  _id: _BaseUser.DOC_IDS.COURSE_REGISTRATIONS,
8058
8100
  courses: [],
8059
8101
  studyWeight: {}
@@ -8300,7 +8342,7 @@ Currently logged-in as ${this._username}.`
8300
8342
  `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.`
8301
8343
  );
8302
8344
  }
8303
- await this.localDB.put(defaultConfig);
8345
+ await this.putDefaultUnlessCreated(defaultConfig);
8304
8346
  return this.getConfig();
8305
8347
  } else {
8306
8348
  logger.error(`Error setting user default config:`, e);
@@ -8561,22 +8603,20 @@ Currently logged-in as ${this._username}.`
8561
8603
  async putCardRecord(record) {
8562
8604
  const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);
8563
8605
  record.timeStamp = import_moment6.default.utc(record.timeStamp).toString();
8564
- try {
8565
- const cardHistory = await this.update(
8566
- cardHistoryID,
8567
- function(h) {
8568
- h.records.push(record);
8569
- h.bestInterval = h.bestInterval || 0;
8570
- if (areQuestionRecords(h)) {
8571
- h.lapses = getLapses(h.records);
8572
- h.streak = getStreak(h.records);
8573
- } else {
8574
- h.lapses = h.lapses || 0;
8575
- h.streak = h.streak || 0;
8576
- }
8577
- return h;
8578
- }
8579
- );
8606
+ const append = (h) => {
8607
+ h.records.push(record);
8608
+ h.bestInterval = h.bestInterval || 0;
8609
+ if (areQuestionRecords(h)) {
8610
+ h.lapses = getLapses(h.records);
8611
+ h.streak = getStreak(h.records);
8612
+ } else {
8613
+ h.lapses = h.lapses || 0;
8614
+ h.streak = h.streak || 0;
8615
+ }
8616
+ return h;
8617
+ };
8618
+ const appendToExisting = async () => {
8619
+ const cardHistory = await this.update(cardHistoryID, append);
8580
8620
  cardHistory.records = cardHistory.records.map((record2) => {
8581
8621
  const ret = {
8582
8622
  ...record2
@@ -8585,6 +8625,9 @@ Currently logged-in as ${this._username}.`
8585
8625
  return ret;
8586
8626
  });
8587
8627
  return cardHistory;
8628
+ };
8629
+ try {
8630
+ return await appendToExisting();
8588
8631
  } catch (e) {
8589
8632
  const reason = e;
8590
8633
  if (reason.status === 404) {
@@ -8601,6 +8644,9 @@ Currently logged-in as ${this._username}.`
8601
8644
  const putResult = await this.writeDB.put(initCardHistory);
8602
8645
  return { ...initCardHistory, _rev: putResult.rev };
8603
8646
  } catch (creationError) {
8647
+ if (creationError.name === "conflict") {
8648
+ return appendToExisting();
8649
+ }
8604
8650
  throw new Error(
8605
8651
  `Failed to create CardHistory for ${cardHistoryID}. Reason: ${creationError}`
8606
8652
  );
@@ -8915,7 +8961,7 @@ var init_common = __esm({
8915
8961
 
8916
8962
  // src/impl/couch/courseAPI.ts
8917
8963
  async function addNote55(courseID, codeCourse, shape, data, author, tags, uploads, elo = (0, import_common12.blankCourseElo)()) {
8918
- const db = getCourseDB2(courseID);
8964
+ const db = getCourseDB(courseID);
8919
8965
  const payload = (0, import_common13.prepareNote55)(courseID, codeCourse, shape, data, author, tags, uploads);
8920
8966
  const _id = `${DocTypePrefixes["DISPLAYABLE_DATA" /* DISPLAYABLE_DATA */]}-${(0, import_uuid.v4)()}`;
8921
8967
  const result = await db.put({ ...payload, _id });
@@ -8988,7 +9034,7 @@ async function createCard(questionViewName, courseID, dsDescriptor, noteID, tags
8988
9034
  }
8989
9035
  }
8990
9036
  async function addCard(courseID, course, id_displayable_data, id_view, elo, tags, author) {
8991
- const db = getCourseDB2(courseID);
9037
+ const db = getCourseDB(courseID);
8992
9038
  const _id = `${DocTypePrefixes["CARD" /* CARD */]}-${(0, import_uuid.v4)()}`;
8993
9039
  const card = await db.put({
8994
9040
  _id,
@@ -9005,21 +9051,33 @@ async function addCard(courseID, course, id_displayable_data, id_view, elo, tags
9005
9051
  }
9006
9052
  return card;
9007
9053
  }
9054
+ function invalidateCourseConfigCache(courseID) {
9055
+ courseConfigCache.delete(courseID);
9056
+ }
9008
9057
  async function getCredentialledCourseConfig(courseID) {
9009
- try {
9010
- const db = getCourseDB2(courseID);
9058
+ const hit = courseConfigCache.get(courseID);
9059
+ if (hit && Date.now() - hit.at < COURSE_CONFIG_TTL_MS) {
9060
+ return structuredClone(await hit.config);
9061
+ }
9062
+ const config = (async () => {
9063
+ const db = getCourseDB(courseID);
9011
9064
  const ret = await db.get("CourseConfig");
9012
9065
  ret.courseID = courseID;
9013
- logger.info(`Returning course config: ${JSON.stringify(ret)}`);
9066
+ logger.debug(`Fetched course config for ${courseID}`);
9014
9067
  return ret;
9068
+ })();
9069
+ courseConfigCache.set(courseID, { at: Date.now(), config });
9070
+ try {
9071
+ return structuredClone(await config);
9015
9072
  } catch (e) {
9073
+ courseConfigCache.delete(courseID);
9016
9074
  logger.error(`Error fetching config for ${courseID}:`, e);
9017
9075
  throw e;
9018
9076
  }
9019
9077
  }
9020
9078
  async function addTagToCard(courseID, cardID, tagID, author, updateELO = true) {
9021
9079
  const prefixedTagID = getTagID(tagID);
9022
- const courseDB = getCourseDB2(courseID);
9080
+ const courseDB = getCourseDB(courseID);
9023
9081
  const courseApi = new CourseDB(courseID, async () => {
9024
9082
  const dummySyncStrategy = {
9025
9083
  setupRemoteDB: () => null,
@@ -9062,7 +9120,7 @@ async function addTagToCard(courseID, cardID, tagID, author, updateELO = true) {
9062
9120
  }
9063
9121
  async function updateCardElo(courseID, cardID, elo) {
9064
9122
  if (elo) {
9065
- const cDB = getCourseDB2(courseID);
9123
+ const cDB = getCourseDB(courseID);
9066
9124
  const card = await cDB.get(cardID);
9067
9125
  logger.debug(`Replacing ${JSON.stringify(card.elo)} with ${JSON.stringify(elo)}`);
9068
9126
  card.elo = elo;
@@ -9077,20 +9135,11 @@ function getTagID(tagName) {
9077
9135
  return tagPrefix + tagName;
9078
9136
  }
9079
9137
  }
9080
- function getCourseDB2(courseID) {
9081
- const dbName = `coursedb-${courseID}`;
9082
- return new pouchdb_setup_default(
9083
- ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + dbName,
9084
- createPouchDBConfig()
9085
- );
9086
- }
9087
- var import_common11, import_common12, import_common13, import_uuid, AlreadyTaggedErr;
9138
+ var import_common11, import_common12, import_common13, import_uuid, COURSE_CONFIG_TTL_MS, courseConfigCache, AlreadyTaggedErr;
9088
9139
  var init_courseAPI = __esm({
9089
9140
  "src/impl/couch/courseAPI.ts"() {
9090
9141
  "use strict";
9091
- init_pouchdb_setup();
9092
9142
  init_couch();
9093
- init_factory();
9094
9143
  import_common11 = require("@vue-skuilder/common");
9095
9144
  import_common12 = require("@vue-skuilder/common");
9096
9145
  init_courseDB();
@@ -9099,6 +9148,8 @@ var init_courseAPI = __esm({
9099
9148
  init_common();
9100
9149
  init_logger();
9101
9150
  import_uuid = require("uuid");
9151
+ COURSE_CONFIG_TTL_MS = 5 * 60 * 1e3;
9152
+ courseConfigCache = /* @__PURE__ */ new Map();
9102
9153
  AlreadyTaggedErr = class extends Error {
9103
9154
  constructor(message) {
9104
9155
  super(message);
@@ -9145,10 +9196,13 @@ function createPouchDBConfig() {
9145
9196
  return pouchDBincludeCredentialsConfig;
9146
9197
  }
9147
9198
  function getCourseDB(courseID) {
9148
- return new pouchdb_setup_default(
9149
- ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + "coursedb-" + courseID,
9150
- createPouchDBConfig()
9151
- );
9199
+ const url = ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + "coursedb-" + courseID;
9200
+ let db = courseDBHandles.get(url);
9201
+ if (!db) {
9202
+ db = new pouchdb_setup_default(url, { ...createPouchDBConfig(), skip_setup: true });
9203
+ courseDBHandles.set(url, db);
9204
+ }
9205
+ return db;
9152
9206
  }
9153
9207
  function filterAllDocsByPrefix2(db, prefix, opts) {
9154
9208
  const options = {
@@ -9167,7 +9221,7 @@ function getStartAndEndKeys2(key) {
9167
9221
  endkey: key + "\uFFF0"
9168
9222
  };
9169
9223
  }
9170
- var import_cross_fetch, import_moment7, GUEST_LOCAL_DB, localUserDB, pouchDBincludeCredentialsConfig, REVIEW_TIME_FORMAT2;
9224
+ var import_cross_fetch, import_moment7, GUEST_LOCAL_DB, localUserDB, pouchDBincludeCredentialsConfig, courseDBHandles, REVIEW_TIME_FORMAT2;
9171
9225
  var init_couch = __esm({
9172
9226
  "src/impl/couch/index.ts"() {
9173
9227
  "use strict";
@@ -9191,6 +9245,7 @@ var init_couch = __esm({
9191
9245
  return pouchdb_setup_default.fetch(url, opts);
9192
9246
  }
9193
9247
  };
9248
+ courseDBHandles = /* @__PURE__ */ new Map();
9194
9249
  REVIEW_TIME_FORMAT2 = "YYYY-MM-DD--kk:mm:ss-SSS";
9195
9250
  }
9196
9251
  });