forked from lichess-org/mobile
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpuzzle_service.dart
More file actions
209 lines (181 loc) · 7.19 KB
/
puzzle_service.dart
File metadata and controls
209 lines (181 loc) · 7.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import 'dart:math' show max;
import 'package:async/async.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:lichess_mobile/src/model/common/id.dart';
import 'package:lichess_mobile/src/model/puzzle/puzzle.dart';
import 'package:lichess_mobile/src/model/puzzle/puzzle_angle.dart';
import 'package:lichess_mobile/src/model/puzzle/puzzle_batch_storage.dart';
import 'package:lichess_mobile/src/model/puzzle/puzzle_preferences.dart';
import 'package:lichess_mobile/src/model/puzzle/puzzle_repository.dart';
import 'package:lichess_mobile/src/model/puzzle/puzzle_storage.dart';
import 'package:lichess_mobile/src/model/puzzle/puzzle_theme.dart';
import 'package:lichess_mobile/src/network/http.dart';
import 'package:logging/logging.dart';
import 'package:result_extensions/result_extensions.dart';
part 'puzzle_service.freezed.dart';
/// Size of puzzle local cache
const kPuzzleLocalQueueLength = 50;
/// A provider for [PuzzleService].
final puzzleServiceProvider = FutureProvider<PuzzleService>((Ref ref) {
return ref.read(puzzleServiceFactoryProvider)(queueLength: kPuzzleLocalQueueLength);
}, name: 'PuzzleServiceProvider');
/// A provider for [PuzzleServiceFactory].
final puzzleServiceFactoryProvider = Provider<PuzzleServiceFactory>((Ref ref) {
return PuzzleServiceFactory(ref);
}, name: 'PuzzleServiceFactoryProvider');
class PuzzleServiceFactory {
PuzzleServiceFactory(this._ref);
final Ref _ref;
Future<PuzzleService> call({required int queueLength}) async {
return PuzzleService(
_ref,
batchStorage: await _ref.read(puzzleBatchStorageProvider.future),
puzzleStorage: await _ref.read(puzzleStorageProvider.future),
queueLength: queueLength,
);
}
}
@freezed
sealed class PuzzleContext with _$PuzzleContext {
const factory PuzzleContext({
required Puzzle puzzle,
required PuzzleAngle angle,
required UserId? userId,
/// Current Glicko rating of the user if available.
PuzzleGlicko? glicko,
/// List of solved puzzle results if available.
IList<PuzzleRound>? rounds,
/// If true, the result won't be recorded on the server for this puzzle.
bool? casual,
bool? isPuzzleStreak,
/// Remaining puzzle IDs to replay after the current one.
IList<PuzzleId>? replayRemaining,
}) = _PuzzleContext;
}
class PuzzleService {
PuzzleService(
this._ref, {
required this.batchStorage,
required this.puzzleStorage,
required this.queueLength,
});
final Ref _ref;
final int queueLength;
final PuzzleBatchStorage batchStorage;
final PuzzleStorage puzzleStorage;
final Logger _log = Logger('PuzzleService');
/// Loads the next puzzle from database and the glicko rating if available.
///
/// Will sync with server if necessary.
/// This future should never fail on network errors.
Future<PuzzleContext?> nextPuzzle({
required UserId? userId,
PuzzleAngle angle = const PuzzleTheme(PuzzleThemeKey.mix),
}) {
return Result.release(
_syncAndLoadData(userId, angle).map(
(data) => data.$1 != null && data.$1!.unsolved.isNotEmpty
? PuzzleContext(
puzzle: data.$1!.unsolved[0],
angle: angle,
userId: userId,
glicko: data.$2,
rounds: data.$3,
)
: null,
),
);
}
/// Update puzzle queue with the solved puzzle, sync with server and returns
/// the next puzzle with the glicko rating if available.
///
/// This future should never fail on network errors.
Future<PuzzleContext?> solve({
required UserId? userId,
required PuzzleSolution solution,
required Puzzle puzzle,
PuzzleAngle angle = const PuzzleTheme(PuzzleThemeKey.mix),
}) async {
puzzleStorage.save(puzzle: puzzle);
const emptyBatch = PuzzleBatch(solved: IListConst([]), unsolved: IListConst([]));
final data = await batchStorage.fetch(userId: userId, angle: angle) ?? emptyBatch;
await batchStorage.save(
userId: userId,
angle: angle,
data: PuzzleBatch(
solved: IList([...data.solved, solution]),
unsolved: data.unsolved.removeWhere((e) => e.puzzle.id == solution.id),
),
);
return nextPuzzle(userId: userId, angle: angle);
}
/// Clears the current puzzle batch, fetches a new one and returns the next puzzle.
Future<PuzzleContext?> resetBatch({
required UserId? userId,
PuzzleAngle angle = const PuzzleTheme(PuzzleThemeKey.mix),
}) async {
await batchStorage.delete(userId: userId, angle: angle);
return nextPuzzle(userId: userId, angle: angle);
}
/// Deletes the puzzle batch of [angle] from the local storage.
Future<void> deleteBatch({required UserId? userId, required PuzzleAngle angle}) async {
await batchStorage.delete(userId: userId, angle: angle);
}
/// Synchronize offline puzzle queue with server and gets latest data.
///
/// This task will fetch missing puzzles so the queue length is always equal to
/// `queueLength`.
/// It will call [PuzzleRepository.solveBatch] if necessary.
///
/// This method should never fail, as if the network is down it will fallback
/// to the local database.
FutureResult<(PuzzleBatch?, PuzzleGlicko?, IList<PuzzleRound>?)> _syncAndLoadData(
UserId? userId,
PuzzleAngle angle,
) async {
final data = await batchStorage.fetch(userId: userId, angle: angle);
final unsolved = data?.unsolved ?? IList(const []);
final solved = data?.solved ?? IList(const []);
final deficit = max(0, queueLength - unsolved.length);
if (deficit > 0 || solved.isNotEmpty) {
_log.fine('Will sync puzzles with lichess (deficit: $deficit, solved: ${solved.length})');
final difficulty = _ref.read(puzzlePreferencesProvider).difficulty;
// anonymous users can't solve puzzles so we just download the deficit
final batchResponse = _ref.withClient(
(client) => Result.capture(
solved.isNotEmpty && userId != null
? PuzzleRepository(
client,
).solveBatch(nb: deficit, solved: solved, angle: angle, difficulty: difficulty)
: PuzzleRepository(
client,
).selectBatch(nb: deficit, angle: angle, difficulty: difficulty),
),
);
return batchResponse
.fold(
(value) => Result.value((
PuzzleBatch(
solved: IList(const []),
unsolved: IList([...unsolved, ...value.puzzles]),
),
value.glicko,
value.rounds,
true, // should save the batch
)),
// we don't need to save the batch if the request failed
(_, _) => Result.value((data, null, null, false)),
)
.flatMap((tuple) async {
final (newBatch, glicko, rounds, shouldSave) = tuple;
if (newBatch != null && shouldSave) {
await batchStorage.save(userId: userId, angle: angle, data: newBatch);
}
return Result.value((newBatch, glicko, rounds));
});
}
return Result.value((data, null, null));
}
}