@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.
Files changed (33) hide show
  1. package/dist/core/index.cjs +91 -70
  2. package/dist/core/index.cjs.map +1 -1
  3. package/dist/core/navigators/generators/prescribed.mjs +29 -11
  4. package/dist/core/navigators/generators/prescribed.mjs.map +1 -1
  5. package/dist/core/versionStamps.mjs +1 -1
  6. package/dist/impl/common/BaseUserDB.mjs +14 -2
  7. package/dist/impl/common/BaseUserDB.mjs.map +1 -1
  8. package/dist/impl/couch/CourseSyncService.mjs +88 -10
  9. package/dist/impl/couch/CourseSyncService.mjs.map +1 -1
  10. package/dist/impl/couch/PouchDataLayerProvider.mjs +16 -1
  11. package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -1
  12. package/dist/impl/couch/courseAPI.mjs +24 -10
  13. package/dist/impl/couch/courseAPI.mjs.map +1 -1
  14. package/dist/impl/couch/courseDB.mjs +15 -9
  15. package/dist/impl/couch/courseDB.mjs.map +1 -1
  16. package/dist/impl/couch/index.cjs +163 -62
  17. package/dist/impl/couch/index.cjs.map +1 -1
  18. package/dist/impl/couch/index.d.ts +22 -1
  19. package/dist/impl/couch/index.mjs +20 -3
  20. package/dist/impl/couch/index.mjs.map +1 -1
  21. package/dist/impl/static/index.cjs +39 -15
  22. package/dist/impl/static/index.cjs.map +1 -1
  23. package/dist/index.cjs +202 -92
  24. package/dist/index.cjs.map +1 -1
  25. package/package.json +3 -3
  26. package/src/core/navigators/generators/prescribed.ts +42 -16
  27. package/src/impl/common/BaseUserDB.ts +15 -2
  28. package/src/impl/couch/CourseSyncService.ts +130 -20
  29. package/src/impl/couch/PouchDataLayerProvider.ts +14 -1
  30. package/src/impl/couch/courseAPI.ts +26 -12
  31. package/src/impl/couch/courseDB.ts +20 -12
  32. package/src/impl/couch/index.ts +16 -5
  33. package/tests/impl/courseSync.test.ts +139 -0
@@ -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
  }
@@ -5668,17 +5688,6 @@ var init_PipelineAssembler = __esm({
5668
5688
  function randIntWeightedTowardZero(n) {
5669
5689
  return Math.floor(Math.random() * Math.random() * Math.random() * n);
5670
5690
  }
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
5691
  async function createTag(courseID, tagName, author) {
5683
5692
  logger.debug(`Creating tag: ${tagName}...`);
5684
5693
  const tagID = getTagID(tagName);
@@ -5716,26 +5725,22 @@ async function removeTagFromCard(courseID, cardID, tagID) {
5716
5725
  });
5717
5726
  return courseDB.put(tag);
5718
5727
  }
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
5728
  async function updateCredentialledCourseConfig(courseID, config) {
5729
5729
  logger.debug(`Updating course config:
5730
5730
 
5731
5731
  ${JSON.stringify(config)}
5732
5732
  `);
5733
5733
  const db = getCourseDB(courseID);
5734
+ invalidateCourseConfigCache(courseID);
5734
5735
  const old = await getCredentialledCourseConfig(courseID);
5735
- return await db.put({
5736
- ...config,
5737
- _rev: old._rev
5738
- });
5736
+ try {
5737
+ return await db.put({
5738
+ ...config,
5739
+ _rev: old._rev
5740
+ });
5741
+ } finally {
5742
+ invalidateCourseConfigCache(courseID);
5743
+ }
5739
5744
  }
5740
5745
  function isSuccessRow(row) {
5741
5746
  return "doc" in row && row.doc !== null && row.doc !== void 0;
@@ -5992,12 +5997,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
5992
5997
  }
5993
5998
  }
5994
5999
  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
- }
6000
+ return this.db.query("getTags", { startkey: cardId, endkey: cardId });
6001
6001
  }
6002
6002
  async getAppliedTagsBatch(cardIds) {
6003
6003
  if (cardIds.length === 0) {
@@ -6054,7 +6054,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
6054
6054
  return await updateTag(tag);
6055
6055
  }
6056
6056
  async getCourseTagStubs() {
6057
- return getCourseTagStubs(this.id);
6057
+ return filterAllDocsByPrefix2(this.db, "TAG" /* TAG */.valueOf() + "-");
6058
6058
  }
6059
6059
  async addNote(codeCourse, shape, data, author, tags, uploads, elo = (0, import_common7.blankCourseElo)()) {
6060
6060
  try {
@@ -8037,6 +8037,18 @@ Currently logged-in as ${this._username}.`
8037
8037
  update(id, update) {
8038
8038
  return this.updateQueue.update(id, update);
8039
8039
  }
8040
+ /**
8041
+ * Create a default doc after a 404. Concurrent first reads (e.g. two
8042
+ * components on a brand-new user) both see the 404 and both create; the
8043
+ * loser's conflict just means the doc now exists, which is what it wanted.
8044
+ */
8045
+ async putDefaultUnlessCreated(doc) {
8046
+ try {
8047
+ await this.localDB.put(doc);
8048
+ } catch (e) {
8049
+ if (e.status !== 409) throw e;
8050
+ }
8051
+ }
8040
8052
  async getCourseRegistrationsDoc() {
8041
8053
  logger.debug(`Fetching courseRegistrations for ${this.getUsername()}`);
8042
8054
  let ret;
@@ -8053,7 +8065,7 @@ Currently logged-in as ${this._username}.`
8053
8065
  `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
8066
  );
8055
8067
  }
8056
- await this.localDB.put({
8068
+ await this.putDefaultUnlessCreated({
8057
8069
  _id: _BaseUser.DOC_IDS.COURSE_REGISTRATIONS,
8058
8070
  courses: [],
8059
8071
  studyWeight: {}
@@ -8300,7 +8312,7 @@ Currently logged-in as ${this._username}.`
8300
8312
  `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
8313
  );
8302
8314
  }
8303
- await this.localDB.put(defaultConfig);
8315
+ await this.putDefaultUnlessCreated(defaultConfig);
8304
8316
  return this.getConfig();
8305
8317
  } else {
8306
8318
  logger.error(`Error setting user default config:`, e);
@@ -8915,7 +8927,7 @@ var init_common = __esm({
8915
8927
 
8916
8928
  // src/impl/couch/courseAPI.ts
8917
8929
  async function addNote55(courseID, codeCourse, shape, data, author, tags, uploads, elo = (0, import_common12.blankCourseElo)()) {
8918
- const db = getCourseDB2(courseID);
8930
+ const db = getCourseDB(courseID);
8919
8931
  const payload = (0, import_common13.prepareNote55)(courseID, codeCourse, shape, data, author, tags, uploads);
8920
8932
  const _id = `${DocTypePrefixes["DISPLAYABLE_DATA" /* DISPLAYABLE_DATA */]}-${(0, import_uuid.v4)()}`;
8921
8933
  const result = await db.put({ ...payload, _id });
@@ -8988,7 +9000,7 @@ async function createCard(questionViewName, courseID, dsDescriptor, noteID, tags
8988
9000
  }
8989
9001
  }
8990
9002
  async function addCard(courseID, course, id_displayable_data, id_view, elo, tags, author) {
8991
- const db = getCourseDB2(courseID);
9003
+ const db = getCourseDB(courseID);
8992
9004
  const _id = `${DocTypePrefixes["CARD" /* CARD */]}-${(0, import_uuid.v4)()}`;
8993
9005
  const card = await db.put({
8994
9006
  _id,
@@ -9005,21 +9017,33 @@ async function addCard(courseID, course, id_displayable_data, id_view, elo, tags
9005
9017
  }
9006
9018
  return card;
9007
9019
  }
9020
+ function invalidateCourseConfigCache(courseID) {
9021
+ courseConfigCache.delete(courseID);
9022
+ }
9008
9023
  async function getCredentialledCourseConfig(courseID) {
9009
- try {
9010
- const db = getCourseDB2(courseID);
9024
+ const hit = courseConfigCache.get(courseID);
9025
+ if (hit && Date.now() - hit.at < COURSE_CONFIG_TTL_MS) {
9026
+ return structuredClone(await hit.config);
9027
+ }
9028
+ const config = (async () => {
9029
+ const db = getCourseDB(courseID);
9011
9030
  const ret = await db.get("CourseConfig");
9012
9031
  ret.courseID = courseID;
9013
- logger.info(`Returning course config: ${JSON.stringify(ret)}`);
9032
+ logger.debug(`Fetched course config for ${courseID}`);
9014
9033
  return ret;
9034
+ })();
9035
+ courseConfigCache.set(courseID, { at: Date.now(), config });
9036
+ try {
9037
+ return structuredClone(await config);
9015
9038
  } catch (e) {
9039
+ courseConfigCache.delete(courseID);
9016
9040
  logger.error(`Error fetching config for ${courseID}:`, e);
9017
9041
  throw e;
9018
9042
  }
9019
9043
  }
9020
9044
  async function addTagToCard(courseID, cardID, tagID, author, updateELO = true) {
9021
9045
  const prefixedTagID = getTagID(tagID);
9022
- const courseDB = getCourseDB2(courseID);
9046
+ const courseDB = getCourseDB(courseID);
9023
9047
  const courseApi = new CourseDB(courseID, async () => {
9024
9048
  const dummySyncStrategy = {
9025
9049
  setupRemoteDB: () => null,
@@ -9062,7 +9086,7 @@ async function addTagToCard(courseID, cardID, tagID, author, updateELO = true) {
9062
9086
  }
9063
9087
  async function updateCardElo(courseID, cardID, elo) {
9064
9088
  if (elo) {
9065
- const cDB = getCourseDB2(courseID);
9089
+ const cDB = getCourseDB(courseID);
9066
9090
  const card = await cDB.get(cardID);
9067
9091
  logger.debug(`Replacing ${JSON.stringify(card.elo)} with ${JSON.stringify(elo)}`);
9068
9092
  card.elo = elo;
@@ -9077,20 +9101,11 @@ function getTagID(tagName) {
9077
9101
  return tagPrefix + tagName;
9078
9102
  }
9079
9103
  }
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;
9104
+ var import_common11, import_common12, import_common13, import_uuid, COURSE_CONFIG_TTL_MS, courseConfigCache, AlreadyTaggedErr;
9088
9105
  var init_courseAPI = __esm({
9089
9106
  "src/impl/couch/courseAPI.ts"() {
9090
9107
  "use strict";
9091
- init_pouchdb_setup();
9092
9108
  init_couch();
9093
- init_factory();
9094
9109
  import_common11 = require("@vue-skuilder/common");
9095
9110
  import_common12 = require("@vue-skuilder/common");
9096
9111
  init_courseDB();
@@ -9099,6 +9114,8 @@ var init_courseAPI = __esm({
9099
9114
  init_common();
9100
9115
  init_logger();
9101
9116
  import_uuid = require("uuid");
9117
+ COURSE_CONFIG_TTL_MS = 5 * 60 * 1e3;
9118
+ courseConfigCache = /* @__PURE__ */ new Map();
9102
9119
  AlreadyTaggedErr = class extends Error {
9103
9120
  constructor(message) {
9104
9121
  super(message);
@@ -9145,10 +9162,13 @@ function createPouchDBConfig() {
9145
9162
  return pouchDBincludeCredentialsConfig;
9146
9163
  }
9147
9164
  function getCourseDB(courseID) {
9148
- return new pouchdb_setup_default(
9149
- ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + "coursedb-" + courseID,
9150
- createPouchDBConfig()
9151
- );
9165
+ const url = ENV.COUCHDB_SERVER_PROTOCOL + "://" + ENV.COUCHDB_SERVER_URL + "coursedb-" + courseID;
9166
+ let db = courseDBHandles.get(url);
9167
+ if (!db) {
9168
+ db = new pouchdb_setup_default(url, { ...createPouchDBConfig(), skip_setup: true });
9169
+ courseDBHandles.set(url, db);
9170
+ }
9171
+ return db;
9152
9172
  }
9153
9173
  function filterAllDocsByPrefix2(db, prefix, opts) {
9154
9174
  const options = {
@@ -9167,7 +9187,7 @@ function getStartAndEndKeys2(key) {
9167
9187
  endkey: key + "\uFFF0"
9168
9188
  };
9169
9189
  }
9170
- var import_cross_fetch, import_moment7, GUEST_LOCAL_DB, localUserDB, pouchDBincludeCredentialsConfig, REVIEW_TIME_FORMAT2;
9190
+ var import_cross_fetch, import_moment7, GUEST_LOCAL_DB, localUserDB, pouchDBincludeCredentialsConfig, courseDBHandles, REVIEW_TIME_FORMAT2;
9171
9191
  var init_couch = __esm({
9172
9192
  "src/impl/couch/index.ts"() {
9173
9193
  "use strict";
@@ -9191,6 +9211,7 @@ var init_couch = __esm({
9191
9211
  return pouchdb_setup_default.fetch(url, opts);
9192
9212
  }
9193
9213
  };
9214
+ courseDBHandles = /* @__PURE__ */ new Map();
9194
9215
  REVIEW_TIME_FORMAT2 = "YYYY-MM-DD--kk:mm:ss-SSS";
9195
9216
  }
9196
9217
  });