@vue-skuilder/db 0.2.37 → 0.3.1

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 (47) hide show
  1. package/dist/{contentSource-D_E7JaxR.d.ts → contentSource-2zVmcjKA.d.ts} +6 -1
  2. package/dist/core/index.cjs +155 -100
  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/versionStamps.mjs +1 -1
  8. package/dist/{dataLayerProvider-BDshhSp_.d.ts → dataLayerProvider-rGyLQ93v.d.ts} +1 -1
  9. package/dist/diagnostics/index.d.ts +3 -3
  10. package/dist/impl/common/BaseUserDB.mjs +61 -34
  11. package/dist/impl/common/BaseUserDB.mjs.map +1 -1
  12. package/dist/impl/couch/CourseSyncService.mjs +23 -1
  13. package/dist/impl/couch/CourseSyncService.mjs.map +1 -1
  14. package/dist/impl/couch/courseDB.mjs +4 -0
  15. package/dist/impl/couch/courseDB.mjs.map +1 -1
  16. package/dist/impl/couch/index.cjs +177 -101
  17. package/dist/impl/couch/index.cjs.map +1 -1
  18. package/dist/impl/couch/index.d.ts +5 -3
  19. package/dist/impl/couch/updateQueue.mjs +69 -46
  20. package/dist/impl/couch/updateQueue.mjs.map +1 -1
  21. package/dist/impl/static/index.cjs +151 -100
  22. package/dist/impl/static/index.cjs.map +1 -1
  23. package/dist/impl/static/index.d.ts +4 -4
  24. package/dist/{index-BLDpFYG3.d.ts → index-C745YB_6.d.ts} +1 -1
  25. package/dist/index.cjs +187 -102
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.ts +23 -10
  28. package/dist/index.mjs +2 -1
  29. package/dist/study/SessionController.mjs +4 -0
  30. package/dist/study/SessionController.mjs.map +1 -1
  31. package/dist/{types-DChCz22D.d.ts → types-DF0JuPbs.d.ts} +1 -1
  32. package/dist/{types-legacy-fT5Y1Wuy.d.ts → types-legacy-DdVjg81H.d.ts} +1 -1
  33. package/dist/util/packer/index.d.ts +3 -3
  34. package/dist/util/perfMarks.mjs +30 -0
  35. package/dist/util/perfMarks.mjs.map +1 -0
  36. package/docs/session-lifecycle-and-replan.md +71 -58
  37. package/package.json +3 -3
  38. package/src/core/interfaces/courseDB.ts +6 -0
  39. package/src/core/navigators/Pipeline.ts +8 -0
  40. package/src/impl/common/BaseUserDB.ts +74 -46
  41. package/src/impl/couch/CourseSyncService.ts +19 -2
  42. package/src/impl/couch/courseDB.ts +5 -0
  43. package/src/impl/couch/updateQueue.ts +86 -82
  44. package/src/study/SessionController.ts +4 -0
  45. package/src/util/index.ts +1 -0
  46. package/src/util/perfMarks.ts +35 -0
  47. package/tests/impl/updateQueue.test.ts +57 -0
@@ -1,9 +1,9 @@
1
1
  import { C as ClassroomDBInterface, A as AdminDBInterface } from '../../classroomDB-DLTtLZct.js';
2
- import { U as UserDBInterface, C as CourseDBInterface, a as CoursesDBInterface, b as CourseInfo, S as StudySessionItem, D as DataLayerResult, c as ContentNavigationStrategyData, d as ContentNavigator, R as ReplanHints, G as GeneratorResult } from '../../contentSource-D_E7JaxR.js';
3
- import { D as DataLayerProvider } from '../../dataLayerProvider-BDshhSp_.js';
4
- import { S as StaticCourseManifest } from '../../types-DChCz22D.js';
2
+ import { U as UserDBInterface, C as CourseDBInterface, a as CoursesDBInterface, b as CourseInfo, S as StudySessionItem, D as DataLayerResult, c as ContentNavigationStrategyData, d as ContentNavigator, R as ReplanHints, G as GeneratorResult } from '../../contentSource-2zVmcjKA.js';
3
+ import { D as DataLayerProvider } from '../../dataLayerProvider-rGyLQ93v.js';
4
+ import { S as StaticCourseManifest } from '../../types-DF0JuPbs.js';
5
5
  import { CourseConfig, CourseElo, DataShape } from '@vue-skuilder/common';
6
- import { S as SkuilderCourseData, Q as QualifiedCardID, T as TagStub, a as Tag } from '../../types-legacy-fT5Y1Wuy.js';
6
+ import { S as SkuilderCourseData, Q as QualifiedCardID, T as TagStub, a as Tag } from '../../types-legacy-DdVjg81H.js';
7
7
  import { S as SyncStrategy, A as AccountCreationResult, a as AuthenticationResult } from '../../SyncStrategy-BXliog1m.js';
8
8
  import 'moment';
9
9
 
@@ -1,4 +1,4 @@
1
- import { P as PackerConfig, a as PackedCourseData, S as StaticCourseManifest } from './types-DChCz22D.js';
1
+ import { P as PackerConfig, a as PackedCourseData, S as StaticCourseManifest } from './types-DF0JuPbs.js';
2
2
 
3
3
  /**
4
4
  * Abstraction for file system operations needed by the migrator.
package/dist/index.cjs CHANGED
@@ -3624,7 +3624,7 @@ var FRAMEWORK_VERSION, hostAppVersion, DEFAULT_STRATEGY_HASH;
3624
3624
  var init_versionStamps = __esm({
3625
3625
  "src/core/versionStamps.ts"() {
3626
3626
  "use strict";
3627
- FRAMEWORK_VERSION = true ? "0.2.37" : "dev";
3627
+ FRAMEWORK_VERSION = true ? "0.3.1" : "dev";
3628
3628
  DEFAULT_STRATEGY_HASH = "default";
3629
3629
  }
3630
3630
  });
@@ -3767,8 +3767,10 @@ var init_updateQueue = __esm({
3767
3767
  init_logger();
3768
3768
  UpdateQueue = class extends Loggable {
3769
3769
  _className = "UpdateQueue";
3770
- pendingUpdates = {};
3771
- 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();
3772
3774
  readDB;
3773
3775
  // Database for read operations
3774
3776
  writeDB;
@@ -3786,6 +3788,9 @@ var init_updateQueue = __esm({
3786
3788
  * **Error Handling Pattern:**
3787
3789
  * - This method does NOT create documents if they don't exist
3788
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
3789
3794
  * - This design maintains separation of concerns (UpdateQueue handles conflicts, callers handle lifecycle)
3790
3795
  *
3791
3796
  * @example
@@ -3802,12 +3807,16 @@ var init_updateQueue = __esm({
3802
3807
  */
3803
3808
  update(id, update) {
3804
3809
  logger.debug(`Update requested on doc: ${id}`);
3805
- if (this.pendingUpdates[id]) {
3806
- this.pendingUpdates[id].push(update);
3807
- } else {
3808
- this.pendingUpdates[id] = [update];
3809
- }
3810
- 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
+ });
3811
3820
  }
3812
3821
  constructor(readDB, writeDB) {
3813
3822
  super();
@@ -3818,64 +3827,56 @@ var init_updateQueue = __esm({
3818
3827
  logger.debug(`db info: ${JSON.stringify(i)}`);
3819
3828
  });
3820
3829
  }
3821
- async applyUpdates(id) {
3822
- logger.debug(`Applying updates on doc: ${id}`);
3823
- if (this.inprogressUpdates[id]) {
3824
- while (this.inprogressUpdates[id]) {
3825
- 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
+ }
3826
3846
  }
3827
- return this.applyUpdates(id);
3828
- } else {
3829
- if (this.pendingUpdates[id] && this.pendingUpdates[id].length > 0) {
3830
- this.inprogressUpdates[id] = true;
3831
- const MAX_RETRIES = 5;
3832
- for (let i = 0; i < MAX_RETRIES; i++) {
3833
- try {
3834
- const doc = await this.readDB.get(id);
3835
- let updatedDoc = { ...doc };
3836
- const updatesToApply = [...this.pendingUpdates[id]];
3837
- for (const update of updatesToApply) {
3838
- if (typeof update === "function") {
3839
- updatedDoc = { ...updatedDoc, ...update(updatedDoc) };
3840
- } else {
3841
- updatedDoc = {
3842
- ...updatedDoc,
3843
- ...update
3844
- };
3845
- }
3846
- }
3847
- await this.writeDB.put(updatedDoc);
3848
- this.pendingUpdates[id].splice(0, updatesToApply.length);
3849
- if (this.pendingUpdates[id].length === 0) {
3850
- this.inprogressUpdates[id] = false;
3851
- delete this.inprogressUpdates[id];
3852
- } else {
3853
- return this.applyUpdates(id);
3854
- }
3855
- return updatedDoc;
3856
- } catch (e) {
3857
- if (e.name === "conflict" && i < MAX_RETRIES - 1) {
3858
- logger.warn(`Conflict on update for doc ${id}, retry #${i + 1}`);
3859
- await new Promise((res) => setTimeout(res, 50 * Math.random()));
3860
- } else if (e.name === "not_found" && i === 0) {
3861
- logger.warn(`Update failed for ${id} - does not exist. Throwing to caller.`);
3862
- delete this.inprogressUpdates[id];
3863
- throw e;
3864
- } else {
3865
- delete this.inprogressUpdates[id];
3866
- if (this.pendingUpdates[id]) {
3867
- delete this.pendingUpdates[id];
3868
- }
3869
- logger.error(`Error on attemped update (retry ${i}): ${JSON.stringify(e)}`);
3870
- throw e;
3871
- }
3872
- }
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;
3873
3876
  }
3874
- throw new Error(`UpdateQueue failed for doc ${id} after ${MAX_RETRIES} retries.`);
3875
- } else {
3876
- throw new Error(`Empty Updates Queue Triggered`);
3877
3877
  }
3878
3878
  }
3879
+ throw new Error(`UpdateQueue failed for doc ${id} after ${MAX_RETRIES} retries.`);
3879
3880
  }
3880
3881
  };
3881
3882
  }
@@ -6587,6 +6588,29 @@ var init_dataDirectory = __esm({
6587
6588
  }
6588
6589
  });
6589
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
+
6590
6614
  // src/util/index.ts
6591
6615
  var init_util2 = __esm({
6592
6616
  "src/util/index.ts"() {
@@ -6595,6 +6619,7 @@ var init_util2 = __esm({
6595
6619
  init_packer();
6596
6620
  init_migrator();
6597
6621
  init_dataDirectory();
6622
+ init_perfMarks();
6598
6623
  }
6599
6624
  });
6600
6625
 
@@ -7008,6 +7033,7 @@ var init_Pipeline = __esm({
7008
7033
  import_common11 = require("@vue-skuilder/common");
7009
7034
  init_navigators();
7010
7035
  init_logger();
7036
+ init_perfMarks();
7011
7037
  init_orchestration();
7012
7038
  init_PipelineDebugger();
7013
7039
  init_diversityRerank();
@@ -7211,6 +7237,13 @@ var init_Pipeline = __esm({
7211
7237
  logger.info(
7212
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)})`
7213
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
+ });
7214
7247
  const topScores = result.slice(0, 3).map((c) => c.score);
7215
7248
  logExecutionSummary(
7216
7249
  this.generator.name,
@@ -8861,6 +8894,7 @@ var init_SessionController = __esm({
8861
8894
  init_studySession();
8862
8895
  init_recording();
8863
8896
  init_util2();
8897
+ init_perfMarks();
8864
8898
  init_navigators();
8865
8899
  init_Pipeline();
8866
8900
  init_versionStamps();
@@ -9122,6 +9156,7 @@ var init_SessionController = __esm({
9122
9156
  );
9123
9157
  }
9124
9158
  clearStaleSessionDebugState();
9159
+ perfMark("sk:session-prepare-start");
9125
9160
  const wellIndicated = await this.getWeightedContent();
9126
9161
  this._recordRuns("bootstrap");
9127
9162
  this._wellIndicatedRemaining = wellIndicated;
@@ -9131,6 +9166,8 @@ var init_SessionController = __esm({
9131
9166
  );
9132
9167
  }
9133
9168
  await this.hydrationService.ensureHydratedCards();
9169
+ perfMark("sk:session-prepared");
9170
+ perfMeasure("sk:session-prepare", "sk:session-prepare-start", "sk:session-prepared");
9134
9171
  startSessionTracking(this.sessionId, this.supplyQ.length, this.failedQ.length);
9135
9172
  this._openDocPromise = this._openSessionDoc();
9136
9173
  this._intervalHandle = setInterval(() => {
@@ -10701,6 +10738,9 @@ var init_BaseUserDB = __esm({
10701
10738
  // Database to use for write operations (local-first approach)
10702
10739
  updateQueue;
10703
10740
  _hydration = { state: "not-required" };
10741
+ /** See scanScheduledCards. Bumped by every write to scheduled reviews. */
10742
+ _scheduledScan = null;
10743
+ _scheduledGeneration = 0;
10704
10744
  /** In-flight hydration, so concurrent callers can wait for a real answer. */
10705
10745
  _hydrationPromise = null;
10706
10746
  /**
@@ -10945,18 +10985,38 @@ Currently logged-in as ${this._username}.`
10945
10985
  *
10946
10986
  */
10947
10987
  async getActiveCards() {
10988
+ return (await this.scanScheduledCards()).map((doc) => ({
10989
+ courseID: doc.courseId,
10990
+ cardID: doc.cardId
10991
+ }));
10992
+ }
10993
+ /**
10994
+ * The user's scheduled reviews (`card_review_*`), all of them: one `allDocs`
10995
+ * scan shared by concurrent readers. A pipeline run's generators start
10996
+ * together (`CompositeGenerator`), and each used to scan the range itself
10997
+ * (`getActiveCards` from ELO and Prescribed, `getReviewstoDate` from SRS).
10998
+ * Sharing only an in-flight scan keeps reads as fresh as before; a schedule
10999
+ * or removal of a review starts a new scan for anyone reading after it.
11000
+ * Docs are shared between callers: copy before mutating.
11001
+ */
11002
+ scanScheduledCards() {
11003
+ const inFlight = this._scheduledScan;
11004
+ if (inFlight && inFlight.generation === this._scheduledGeneration) return inFlight.scan;
10948
11005
  const keys = getStartAndEndKeys(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */]);
10949
- const reviews = await this.remoteDB.allDocs({
10950
- startkey: keys.startkey,
10951
- endkey: keys.endkey,
10952
- include_docs: true
10953
- });
10954
- return reviews.rows.map((r) => {
10955
- return {
10956
- courseID: r.doc.courseId,
10957
- cardID: r.doc.cardId
10958
- };
10959
- });
11006
+ const entry = {
11007
+ generation: this._scheduledGeneration,
11008
+ scan: this.remoteDB.allDocs({
11009
+ startkey: keys.startkey,
11010
+ endkey: keys.endkey,
11011
+ include_docs: true
11012
+ }).then((res) => res.rows.map((row) => row.doc))
11013
+ };
11014
+ this._scheduledScan = entry;
11015
+ const done = () => {
11016
+ if (this._scheduledScan === entry) this._scheduledScan = null;
11017
+ };
11018
+ entry.scan.then(done, done);
11019
+ return entry.scan;
10960
11020
  }
10961
11021
  async getActivityRecords() {
10962
11022
  try {
@@ -11022,28 +11082,23 @@ Currently logged-in as ${this._username}.`
11022
11082
  }
11023
11083
  }
11024
11084
  async getReviewstoDate(targetDate, course_id) {
11025
- const keys = getStartAndEndKeys(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */]);
11026
- const reviews = await this.remoteDB.allDocs({
11027
- startkey: keys.startkey,
11028
- endkey: keys.endkey,
11029
- include_docs: true
11030
- });
11085
+ const reviews = await this.scanScheduledCards();
11031
11086
  log3(
11032
11087
  `Fetching ${this._username}'s scheduled reviews${course_id ? ` for course ${course_id}` : ""}.`
11033
11088
  );
11034
- return reviews.rows.filter((r) => {
11035
- if (r.id.startsWith(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */])) {
11089
+ return reviews.filter((doc) => {
11090
+ if (doc._id.startsWith(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */])) {
11036
11091
  const date = import_moment7.default.utc(
11037
- r.id.substr(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */].length),
11092
+ doc._id.substr(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */].length),
11038
11093
  REVIEW_TIME_FORMAT
11039
11094
  );
11040
11095
  if (targetDate.isAfter(date)) {
11041
- if (course_id === void 0 || r.doc.courseId === course_id) {
11096
+ if (course_id === void 0 || doc.courseId === course_id) {
11042
11097
  return true;
11043
11098
  }
11044
11099
  }
11045
11100
  }
11046
- }).map((r) => r.doc);
11101
+ }).map((doc) => ({ ...doc }));
11047
11102
  }
11048
11103
  async getReviewsForcast(daysCount, course_id) {
11049
11104
  const time = import_moment7.default.utc().add(daysCount, "days");
@@ -11427,22 +11482,20 @@ Currently logged-in as ${this._username}.`
11427
11482
  async putCardRecord(record) {
11428
11483
  const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);
11429
11484
  record.timeStamp = import_moment7.default.utc(record.timeStamp).toString();
11430
- try {
11431
- const cardHistory = await this.update(
11432
- cardHistoryID,
11433
- function(h) {
11434
- h.records.push(record);
11435
- h.bestInterval = h.bestInterval || 0;
11436
- if (areQuestionRecords(h)) {
11437
- h.lapses = getLapses(h.records);
11438
- h.streak = getStreak(h.records);
11439
- } else {
11440
- h.lapses = h.lapses || 0;
11441
- h.streak = h.streak || 0;
11442
- }
11443
- return h;
11444
- }
11445
- );
11485
+ const append = (h) => {
11486
+ h.records.push(record);
11487
+ h.bestInterval = h.bestInterval || 0;
11488
+ if (areQuestionRecords(h)) {
11489
+ h.lapses = getLapses(h.records);
11490
+ h.streak = getStreak(h.records);
11491
+ } else {
11492
+ h.lapses = h.lapses || 0;
11493
+ h.streak = h.streak || 0;
11494
+ }
11495
+ return h;
11496
+ };
11497
+ const appendToExisting = async () => {
11498
+ const cardHistory = await this.update(cardHistoryID, append);
11446
11499
  cardHistory.records = cardHistory.records.map((record2) => {
11447
11500
  const ret = {
11448
11501
  ...record2
@@ -11451,6 +11504,9 @@ Currently logged-in as ${this._username}.`
11451
11504
  return ret;
11452
11505
  });
11453
11506
  return cardHistory;
11507
+ };
11508
+ try {
11509
+ return await appendToExisting();
11454
11510
  } catch (e) {
11455
11511
  const reason = e;
11456
11512
  if (reason.status === 404) {
@@ -11467,6 +11523,9 @@ Currently logged-in as ${this._username}.`
11467
11523
  const putResult = await this.writeDB.put(initCardHistory);
11468
11524
  return { ...initCardHistory, _rev: putResult.rev };
11469
11525
  } catch (creationError) {
11526
+ if (creationError.name === "conflict") {
11527
+ return appendToExisting();
11528
+ }
11470
11529
  throw new Error(
11471
11530
  `Failed to create CardHistory for ${cardHistoryID}. Reason: ${creationError}`
11472
11531
  );
@@ -11510,6 +11569,7 @@ Currently logged-in as ${this._username}.`
11510
11569
  const deletePromises = duplicateDocIds.map(async (docId) => {
11511
11570
  try {
11512
11571
  const doc = await this.remoteDB.get(docId);
11572
+ this._scheduledGeneration++;
11513
11573
  await this.writeDB.remove(doc);
11514
11574
  log3(`Successfully removed duplicate review: ${docId}`);
11515
11575
  } catch (error) {
@@ -11655,9 +11715,11 @@ Currently logged-in as ${this._username}.`
11655
11715
  }
11656
11716
  }
11657
11717
  async scheduleCardReview(review) {
11718
+ this._scheduledGeneration++;
11658
11719
  return scheduleCardReviewLocal(this.writeDB, review);
11659
11720
  }
11660
11721
  async removeScheduledCardReview(reviewId) {
11722
+ this._scheduledGeneration++;
11661
11723
  return removeScheduledCardReviewLocal(this.writeDB, reviewId);
11662
11724
  }
11663
11725
  async registerForClassroom(_classId, _registerAs) {
@@ -12848,6 +12910,10 @@ var init_courseDB = __esm({
12848
12910
  * values may be stale, so read-modify-write cycles must go through
12849
12911
  * the remote DB to avoid conflicts).
12850
12912
  */
12913
+ /** Reads go to this device's replica (perf marks report it as the session's binding). */
12914
+ get readsLocal() {
12915
+ return this.db !== this.remoteDB;
12916
+ }
12851
12917
  constructor(id, userLookup, localDB) {
12852
12918
  this.id = id;
12853
12919
  const remote = getCourseDB(this.id);
@@ -14282,6 +14348,7 @@ var init_CourseSyncService = __esm({
14282
14348
  init_pouchdb_setup();
14283
14349
  init_couch();
14284
14350
  init_logger();
14351
+ init_perfMarks();
14285
14352
  SYNC_MARKER_ID = "_local/sk-course-sync-complete";
14286
14353
  DEFAULT_REPLICATION = {
14287
14354
  batchSize: 1e3,
@@ -14380,6 +14447,7 @@ var init_CourseSyncService = __esm({
14380
14447
  entry.localDB = localDB;
14381
14448
  entry.status = { state: "ready" };
14382
14449
  entry.readyPromise = null;
14450
+ perfMark("sk:course-sync-ready", { courseId, from: "marker" });
14383
14451
  logger.info(
14384
14452
  `[CourseSyncService] Using this device's replica of course ${courseId}; refreshing in the background`
14385
14453
  );
@@ -14422,6 +14490,12 @@ var init_CourseSyncService = __esm({
14422
14490
  syncTimeMs,
14423
14491
  viewWarmTimeMs
14424
14492
  };
14493
+ perfMark("sk:course-sync-refreshed", {
14494
+ courseId,
14495
+ docs: result.docs_written,
14496
+ syncTimeMs,
14497
+ viewWarmTimeMs
14498
+ });
14425
14499
  logger.info(
14426
14500
  `[CourseSyncService] Background refresh of course ${courseId}: ${result.docs_written} docs in ${syncTimeMs}ms, views ${viewWarmTimeMs}ms`
14427
14501
  );
@@ -14522,6 +14596,11 @@ var init_CourseSyncService = __esm({
14522
14596
  );
14523
14597
  const result = await this.replicate(remoteDB, localDB);
14524
14598
  const syncTimeMs = Date.now() - syncStart;
14599
+ perfMark("sk:course-sync-replicated", {
14600
+ courseId,
14601
+ docs: result.docs_written,
14602
+ ms: syncTimeMs
14603
+ });
14525
14604
  logger.info(
14526
14605
  `[CourseSyncService] Replication complete for course ${courseId}: ${result.docs_written} docs in ${syncTimeMs}ms`
14527
14606
  );
@@ -14539,6 +14618,7 @@ var init_CourseSyncService = __esm({
14539
14618
  syncTimeMs,
14540
14619
  viewWarmTimeMs
14541
14620
  };
14621
+ perfMark("sk:course-sync-ready", { courseId, from: "sync", viewWarmTimeMs });
14542
14622
  } catch (e) {
14543
14623
  const errorMsg = e instanceof Error ? e.message : String(e);
14544
14624
  logger.error(
@@ -14626,7 +14706,8 @@ var init_CourseSyncService = __esm({
14626
14706
  try {
14627
14707
  localEpoch = await localDB.get("db-epoch");
14628
14708
  } catch {
14629
- return true;
14709
+ const info = await localDB.info();
14710
+ return info.doc_count > 0 || !!info.update_seq;
14630
14711
  }
14631
14712
  return remoteEpoch.epoch !== localEpoch.epoch;
14632
14713
  } catch {
@@ -16531,6 +16612,8 @@ __export(index_exports, {
16531
16612
  newInterval: () => newInterval,
16532
16613
  newSessionId: () => newSessionId,
16533
16614
  parseCardHistoryID: () => parseCardHistoryID,
16615
+ perfMark: () => perfMark,
16616
+ perfMeasure: () => perfMeasure,
16534
16617
  pipelineDebugAPI: () => pipelineDebugAPI,
16535
16618
  planPipeline: () => planPipeline,
16536
16619
  processCustomQuestionsData: () => processCustomQuestionsData,
@@ -16975,6 +17058,8 @@ init_userDBKeys();
16975
17058
  newInterval,
16976
17059
  newSessionId,
16977
17060
  parseCardHistoryID,
17061
+ perfMark,
17062
+ perfMeasure,
16978
17063
  pipelineDebugAPI,
16979
17064
  planPipeline,
16980
17065
  processCustomQuestionsData,