forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync_upload_gate.dart
More file actions
408 lines (379 loc) · 13.9 KB
/
Copy pathsync_upload_gate.dart
File metadata and controls
408 lines (379 loc) · 13.9 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import 'dart:async';
import 'dart:io';
import 'package:omi/backend/http/api/conversations.dart';
import 'package:omi/backend/http/api/users.dart';
import 'package:omi/backend/http/shared.dart';
import 'package:omi/backend/schema/geolocation.dart';
import 'package:omi/services/account_cutover/account_cutover_runtime.dart';
import 'package:omi/services/wals/sync_rate_limit_reconciliation.dart';
import 'package:omi/services/wals/sync_rate_limiter.dart';
import 'package:omi/utils/analytics/analytics_manager.dart';
import 'package:omi/utils/mutex.dart';
import 'package:uuid/uuid.dart';
typedef SyncFilesUploader = Future<UploadFilesResult> Function(
List<File> files, {
UploadProgressCallback? onUploadProgress,
String? conversationId,
bool claimLiveCapture,
Geolocation? geolocation,
});
typedef FairUseStatusLoader = Future<Map<String, dynamic>?> Function();
typedef UploadTelemetryEmitter = void Function(String eventName, Map<String, dynamic> properties);
typedef UploadAttemptIdFactory = String Function();
typedef UploadClock = DateTime Function();
/// Account-global admission gate for every `/v2/sync-local-files` upload.
///
/// Uploads are serialized so independent WAL, live-capture, and Transcribe
/// Later loops cannot race past a newly established cooldown. Persisted fair-
/// use state is reconciled through a single in-flight status request before an
/// upload is admitted.
class SyncUploadGate {
SyncUploadGate({
required SyncRateLimiter limiter,
required SyncFilesUploader uploader,
required FairUseStatusLoader fairUseStatusLoader,
UploadTelemetryEmitter? telemetryEmitter,
UploadAttemptIdFactory? attemptIdFactory,
UploadClock? clock,
}) : _limiter = limiter,
_uploader = uploader,
_fairUseStatusLoader = fairUseStatusLoader,
_telemetryEmitter = telemetryEmitter,
_attemptIdFactory = attemptIdFactory ?? _defaultAttemptId,
_clock = clock ?? DateTime.now;
static final SyncUploadGate instance = SyncUploadGate(
limiter: SyncRateLimiter.instance,
uploader: uploadLocalFilesV2,
fairUseStatusLoader: getFairUseStatus,
telemetryEmitter: _emitProductionTelemetry,
);
static const int _statusRetryCooldownSeconds = 60;
final SyncRateLimiter _limiter;
final SyncFilesUploader _uploader;
final FairUseStatusLoader _fairUseStatusLoader;
final UploadTelemetryEmitter? _telemetryEmitter;
final UploadAttemptIdFactory _attemptIdFactory;
final UploadClock _clock;
final Mutex _uploadMutex = Mutex();
Future<bool>? _reconciliation;
static String _defaultAttemptId() => const Uuid().v4();
static void _emitProductionTelemetry(String eventName, Map<String, dynamic> properties) {
final analytics = AnalyticsManager();
switch (eventName) {
case RecordingUploadTelemetry.startedEvent:
analytics.recordingUploadStarted(
attemptId: properties['upload_attempt_id'] as String,
recordingId: properties['recording_id'] as String?,
fileCount: properties['file_count'] as int,
totalBytes: properties['total_bytes'] as int,
claimsLiveCapture: properties['claims_live_capture'] as bool,
);
return;
case RecordingUploadTelemetry.completedEvent:
analytics.recordingUploadCompleted(
attemptId: properties['upload_attempt_id'] as String,
recordingId: properties['recording_id'] as String?,
fileCount: properties['file_count'] as int,
totalBytes: properties['total_bytes'] as int,
claimsLiveCapture: properties['claims_live_capture'] as bool,
durationSeconds: properties['duration_seconds'] as double,
result: properties['result'] as String,
);
return;
case RecordingUploadTelemetry.failedEvent:
analytics.recordingUploadFailed(
attemptId: properties['upload_attempt_id'] as String,
recordingId: properties['recording_id'] as String?,
fileCount: properties['file_count'] as int,
totalBytes: properties['total_bytes'] as int,
claimsLiveCapture: properties['claims_live_capture'] as bool,
durationSeconds: properties['duration_seconds'] as double,
failureClass: properties['failure_class'] as String,
);
return;
}
}
/// Reconciles a previously confirmed fair-use restriction with the server.
/// Returns whether uploads are currently allowed after all cooldowns.
Future<bool> prepareToUpload() async {
if (_limiter.hasPersistedFairUseState) {
await reconcileFairUseStatus();
}
return !_limiter.isLimited;
}
/// Single-flight authoritative fair-use reconciliation.
Future<bool> reconcileFairUseStatus() {
if (!_limiter.hasPersistedFairUseState) {
return Future.value(!_limiter.isLimited);
}
final active = _reconciliation;
if (active != null) return active;
final future = _reconcileFairUseStatus();
_reconciliation = future;
return future.whenComplete(() {
if (identical(_reconciliation, future)) _reconciliation = null;
});
}
Future<bool> _reconcileFairUseStatus() async {
Map<String, dynamic>? status;
try {
status = await _fairUseStatusLoader();
} catch (_) {
status = null;
}
if (shouldClearSyncRateLimitForFairUseStatus(status)) {
_limiter.clearRateLimit();
} else if (!_limiter.isFairUseLimited) {
// A hard restriction or failed status fetch remains authoritative. Retry
// reconciliation soon without hitting upload after the local deadline.
_limiter.markLimited(retryAfterSeconds: _statusRetryCooldownSeconds, reason: RateLimitReason.fairUse);
}
return !_limiter.isLimited;
}
Future<UploadFilesResult> upload(
List<File> files, {
UploadProgressCallback? onUploadProgress,
String? conversationId,
bool claimLiveCapture = false,
Geolocation? geolocation,
}) async {
await _uploadMutex.acquire();
try {
if (!AccountCutoverRuntime.instance.allowsOfflineQueueUpload) {
throw const SyncOfflineQueueQuarantinedException();
}
// Honor an active Retry-After without immediately probing fair-use
// status. Lifecycle/manual entry points may reconcile active state, but
// queued parallel uploads must stop at the established cooldown.
var allowed = !_limiter.isLimited;
if (allowed && _limiter.hasPersistedFairUseState) {
allowed = await reconcileFairUseStatus();
}
if (!allowed) {
throw SyncRateLimitedException(
kind: _limiter.reason == RateLimitReason.backendBusy
? SyncRateLimitKind.backendCapacity
: SyncRateLimitKind.fairUse,
retryAfterSeconds: _limiter.activeRetryAfterSeconds,
);
}
final attemptId = _attemptIdFactory();
final startedAt = _clock();
final totalBytes = await RecordingUploadTelemetry.totalBytes(files);
_emitTelemetry(
RecordingUploadTelemetry.startedEvent,
RecordingUploadTelemetry.startedPayload(
attemptId: attemptId,
recordingId: conversationId,
fileCount: files.length,
totalBytes: totalBytes,
claimsLiveCapture: claimLiveCapture,
),
);
try {
final result = await _uploader(
files,
onUploadProgress: onUploadProgress,
conversationId: conversationId,
claimLiveCapture: claimLiveCapture,
geolocation: geolocation,
);
_limiter.clear();
_emitTelemetry(
RecordingUploadTelemetry.completedEvent,
RecordingUploadTelemetry.completedPayload(
attemptId: attemptId,
recordingId: conversationId,
fileCount: files.length,
totalBytes: totalBytes,
claimsLiveCapture: claimLiveCapture,
durationSeconds: _durationSeconds(startedAt),
result: result.isQueued ? 'accepted' : 'completed',
),
);
return result;
} on SyncRateLimitedException catch (error) {
_limiter.markLimited(
retryAfterSeconds: error.retryAfterSeconds,
reason: error.kind == SyncRateLimitKind.fairUse ? RateLimitReason.fairUse : RateLimitReason.backendBusy,
);
_recordUploadFailure(
error,
attemptId: attemptId,
recordingId: conversationId,
fileCount: files.length,
totalBytes: totalBytes,
claimsLiveCapture: claimLiveCapture,
startedAt: startedAt,
);
rethrow;
} catch (error) {
_recordUploadFailure(
error,
attemptId: attemptId,
recordingId: conversationId,
fileCount: files.length,
totalBytes: totalBytes,
claimsLiveCapture: claimLiveCapture,
startedAt: startedAt,
);
rethrow;
}
} finally {
_uploadMutex.release();
}
}
double _durationSeconds(DateTime startedAt) {
final milliseconds = _clock().difference(startedAt).inMilliseconds;
return (milliseconds < 0 ? 0 : milliseconds) / 1000.0;
}
void _recordUploadFailure(
Object error, {
required String attemptId,
required String? recordingId,
required int fileCount,
required int totalBytes,
required bool claimsLiveCapture,
required DateTime startedAt,
}) {
_emitTelemetry(
RecordingUploadTelemetry.failedEvent,
RecordingUploadTelemetry.failedPayload(
attemptId: attemptId,
recordingId: recordingId,
fileCount: fileCount,
totalBytes: totalBytes,
claimsLiveCapture: claimsLiveCapture,
durationSeconds: _durationSeconds(startedAt),
failureClass: RecordingUploadTelemetry.failureClass(error),
),
);
}
void _emitTelemetry(String eventName, Map<String, dynamic> properties) {
try {
_telemetryEmitter?.call(eventName, properties);
} catch (_) {
// Analytics must never change upload success, failure, or retry behavior.
}
}
}
class RecordingUploadTelemetry {
static const String startedEvent = 'Recording Upload Started';
static const String completedEvent = 'Recording Upload Completed';
static const String failedEvent = 'Recording Upload Failed';
static Future<int> totalBytes(List<File> files) async {
var bytes = 0;
for (final file in files) {
try {
bytes += await file.length();
} catch (_) {
// A missing/unreadable file will be classified by the authoritative
// uploader. Telemetry remains best-effort and content-free.
}
}
return bytes;
}
static Map<String, dynamic> startedPayload({
required String attemptId,
required String? recordingId,
required int fileCount,
required int totalBytes,
required bool claimsLiveCapture,
}) =>
_basePayload(
attemptId: attemptId,
recordingId: recordingId,
fileCount: fileCount,
totalBytes: totalBytes,
claimsLiveCapture: claimsLiveCapture,
);
static Map<String, dynamic> completedPayload({
required String attemptId,
required String? recordingId,
required int fileCount,
required int totalBytes,
required bool claimsLiveCapture,
required double durationSeconds,
required String result,
}) =>
{
..._basePayload(
attemptId: attemptId,
recordingId: recordingId,
fileCount: fileCount,
totalBytes: totalBytes,
claimsLiveCapture: claimsLiveCapture,
),
'duration_seconds': durationSeconds < 0 ? 0.0 : durationSeconds,
'result': result == 'completed' ? 'completed' : 'accepted',
};
static Map<String, dynamic> failedPayload({
required String attemptId,
required String? recordingId,
required int fileCount,
required int totalBytes,
required bool claimsLiveCapture,
required double durationSeconds,
required String failureClass,
}) =>
{
..._basePayload(
attemptId: attemptId,
recordingId: recordingId,
fileCount: fileCount,
totalBytes: totalBytes,
claimsLiveCapture: claimsLiveCapture,
),
'duration_seconds': durationSeconds < 0 ? 0.0 : durationSeconds,
'failure_class': _failureClasses.contains(failureClass) ? failureClass : 'unknown',
};
static const Set<String> _failureClasses = {
'rate_limited',
'timeout',
'network',
'authentication',
'server',
'unknown',
};
static String failureClass(Object error) {
if (error is SyncRateLimitedException) return 'rate_limited';
if (error is TimeoutException) return 'timeout';
if (error is SocketException) return 'network';
if (error is SyncUploadHttpException) {
if (error.statusCode == 401 || error.statusCode == 403) return 'authentication';
if (error.statusCode >= 500) return 'server';
}
final normalized = error.toString().toLowerCase();
if (normalized.contains('401') || normalized.contains('403') || normalized.contains('unauthorized')) {
return 'authentication';
}
if (normalized.contains('500') ||
normalized.contains('502') ||
normalized.contains('503') ||
normalized.contains('504')) {
return 'server';
}
return 'unknown';
}
static Map<String, dynamic> _basePayload({
required String attemptId,
required String? recordingId,
required int fileCount,
required int totalBytes,
required bool claimsLiveCapture,
}) =>
{
'upload_attempt_id': attemptId,
if (recordingId != null && recordingId.isNotEmpty) 'recording_id': recordingId,
'file_count': fileCount < 0 ? 0 : fileCount,
'total_bytes': totalBytes < 0 ? 0 : totalBytes,
'claims_live_capture': claimsLiveCapture,
'upload_source': 'offline_audio_queue',
};
}
/// Raised when the server cutover control quarantines legacy offline uploads.
class SyncOfflineQueueQuarantinedException implements Exception {
const SyncOfflineQueueQuarantinedException();
@override
String toString() => 'SyncOfflineQueueQuarantinedException';
}