dopaminejs 3.3.0 → 3.5.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.
package/spec/schema.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
3
  "$id": "https://github.com/BaryoDev/dopaminejs/spec/schema.json",
4
4
  "title": "DopamineJS player document, contract 3",
5
- "description": "What export() returns and what validate() and merge() accept. Only v is required on input; validate fills in the rest. Keys inside the per-device maps are device ids, which are never __proto__, constructor or prototype, and a document holds at most 20 of them across xpBy, xpSpentBy, gamesBy, playsBy and sumsBy.",
5
+ "description": "What export() returns and what validate() and merge() accept. Only v is required on input; validate fills in the rest. Any other top level field is kept as read (never __proto__, constructor or prototype). merge joins such a field by value: the larger number if both sides hold a finite number, otherwise the larger canonical JSON text. Recency is not used, since no field has its own timestamp and merge must not depend on order. Keys inside the per-device maps are device ids, which are never __proto__, constructor or prototype, and a document holds at most 20 of them across xpBy, xpSpentBy, gamesBy, playsBy and sumsBy.",
6
6
  "type": "object",
7
7
  "required": ["v"],
8
- "additionalProperties": false,
8
+ "additionalProperties": true,
9
9
  "properties": {
10
10
  "v": { "const": 3 },
11
11
  "name": { "type": "string" },
@@ -31,7 +31,7 @@
31
31
  "type": "object",
32
32
  "additionalProperties": {
33
33
  "type": "object",
34
- "additionalProperties": { "type": "number" }
34
+ "additionalProperties": { "type": "number", "minimum": 0 }
35
35
  }
36
36
  }
37
37
  },
@@ -12,10 +12,10 @@ import { systemClock } from './clock.js';
12
12
  import { levelFor, thresholdFor } from './levels.js';
13
13
  import { BUILTIN_REWARDS, builtinAchievements, rewardsOf } from './achievements.js';
14
14
  import { Middleware } from './middleware.js';
15
- import { merge } from './merge.js';
15
+ import { merge, mergeSession, rekey, ownCounters, raiseOwn, countedDevices } from './merge.js';
16
16
  import { currentStreak, longestRun, trimDays } from './streaks.js';
17
17
  import {
18
- LEGACY, MAX_DEVICES, cap, deviceIds, emptyDoc, validate, view, xpOf, levelOf, clone, freeze, isSafeKey, hasOwn, isRecord
18
+ LEGACY, MAX_DEVICES, cap, checkDevices, deviceIds, emptyDoc, validate, view, xpOf, levelOf, clone, freeze, isSafeKey, hasOwn, isRecord
19
19
  } from './store.js';
20
20
 
21
21
  const DEVICE_KEY = 'device';
@@ -45,6 +45,8 @@ export class RewardSystem extends EventEmitter {
45
45
  * @param {'any'|'record'} [config.streakDays] - What marks today as a play day.
46
46
  * 'any' (default): record() or addXP(). 'record': record() only. XP from an
47
47
  * achievement reward never marks a day.
48
+ * @param {number} [config.loadRetryMs] - After a failed read, a blocked save retries the
49
+ * read at most this often, in ms of the clock. Default 30000. 0 retries on every blocked save.
48
50
  */
49
51
  constructor(dataService, config = {}) {
50
52
  super();
@@ -60,6 +62,10 @@ export class RewardSystem extends EventEmitter {
60
62
  this._deviceSaved = false;
61
63
  this._middleware = new Middleware();
62
64
 
65
+ // Ids whose unlock is waiting on a hook, so a second call for the
66
+ // same id does not unlock it again.
67
+ this._unlocking = new Set();
68
+
63
69
  // Write batching: one record is one write.
64
70
  this._batchDepth = 0;
65
71
  this._pendingSave = false;
@@ -69,11 +75,26 @@ export class RewardSystem extends EventEmitter {
69
75
  // never replaced by accident.
70
76
  this._loadFailed = false;
71
77
  this._readFailed = false;
78
+
79
+ // Retry of a failed read: when it last read, the retry in flight, and a
80
+ // counter that lets init() cancel a retry it overtakes.
81
+ this.loadRetryMs = Number.isFinite(config.loadRetryMs) && config.loadRetryMs >= 0 ? config.loadRetryMs : 30000;
82
+ this._lastRead = 0;
83
+ this._reading = false;
84
+ this._recovering = null;
85
+ this._epoch = 0;
86
+
87
+ // What imports and good reads put into this device's counters while the
88
+ // read is blocked. It is not progress made here, so a recovery does not add it.
89
+ this._forgetImports();
90
+ this._recoveries = 0;
72
91
  }
73
92
 
74
93
  /**
75
94
  * True when the last init() could not read the saved player, so nothing
76
- * is saved until init() is called again and the read works, or reset() is called.
95
+ * is saved until a retry or init() reads it, or reset() is called. A blocked
96
+ * save retries the read (see `loadRetryMs`) and, when it works, merges the
97
+ * progress made since into the saved player, saves it and fires `load_recovered`.
77
98
  * @returns {boolean}
78
99
  */
79
100
  get loadFailed() {
@@ -113,9 +134,16 @@ export class RewardSystem extends EventEmitter {
113
134
  * @returns {Promise<Object>} Frozen snapshot of the player
114
135
  */
115
136
  async init() {
137
+ const known = this._doc && !this._loadFailed && ownCounters(this._doc, this._deviceId);
116
138
  const saved = await this._readSaved();
117
139
  // A failed retry keeps the progress made since the first init.
118
- if (!(this._loadFailed && this._doc)) this._doc = this._load(saved);
140
+ if (!(this._loadFailed && this._doc)) {
141
+ this._doc = this._load(saved);
142
+ this._forgetImports();
143
+ } else if (known) {
144
+ // That player came from storage, so what it held is not new progress.
145
+ known.forEach((value, path) => this._base.set(path, Math.max(this._base.get(path) ?? 0, value)));
146
+ }
119
147
  await this._readDevice();
120
148
  await this.save();
121
149
  return this.snapshot();
@@ -131,26 +159,115 @@ export class RewardSystem extends EventEmitter {
131
159
  // Stay blocked until the read succeeds, so a write made while a
132
160
  // retry is in flight cannot land.
133
161
  this._loadFailed = true;
162
+ this._reading = true;
163
+ this._epoch++;
164
+ this._recovering = null;
165
+ this._lastRead = this.clock.now();
134
166
  try {
135
167
  const saved = await this.dataService.load('player', null, { strict: true });
168
+ if (saved !== null && !isRecord(saved)) {
169
+ // Valid JSON that is not a player: keep it like unreadable data.
170
+ return await this._keepCorrupt(saved);
171
+ }
136
172
  this._loadFailed = false;
137
173
  this._readFailed = false;
138
174
  return saved;
139
175
  } catch (error) {
140
- if (error?.code === 'DOPAMINE_CORRUPT') {
141
- // Keep the unreadable value instead of losing it on the next save.
142
- const kept = await this.dataService.save('player_corrupt', error.raw);
143
- if (kept) this._loadFailed = false;
144
- this._readFailed = !kept;
145
- this._publish('load_failed', { key: 'player', reason: 'corrupt', backedUp: kept });
146
- return null;
147
- }
176
+ if (error?.code === 'DOPAMINE_CORRUPT') return this._keepCorrupt(error.raw);
148
177
  this._readFailed = true;
149
178
  this._publish('load_failed', { key: 'player', reason: 'read', error });
150
179
  return null;
180
+ } finally {
181
+ this._reading = false;
151
182
  }
152
183
  }
153
184
 
185
+ /**
186
+ * Retry the read for a blocked save, at most once per interval, and merge
187
+ * the session player into what it finds. Resolves true when it saved. A
188
+ * retry already in flight is reused. Any failure leaves saving blocked and
189
+ * the session player as it is.
190
+ * @private
191
+ */
192
+ _recover() {
193
+ // A retry in flight belongs to the call that started it. Others return
194
+ // at once, as a blocked save always did, so a read that never settles
195
+ // stalls only that one call.
196
+ if (this._recovering || !this._readFailed || this._reading) return Promise.resolve(false);
197
+ const since = this.clock.now() - this._lastRead;
198
+ if (since >= 0 && since < this.loadRetryMs) return Promise.resolve(false);
199
+ this._lastRead = this.clock.now();
200
+ const retry = this._retryRead(this._epoch).finally(() => {
201
+ if (this._recovering === retry) this._recovering = null;
202
+ });
203
+ this._recovering = retry;
204
+ return retry;
205
+ }
206
+
207
+ async _retryRead(epoch) {
208
+ let saved;
209
+ let adopt = null;
210
+ try {
211
+ saved = await this.dataService.load('player', null, { strict: true });
212
+ if (saved !== null && !isRecord(saved)) return false;
213
+ if (!this._deviceSaved) {
214
+ const stored = await this.dataService.load(DEVICE_KEY, null, { strict: true });
215
+ if (isDeviceId(stored) && stored !== this._deviceId) adopt = stored;
216
+ }
217
+ } catch {
218
+ return false;
219
+ }
220
+ // init() or reset() ran meanwhile and owns the state now.
221
+ if (epoch !== this._epoch || !this._loadFailed) return false;
222
+ // Entries under the stored id that came from an import or from a read
223
+ // cannot be told from progress made here, so the move would count them twice.
224
+ if (countedDevices(this._doc).has(adopt)) return false;
225
+
226
+ // No await from here to the assignment, so the session player is
227
+ // merged as it stands, including any XP added while the read was out.
228
+ let merged;
229
+ try {
230
+ const options = this._options();
231
+ const device = adopt ?? this._deviceId;
232
+ const session = adopt ? rekey(this._doc, this._deviceId, adopt) : this._doc;
233
+ merged = saved === null ? clone(session) : mergeSession(saved, session, device, options, this._base);
234
+ checkDevices(merged);
235
+ merged.level = levelOf(merged);
236
+ } catch {
237
+ return false;
238
+ }
239
+ if (adopt) {
240
+ this._deviceId = adopt;
241
+ this._deviceSaved = true;
242
+ }
243
+ this._doc = merged;
244
+ this._recoveries++;
245
+ this._savedLevel = Number(saved?.level) || 0;
246
+ this._loadFailed = false;
247
+ this._readFailed = false;
248
+ this._forgetImports();
249
+ await this._write();
250
+ this._publish('load_recovered', { key: 'player' });
251
+ return true;
252
+ }
253
+
254
+ _forgetImports() {
255
+ this._base = new Map();
256
+ }
257
+
258
+ /**
259
+ * Keep an unreadable value instead of losing it on the next save.
260
+ * @private
261
+ */
262
+ async _keepCorrupt(raw) {
263
+ this._loadFailed = true;
264
+ const kept = await this.dataService.save('player_corrupt', raw);
265
+ if (kept) this._loadFailed = false;
266
+ this._readFailed = !kept;
267
+ this._publish('load_failed', { key: 'player', reason: 'corrupt', backedUp: kept });
268
+ return null;
269
+ }
270
+
154
271
  /**
155
272
  * Saved state is untrusted: it goes through validate. A document from a
156
273
  * newer version or with too many devices is left alone in storage.
@@ -239,9 +356,28 @@ export class RewardSystem extends EventEmitter {
239
356
  this._requirePlayer();
240
357
  const before = this.snapshot();
241
358
  const incoming = validate(doc, this._options());
242
- const merged = merge(this._doc, incoming, this._options());
359
+ let session = this._doc;
360
+ let base = null;
361
+ if (this._readFailed) {
362
+ // This device's counters in the import are not new progress. Count them
363
+ // as a baseline so a recovery adds only what the session earned on top.
364
+ base = new Map(this._base);
365
+ const raise = new Map();
366
+ const have = ownCounters(this._doc, this._deviceId);
367
+ ownCounters(incoming, this._deviceId).forEach((value, path) => {
368
+ // At or below what the session holds, it is the session's own export or older.
369
+ if (value > (have.get(path) ?? 0)) {
370
+ raise.set(path, value - (base.get(path) ?? 0));
371
+ base.set(path, value);
372
+ }
373
+ });
374
+ session = clone(this._doc);
375
+ raiseOwn(session, this._deviceId, raise);
376
+ }
377
+ const merged = merge(session, incoming, this._options());
243
378
  merged.level = levelOf(merged);
244
379
  this._doc = merged;
380
+ if (base) this._base = base;
245
381
 
246
382
  const after = this.snapshot();
247
383
  await this.save();
@@ -278,8 +414,9 @@ export class RewardSystem extends EventEmitter {
278
414
  * Pass `{ overwrite: false }` to keep the stored player when the last
279
415
  * init() could not read it (an unsupported newer version, or a read that
280
416
  * keeps failing). The player in memory is replaced by a new empty one,
281
- * nothing is written, `loadFailed` stays true so later writes stay
282
- * blocked, and `player_reset` is still emitted. When the last init() did
417
+ * nothing is written, `loadFailed` stays true and `player_reset` is still
418
+ * emitted. A later write may retry the read and, when it returns a
419
+ * player, merges the new session into it (see `loadRetryMs`). When the last init() did
283
420
  * read the saved player, `overwrite: false` changes nothing: it saves
284
421
  * like a plain reset(). A corrupt save that init() backed up to `player_corrupt` counts as loaded, so `overwrite: false` saves like a plain reset().
285
422
  * If the backup failed, it counts as a failed load and nothing is written.
@@ -302,6 +439,7 @@ export class RewardSystem extends EventEmitter {
302
439
  this._requirePlayer();
303
440
  if (overwrite === false && this._readFailed) {
304
441
  this._doc = emptyDoc(this.clock.now());
442
+ this._forgetImports();
305
443
  this._publish('player_reset', {});
306
444
  return this.snapshot();
307
445
  }
@@ -309,6 +447,7 @@ export class RewardSystem extends EventEmitter {
309
447
  this._doc = emptyDoc(this.clock.now());
310
448
  this._loadFailed = false;
311
449
  this._readFailed = false;
450
+ this._forgetImports();
312
451
  await this.save();
313
452
  });
314
453
  this._publish('player_reset', {});
@@ -364,7 +503,11 @@ export class RewardSystem extends EventEmitter {
364
503
  * @private
365
504
  */
366
505
  async _write() {
367
- if (this._loadFailed) return;
506
+ if (this._loadFailed) {
507
+ // The retry saves everything changed before it merged.
508
+ await this._recover();
509
+ return;
510
+ }
368
511
  this._doc.lastPlayedAt = this.clock.now();
369
512
  if (!this._deviceSaved) {
370
513
  this._deviceSaved = (await this.dataService.save(DEVICE_KEY, this._deviceId)) !== false;
@@ -434,13 +577,23 @@ export class RewardSystem extends EventEmitter {
434
577
 
435
578
  async _announceXP(oldLevel, amount, reason) {
436
579
  const doc = this._doc;
437
- const total = xpOf(doc);
438
- const newLevel = Math.max(oldLevel, levelFor(total));
439
- const leveledUp = newLevel > oldLevel;
580
+ let total = xpOf(doc);
581
+ let newLevel = Math.max(oldLevel, levelFor(total));
440
582
  if (newLevel > doc.level) doc.level = newLevel;
441
583
 
584
+ const recoveries = this._recoveries;
442
585
  await this.save();
443
586
 
587
+ // A save that recovered a failed read replaced the document with the
588
+ // merged one. Report that, and compare with the merged level before
589
+ // this gain, so a level the saved player already had is not announced.
590
+ if (this._recoveries !== recoveries) {
591
+ total = xpOf(this._doc);
592
+ newLevel = Math.max(newLevel, levelOf(this._doc));
593
+ oldLevel = Math.max(oldLevel, this._savedLevel, levelFor(total - amount));
594
+ }
595
+ const leveledUp = newLevel > oldLevel;
596
+
444
597
  this._publish('xp_gained', { amount, reason, leveledUp, newLevel, total });
445
598
  if (leveledUp) {
446
599
  this._publish('level_up', { oldLevel, newLevel, totalXP: total });
@@ -624,17 +777,26 @@ export class RewardSystem extends EventEmitter {
624
777
 
625
778
  // Already unlocked: paying the XP again would let one call farm levels.
626
779
  if (hasOwn(this._doc.achievements, achievementId)) return false;
780
+ if (this._unlocking.has(achievementId)) return false;
627
781
 
628
782
  const achievement = this.achievements[achievementId];
629
783
  if (!achievement) return false;
630
784
 
631
785
  const { [achievementId]: reward } = rewardsOf(this.achievements);
632
- const context = await this._middleware.before(
633
- 'beforeUnlock',
634
- { id: achievementId, reward },
635
- (next) => Number.isFinite(next.reward) && next.reward >= 0
636
- );
786
+ this._unlocking.add(achievementId);
787
+ let context;
788
+ try {
789
+ context = await this._middleware.before(
790
+ 'beforeUnlock',
791
+ { id: achievementId, reward },
792
+ (next) => Number.isFinite(next.reward) && next.reward >= 0
793
+ );
794
+ } finally {
795
+ this._unlocking.delete(achievementId);
796
+ }
637
797
  if (context === false) return false;
798
+ // A reset or an import during the hook may have unlocked it already.
799
+ if (hasOwn(this._doc.achievements, achievementId)) return false;
638
800
 
639
801
  const doc = this._doc;
640
802
  const oldLevel = levelOf(doc);
@@ -674,6 +836,7 @@ export class RewardSystem extends EventEmitter {
674
836
  * Mark achievements as seen
675
837
  */
676
838
  async markAchievementsSeen(achievementIds) {
839
+ this._requirePlayer();
677
840
  for (const id of achievementIds) {
678
841
  if (hasOwn(this._doc.achievements, id)) {
679
842
  this._doc.achievements[id].seen = true;
@@ -1,4 +1,4 @@
1
- import { validate, checkDevices, hasOwn, VERSION } from './store.js';
1
+ import { validate, checkDevices, hasOwn, extraKeys, cap, clone, VERSION } from './store.js';
2
2
  import { isDay, trimDays } from './streaks.js';
3
3
 
4
4
  // Join two maps that are `depth` levels deep, taking the larger number at the
@@ -30,6 +30,28 @@ function joinAchievements(a, b) {
30
30
  return out;
31
31
  }
32
32
 
33
+ // Same text for the same value whatever the key order, so the choice below does
34
+ // not depend on which side a value came from.
35
+ const stable = (value) => {
36
+ if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`;
37
+ if (value !== null && typeof value === 'object') {
38
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable(value[key])}`).join(',')}}`;
39
+ }
40
+ return JSON.stringify(value);
41
+ };
42
+
43
+ // A field the core does not know has no rule to join by. One side only: kept.
44
+ // Both: the larger number, else the larger text, the same in any order.
45
+ const larger = (a, b) => (Number.isFinite(a) && Number.isFinite(b) && a !== b ? a > b : stable(a) >= stable(b)) ? a : b;
46
+
47
+ function joinExtras(x, y, doc) {
48
+ for (const key of new Set([...extraKeys(x), ...extraKeys(y)])) {
49
+ const a = hasOwn(x, key) ? x[key] : undefined;
50
+ const b = hasOwn(y, key) ? y[key] : undefined;
51
+ doc[key] = a === undefined ? b : b === undefined ? a : larger(a, b);
52
+ }
53
+ }
54
+
33
55
  const positive = (a, b) => (a > 0 && b > 0 ? Math.min(a, b) : Math.max(a, b));
34
56
 
35
57
  /**
@@ -63,6 +85,99 @@ export function merge(a, b, options) {
63
85
  sumsBy: join(x.sumsBy, y.sumsBy, 2),
64
86
  achievements: joinAchievements(x.achievements, y.achievements)
65
87
  };
88
+ joinExtras(x, y, doc);
66
89
  checkDevices(doc);
67
90
  return doc;
68
91
  }
92
+
93
+ // Every counter map of a document by path, as a JSON array of keys.
94
+ function counterMaps(doc) {
95
+ const maps = new Map([[JSON.stringify(['xpBy']), doc.xpBy], [JSON.stringify(['xpSpentBy']), doc.xpSpentBy], [JSON.stringify(['gamesBy']), doc.gamesBy]]);
96
+ for (const activity of Object.keys(doc.playsBy)) maps.set(JSON.stringify(['playsBy', activity]), doc.playsBy[activity]);
97
+ for (const activity of Object.keys(doc.sumsBy)) {
98
+ for (const key of Object.keys(doc.sumsBy[activity])) {
99
+ maps.set(JSON.stringify(['sumsBy', activity, key]), doc.sumsBy[activity][key]);
100
+ }
101
+ }
102
+ return maps;
103
+ }
104
+
105
+ /** The device ids that hold a counter above zero. */
106
+ export function countedDevices(doc) {
107
+ const ids = new Set();
108
+ for (const map of counterMaps(doc).values()) {
109
+ for (const id in map) if (map[id] > 0) ids.add(id);
110
+ }
111
+ return ids;
112
+ }
113
+
114
+ /** This device's counters in a document, by path. */
115
+ export function ownCounters(doc, device) {
116
+ const out = new Map();
117
+ for (const [path, map] of counterMaps(doc)) {
118
+ if (hasOwn(map, device)) out.set(path, map[device]);
119
+ }
120
+ return out;
121
+ }
122
+
123
+ /** Add `by` (a path to amount map) to this device's counters in `doc`, in place. */
124
+ export function raiseOwn(doc, device, by) {
125
+ for (const [path, amount] of by) {
126
+ let node = doc;
127
+ for (const key of JSON.parse(path)) {
128
+ if (!hasOwn(node, key)) node[key] = {};
129
+ node = node[key];
130
+ }
131
+ node[device] = cap((hasOwn(node, device) ? node[device] : 0) + amount);
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Fold a session player into the saved one it could not read earlier. The
137
+ * session started empty, so its counters for this device are new progress and
138
+ * are added, not joined by max. Everything else joins like `merge`. The saved
139
+ * player keeps its name and its unknown fields. Pure.
140
+ *
141
+ * `base` holds what an import put into this device's session counters (path to
142
+ * amount, see `ownCounters`). That is not new progress, so it is joined by max
143
+ * with the saved counter, and only what the session added on top is added.
144
+ *
145
+ * @param {*} saved the player read from storage
146
+ * @param {*} session the player made since the failed read
147
+ * @param {string} device this device's id
148
+ * @param {{ today?: string, rewards?: Object }} [options] see validate
149
+ * @param {Map<string, number>} [base]
150
+ */
151
+ export function mergeSession(saved, session, device, options, base = new Map()) {
152
+ const x = validate(saved, options);
153
+ const y = validate(session, options);
154
+ const doc = merge(x, y, options);
155
+ doc.name = x.name;
156
+ for (const key of extraKeys(x)) doc[key] = x[key];
157
+
158
+ const mine = counterMaps(doc);
159
+ const was = counterMaps(x);
160
+ for (const [path, map] of counterMaps(y)) {
161
+ if (!hasOwn(map, device)) continue;
162
+ const imported = Math.min(base.get(path) ?? 0, map[device]);
163
+ const stored = was.has(path) && hasOwn(was.get(path), device) ? was.get(path)[device] : 0;
164
+ mine.get(path)[device] = cap(Math.max(stored, imported) + (map[device] - imported));
165
+ }
166
+ return doc;
167
+ }
168
+
169
+ /** A copy of a document with one device's entries moved under another id. */
170
+ export function rekey(doc, from, to) {
171
+ const out = clone(doc);
172
+ const move = (map) => {
173
+ if (!hasOwn(map, from)) return;
174
+ map[to] = hasOwn(map, to) ? Math.max(map[to], map[from]) : map[from];
175
+ delete map[from];
176
+ };
177
+ for (const map of [out.xpBy, out.xpSpentBy, out.gamesBy]) move(map);
178
+ for (const activity of Object.keys(out.playsBy)) move(out.playsBy[activity]);
179
+ for (const activity of Object.keys(out.sumsBy)) {
180
+ for (const key of Object.keys(out.sumsBy[activity])) move(out.sumsBy[activity][key]);
181
+ }
182
+ return out;
183
+ }