forked from lichess-org/mobile
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnnue_service.dart
More file actions
226 lines (193 loc) · 7.15 KB
/
nnue_service.dart
File metadata and controls
226 lines (193 loc) · 7.15 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import 'dart:io';
import 'dart:isolate';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart' show AlertDialog, Navigator, Text, showAdaptiveDialog;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:lichess_mobile/src/model/common/preloaded_data.dart';
import 'package:lichess_mobile/src/model/engine/engine.dart';
import 'package:lichess_mobile/src/network/connectivity.dart';
import 'package:lichess_mobile/src/network/http.dart';
import 'package:lichess_mobile/src/tab_scaffold.dart';
import 'package:lichess_mobile/src/utils/l10n_context.dart';
import 'package:lichess_mobile/src/widgets/platform_alert_dialog.dart';
import 'package:logging/logging.dart';
import 'package:multistockfish/multistockfish.dart';
final _logger = Logger('NnueService');
typedef NNUEFiles = ({File bigNet, File smallNet});
/// A provider for [NnueService].
final nnueServiceProvider = Provider<NnueService>((Ref ref) {
return NnueService(ref);
}, name: 'NnueServiceProvider');
/// A service to manage NNUE files for the Stockfish engine.
///
/// This service handles downloading, checking, and deleting NNUE files.
/// It can be overridden in tests to avoid file system access.
class NnueService {
NnueService(this._ref);
final Ref _ref;
final ValueNotifier<double> _nnueDownloadProgress = ValueNotifier(0.0);
bool _nnueOperationInProgress = false;
/// Cache the result of the NNUE checksum verification.
bool? _nnueSumCheckResult;
ValueListenable<double> get nnueDownloadProgress => _nnueDownloadProgress;
bool get isDownloadingNNUEFiles =>
nnueDownloadProgress.value > 0.0 && nnueDownloadProgress.value < 1.0;
/// Get the NNUE files paths.
///
/// Throws an exception if the app support directory is not available.
NNUEFiles get nnueFiles {
final appSupportDirectory = _ref.read(preloadedDataProvider).requireValue.appSupportDirectory;
if (appSupportDirectory == null) {
throw Exception('App support directory is null.');
}
final bigNetFile = File('${appSupportDirectory.path}/${Stockfish.latestBigNNUE}');
final smallNetFile = File('${appSupportDirectory.path}/${Stockfish.latestSmallNNUE}');
return (bigNet: bigNetFile, smallNet: smallNetFile);
}
Future<bool> hasOutdatedNNUEFiles() async {
if (await checkNNUEFiles()) {
return false;
}
final appSupportDirectory = _ref.read(preloadedDataProvider).requireValue.appSupportDirectory;
if (appSupportDirectory == null) {
return false;
}
final NNUEFiles files = nnueFiles;
await for (final entity in appSupportDirectory.list(followLinks: false)) {
if (entity is File &&
entity.path.endsWith('.nnue') &&
entity.path != files.bigNet.path &&
entity.path != files.smallNet.path) {
return true;
}
}
return false;
}
/// Check the presence and integrity of the NNUE files.
Future<bool> checkNNUEFiles() async {
final NNUEFiles files;
try {
files = nnueFiles;
} catch (e) {
_logger.warning('Error getting NNUE files: $e');
return false;
}
final (:bigNet, :smallNet) = files;
try {
final found = await bigNet.exists() && await smallNet.exists();
if (found) {
_nnueSumCheckResult ??= await Isolate.run(() {
return _checksumMatches(bigNet.path, bigNetHash) &&
_checksumMatches(smallNet.path, smallNetHash);
});
if (_nnueSumCheckResult == true) {
return true;
} else {
_logger.warning('NNUE files are corrupted.');
}
}
return false;
} catch (e) {
_logger.warning('Error checking NNUE files: $e');
return false;
}
}
Future<bool> downloadNNUEFiles({bool inBackground = true}) async {
if (_nnueOperationInProgress) {
_logger.warning('NNUE download already in progress, ignoring request');
return false;
}
_nnueOperationInProgress = true;
try {
final NNUEFiles files;
try {
files = nnueFiles;
} catch (e) {
_logger.warning('Error getting NNUE files: $e');
return false;
}
final (:bigNet, :smallNet) = files;
// delete any existing nnue files before downloading
await deleteNNUEFiles();
Future<bool> doDownload() {
final client = _ref.read(defaultClientProvider);
return downloadFiles(
client,
[bigNetUrl, smallNetUrl],
[bigNet, smallNet],
expectedLengths: [bigNetExpectedSize, smallNetExpectedSize],
onProgress: (received, length) {
_nnueDownloadProgress.value = received / length;
},
);
}
final connectivityResult = await _ref.read(connectivityPluginProvider).checkConnectivity();
final onWifi = connectivityResult.contains(ConnectivityResult.wifi);
if (onWifi == false) {
if (inBackground) {
throw Exception('Cannot download in background on mobile data.');
} else {
final context = _ref.read(currentNavigatorKeyProvider).currentContext;
if (context == null || !context.mounted) return false;
final isOk = await showAdaptiveDialog<bool>(
context: context,
barrierDismissible: true,
builder: (context) {
return AlertDialog.adaptive(
content: const Text(
'Are you sure you want to download the NNUE files ($nnueTotalSizeMB)?',
),
actions: [
PlatformDialogAction(
child: const Text('OK'),
onPressed: () {
Navigator.of(context).pop(true);
},
),
PlatformDialogAction(
child: Text(context.l10n.cancel),
onPressed: () {
Navigator.of(context).pop(false);
},
),
],
);
},
);
if (isOk == true) {
await doDownload();
return checkNNUEFiles();
} else {
return Future.value(false);
}
}
} else {
return doDownload();
}
} finally {
_nnueOperationInProgress = false;
_nnueDownloadProgress.value = 0.0;
}
}
Future<void> deleteNNUEFiles() async {
final appSupportDirectory = _ref.read(preloadedDataProvider).requireValue.appSupportDirectory;
if (appSupportDirectory == null) {
throw Exception('App support directory is null.');
}
_nnueSumCheckResult = null;
// delete any existing nnue files before downloading
await for (final entity in appSupportDirectory.list(followLinks: false)) {
if (entity is File && entity.path.endsWith('.nnue')) {
_logger.info('Deleting existing nnue ${entity.path}');
await entity.delete();
}
}
}
}
bool _checksumMatches(String filePath, String expectedHash) {
final bytes = File(filePath).readAsBytesSync();
final hash = sha256.convert(bytes).toString().substring(0, 12);
return hash == expectedHash;
}