Saves that survive an update: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: schema (line 22), session (line 93), migrate (line 205), load (line 218), autosave (line 224), sync (line 240), check (line 342).
1/// Saves that outlive the build that wrote them: a schema with versions and
2/// the migrations between them, an autosave at the moments a session tends
3/// to end, and a copy in the cloud settled against this device's by step and
4/// digest.
5///
6/// Everything here is kept in memory — a storage of a map and a cloud of
7/// one slot — so the page writes nothing to the machine it runs on. A game
8/// passes its platform's `Storage` and an `HttpCloudSaves` or
9/// `PlatformCloudSaves` instead, and nothing else changes.
10///
11/// Quoted by `saves.md` and shown whole in the Source tab.
12library;
14import 'dart:convert';
16import 'package:flutter/foundation.dart' show visibleForTesting;
17import 'package:flutter3d_game/flutter3d_game.dart';
18import 'package:flutter3d_showcase/src/demo/demo.dart';
19import 'package:flutter3d_showcase/src/demo/scene_kit.dart';
20import 'package:flutter3d_sim/flutter3d_sim.dart';
22/// The game's save data, by version. Version 0 kept health as a number;
23/// version 1 made it a row of hearts; version 2 added a key ring. The
24/// version is the number of migrations, so it cannot move without one.
25final SaveSchema _schema = SaveSchema(
26 migrations: <SaveMigration>[
27 (Map<String, Object?> run) {
28 final int health = (run.remove('health') as num? ?? 3).toInt();
29 return run..['hearts'] = <bool>[for (var i = 0; i < health; i++) true];
30 },
31 (Map<String, Object?> run) => run..['keys'] = <String>[],
32 ],
33);
35/// A storage that is a map, counting its writes.
36final class _Memory extends Storage {
37 final Map<String, String> documents = <String, String>{};
38 int writes = 0;
41 Future<String?> read(String name) async => documents[name];
44 Future<void> write(String name, String contents) async {
45 writes++;
46 documents[name] = contents;
47 }
50 Future<void> remove(String name) async => documents.remove(name);
51}
53/// A cloud of one slot, versioned the way an `ETag` versions it, which
54/// records every call made to it.
55final class _Cloud extends CloudSaveStore {
56 String? document;
57 int revision = 0;
58 final List<String> calls = <String>[];
61 String get name => 'the cloud';
64 Future<CloudFetch> fetch(CloudFetchRequest request) async {
65 calls.add('fetch');
66 final String? kept = document;
67 return kept == null
68 ? const CloudEmpty()
69 : CloudDocument(kept, version: '$revision');
70 }
73 Future<CloudPut> put(CloudPutRequest request) async {
74 final doc = request.document;
75 final replacing = request.replacing;
76 calls.add('put');
77 if (replacing != (document == null ? null : '$revision')) {
78 return const CloudMoved();
79 }
80 document = doc;
81 revision++;
82 return CloudStored(version: '$revision');
83 }
84}
86/// One level's worth of the run.
87final class _Level {
88 int hearts = 3;
89 int coins = 0;
90 int steps = 0;
91}
93/// The game, as a `RunSession`: how a level is opened, written down and
94/// put back, and how far the run has got in steps.
95final class _Game extends RunSession<_Level> {
96 _Game(SaveFile saves) : super(firstLevel: 'cellar', saves: saves);
99 Future<_Level> loadLevel(String asset) async => _Level();
102 RunOutcome outcomeOf(_Level level) => RunOutcome.playing;
105 String? nextOf(_Level level) => null;
108 Snapshot snapshotOf(_Level level) => Snapshot(<String, Object?>{
109 'hearts': <bool>[for (var i = 0; i < level.hearts; i++) true],
110 'coins': level.coins,
111 'keys': <String>[],
112 });
115 void restoreInto(RunRestoreContext<_Level> context) {
116 final level = context.level;
117 final snapshot = context.snapshot;
118 level
119 ..hearts = (snapshot.data['hearts'] as List<Object?>? ?? const []).length
120 ..coins = snapshot.data.integer('coins');
121 }
124 int stepOf(_Level level) => level.steps;
125}
127/// What the page found, kept for its claim and its picture.
128final class SavesReport {
129 /// The version-0 save, read through the schema's migrations.
130 SaveRead? old;
132 /// A save from a newer build, which the read must refuse as newer.
133 SaveRead? newer;
135 /// Whether the game resumed the old save when it began.
136 bool resumed = false;
138 /// The hearts the resumed run holds; the check wants 2.
139 int heartsAfterLoad = 0;
141 /// The coins the resumed run holds; the check wants 12.
142 int coinsAfterLoad = 0;
144 /// Whether each of play, pause and still paused made the autosave write.
145 final List<bool> autosaves = <bool>[];
147 /// The writes counted after the pauses, after a checkpoint of the same run,
148 /// and after a checkpoint of a run that moved.
149 final List<int> writesAfter = <int>[];
151 /// The schema version the autosave wrote, or -1 when nothing was read back.
152 int writtenSchema = -1;
154 /// What each sync came to, in order: before consent, into an empty cloud,
155 /// against a further run, against an equal one, and once settled.
156 final List<SyncOutcome> outcomes = <SyncOutcome>[];
158 /// How many calls reached the cloud before consent; the check wants none.
159 int callsBeforeConsent = -1;
161 /// The coins in the save after the further run was downloaded; the check
162 /// wants 40.
163 int coinsAfterDownload = 0;
165 /// Whether this device and the cloud hold the same run at the end.
166 bool inSyncAtEnd = false;
168 /// The step of this device's save at the end, which the picture draws.
169 int localStep = 0;
171 /// The step of the cloud's save at the end, which the picture draws.
172 int cloudStep = 0;
173}
175/// The `saves` page: a save migrated, autosaved and synced with a cloud of
176/// one slot, all in memory. Its check reads [report].
177final class SavesDemo extends ShowcaseDemo {
178 /// What the page found while it prepared, read by its check and drawn.
179 final SavesReport report = SavesReport();
181 late final MeshNode _device;
182 late final MeshNode _cloud;
185 void configureView(DemoContext context) {
186 context.orbit
187 ..distance = 7.0
188 ..pitch = 0.35
189 ..yaw = 0.0;
190 context.orbit.target.setValues(0.0, 0.8, 0.0);
191 }
194 Future<void> prepare(DemoContext context) => _run(report);
196 static Future<void> _run(SavesReport out) async {
197 final storage = _Memory();
198 final saves = SaveFile(
199 appName: 'showcase',
200 storage: storage,
201 onIssue: (_) {},
202 schema: _schema,
203 );
205 // A save from the first release: no schema in it, so version 0, and
206 // health as a number.
207 const oldSave =
208 '{"level": "cellar", "step": 900, '
209 '"run": {"health": 2, "coins": 12}}';
210 out.old = SaveRecord.read(jsonDecode(oldSave), _schema);
211 // And one from a build newer than this one, which must be left alone.
212 out.newer = SaveRecord.read(<String, Object?>{
213 'level': 'cellar',
214 'schema': 3,
215 'run': <String, Object?>{'hearts': <bool>[], 'coins': 1},
216 }, _schema);
218 storage.documents[SaveFile.name] = oldSave;
219 final game = _Game(saves);
220 out.resumed = await game.begin();
221 out.heartsAfterLoad = game.level!.hearts;
222 out.coinsAfterLoad = game.level!.coins;
224 final autosave = Autosave(game);
225 final int before = storage.writes;
226 // Playing: nothing to do. Into a pause: written. Still paused: not again.
227 for (final bool now in const <bool>[false, true, true]) {
228 out.autosaves.add(await autosave.paused(now: now));
229 }
230 out.writesAfter.add(storage.writes - before);
231 await autosave.checkpoint(); // the same run: SaveFile skips the write
232 out.writesAfter.add(storage.writes - before);
233 game.level!
234 ..coins += 5
235 ..steps = 960;
236 await autosave.checkpoint(); // a run that moved: written
237 out.writesAfter.add(storage.writes - before);
238 out.writtenSchema = (await saves.read())?.record?.schema ?? -1;
240 final cloud = _Cloud();
241 final sync = SaveSync(saves: saves, store: cloud);
242 // Off on a fresh install: no store is called at all.
243 out.outcomes.add((await sync.sync()).outcome);
244 out.callsBeforeConsent = cloud.calls.length;
246 await sync.consent();
247 out.outcomes.add((await sync.sync()).outcome); // the cloud was empty
249 // Another device played on from there, three hundred steps further.
250 cloud
251 ..document = SaveFile.encode(
252 SaveRecord(
253 level: 'cellar',
254 run: game.snapshotOf(_Level()..coins = 40),
255 step: 1260,
256 schema: _schema.version,
257 ),
258 )
259 ..revision += 1;
260 out.outcomes.add((await sync.sync()).outcome); // the further run is kept
261 out.coinsAfterDownload = (await saves.read())!.record!.run.data.integer(
262 'coins',
263 );
265 // Then both played apart, equally far: only the player can choose.
266 await saves.writeRecord(
267 SaveRecord(
268 level: 'cellar',
269 run: game.snapshotOf(_Level()..coins = 41),
270 step: 1500,
271 schema: _schema.version,
272 ),
273 );
274 cloud
275 ..document = SaveFile.encode(
276 SaveRecord(
277 level: 'cellar',
278 run: game.snapshotOf(_Level()..coins = 52),
279 step: 1500,
280 schema: _schema.version,
281 ),
282 )
283 ..revision += 1;
284 final SyncReport asked = await sync.sync();
285 out.outcomes.add(asked.outcome);
286 out.outcomes.add((await sync.settle(asked, keepLocal: true)).outcome);
288 // Both sides now hold the run this device kept.
289 final SaveRecord? local = (await saves.read())?.record;
290 final SaveRecord? there = saves.parse(cloud.document ?? '').record;
291 out
292 ..inSyncAtEnd =
293 resolveSaves(local: local, remote: there, base: sync.base) ==
294 SaveResolution.inSync &&
295 local != null
296 ..localStep = local?.step ?? 0
297 ..cloudStep = there?.step ?? 0;
298 }
301 Scene build(DemoContext context) {
302 _device = blockNode(
303 context,
304 'this device',
305 Vector3(0.8, 1.0, 0.8),
306 Vector4(0.45, 0.7, 0.95, 1),
307 );
308 _cloud = blockNode(
309 context,
310 'the cloud',
311 Vector3(0.8, 1.0, 0.8),
312 Vector4(0.85, 0.85, 0.9, 1),
313 );
314 for (final (MeshNode node, int step, double x) in <(MeshNode, int, double)>[
315 (_device, report.localStep, -1.0),
316 (_cloud, report.cloudStep, 1.0),
317 ]) {
318 final double h = 0.2 + step / 1000.0;
319 node
320 ..setScale(1.0, h, 1.0)
321 ..setPosition(x, h / 2.0, 0.0);
322 }
323 return sceneOf(<SceneNode>[
324 floorNode(context, width: 6.0, depth: 4.0),
325 _device,
326 _cloud,
327 // The hearts the version-0 save's health became.
328 for (var i = 0; i < report.heartsAfterLoad; i++)
329 ballNode(
330 context,
331 'heart $i',
332 0.18,
333 Vector4(0.9, 0.3, 0.35, 1),
334 at: Vector3(-0.4 + i * 0.4, 0.2, 1.2),
335 ),
336 ]);
337 }
339 /// The page's claim, as the first thing that is not so, or null.
341 String? wrong() {
342 final SaveRead? old = report.old;
343 if (old is! SaveFound || old.upgradedFrom != 0) {
344 return 'the version-0 save was not migrated: $old';
345 }
346 final Map<String, Object?> run = old.record.run.data;
347 if (old.record.schema != 2 ||
348 run.containsKey('health') ||
349 (run['hearts'] as List<Object?>?)?.length != 2 ||
350 run['keys'] is! List ||
351 old.record.step != 900) {
352 return 'the migrated run is $run at schema ${old.record.schema}';
353 }
354 if (report.newer is! SaveNotRead || !(report.newer! as SaveNotRead).newer) {
355 return 'a save from a newer build was not refused as newer';
356 }
357 if (!report.resumed ||
358 report.heartsAfterLoad != 2 ||
359 report.coinsAfterLoad != 12) {
360 return 'the old save did not load into the game';
361 }
362 if (report.autosaves.join(',') != 'false,true,false' ||
363 report.writesAfter.join(',') != '1,1,2' ||
364 report.writtenSchema != 2) {
365 return 'autosave wrote ${report.writesAfter} after ${report.autosaves}';
366 }
367 final String outcomes = <String>[
368 for (final SyncOutcome o in report.outcomes) o.name,
369 ].join(',');
370 if (outcomes != 'notConsented,uploaded,downloaded,ask,uploaded' ||
371 report.callsBeforeConsent != 0 ||
372 report.coinsAfterDownload != 40 ||
373 !report.inSyncAtEnd) {
374 return 'the sync went $outcomes';
375 }
376 return null;
377 }
380 void verify(Scene scene, FrameResult frame) {
381 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
382 final String? problem = wrong();
383 if (problem != null) throw StateError(problem);
384 }
385}