syncSingle method
Replays one queued entry. Failures remain observable to the drain caller.
Implementation
Future<void> syncSingle(dynamic key, {CancelToken? cancelToken}) async {
final raw = _queueBox.get(key);
if (raw is! Map) return;
final task = Map<String, dynamic>.from(raw);
if (task['eligible'] == false) return;
if (task['synthetic'] == true &&
(kReleaseMode || !LikeConstants.mockEnabled)) {
throw StateError('Synthetic scenario is disabled');
}
if (task['scope'] != currentSession().key) {
throw StateError('Queued action belongs to another or legacy session');
}
final headers = Map<String, dynamic>.from(task['headers'] ?? const {});
final getTokenFn =
authConfig?.getToken ??
LikeConstants.current.authConfig?.getToken ??
LikeAuthInterceptor.getToken;
if (task['withAuth'] == true && getTokenFn != null) {
try {
final token = await getTokenFn();
if (token != null && token.isNotEmpty) {
headers['Authorization'] = 'Bearer $token';
}
} catch (_) {
// The normal authentication interceptor remains responsible for auth.
}
}
if (task['scope'] != currentSession().key) {
throw StateError('Session changed during replay authorization');
}
final taskOrigin = task['origin'] as String?;
final persistedUrl = task['url'] as String?;
final requestTarget =
persistedUrl ??
(taskOrigin == null
? task['path'] as String
: '$taskOrigin${Uri.parse(task['path'] as String).path}');
final requestOrigin = LikeConnectivityManager.canonicalOrigin(
requestTarget,
);
if (taskOrigin != null && requestOrigin != taskOrigin) {
await _lock.synchronized(() => _queueBox.delete(key));
throw StateError('Offline queue origin does not match replay URL');
}
final token = cancelToken ?? CancelToken();
_running[key] = token;
_publish();
try {
await dio.request<dynamic>(
requestTarget,
data: task['body'] is Map
? codec.decode(task['body'] as Map)
: _castToMapStringDynamic(task['data']),
queryParameters: Map<String, dynamic>.from(task['query'] ?? const {}),
cancelToken: token,
options: Options(
method: task['method'] as String?,
headers: headers,
contentType: task['contentType'] as String?,
extra: <String, dynamic>{
'isSyncRequest': true,
'offlineSync': false,
'withAuth': task['withAuth'] == true,
LikeSessionIdentity.scopeKey: task['scope'],
},
),
);
} catch (error) {
if (!(error is DioException && CancelToken.isCancel(error))) {
await _recordFailure(key, task, error);
}
rethrow;
} finally {
_running.remove(key);
_publish();
}
// Once the server acknowledges the mutation, remove its durable entry
// before notifying presentation code. A refresh-listener failure must never
// reclassify acknowledged work as a failed replay.
await _lock.synchronized(() => _queueBox.delete(key));
final tags = Set<String>.from(task['invalidates'] as List? ?? const []);
if (tags.isNotEmpty && task['scope'] == currentSession().key) {
final origin = Uri.parse(task['origin'] as String).origin;
try {
await LikeService.invalidateTags(tags, task['scope'] as String, origin);
} catch (_) {}
LikeInvalidationHub.shared.emit(
LikeInvalidationEvent(
tags,
scope: task['scope'] as String,
origin: origin,
),
);
}
try {
await _notifyRefresh(task['path'] as String);
} catch (error) {
await LikeLogger.log(
level: LikeLogLevel.warning,
category: 'offline_sync',
message: 'Refresh notification failed after successful sync: $error',
);
}
await LikeLogger.log(
level: LikeLogLevel.info,
category: 'offline_sync',
message: 'Synced successfully: ${task['method']} ${task['path']}',
);
}