Files

240 lines
7.6 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../../../core/transport/connection_state.dart';
import '../domain/attention_acks.dart';
import 'attention_ack_queue.dart';
/// Keeps this device's attention acknowledgements in step with the server so
/// clearing on one device clears everywhere.
///
/// [acks] is everything known to be acknowledged: the server's set, every
/// pushed `attention_acks_changed` delta and this device's own acknowledgements
/// (applied at once, before the server answers). Listeners — the Needs-you
/// controller and the chat list — fold it into their own state.
///
/// An acknowledgement the server has not accepted yet stays in a persisted
/// queue and is re-sent on the next [connected]. A server refusal drops the
/// refused batch (it can never succeed); a server that does not know
/// `ack_attention` keeps the queue for a later upgrade and this device falls
/// back to its local state.
///
/// With [sendOnly] (the app passes the socket's own send-only path, as the
/// run watch does) requests are not queued behind the transport's serialized
/// request/reply calls, so a connect-time read never delays the first screen's
/// list; the reply is matched by id from the pushed frames.
class AttentionAckSync extends ChangeNotifier {
AttentionAckSync({
required this.gateway,
required this.queue,
this.sendOnly,
this.replyTimeout = const Duration(seconds: 30),
}) {
_frames = gateway.frames.listen(_onFrame);
}
final ApiGateway gateway;
final AttentionAckQueueStore queue;
final String Function(String type, JsonMap fields)? sendOnly;
final Duration replyTimeout;
late final StreamSubscription<JsonMap> _frames;
final Map<String, Completer<JsonMap>> _replies = {};
AttentionAcks _acks = const AttentionAcks();
AttentionAcks _pending = const AttentionAcks();
Future<void>? _loading;
Future<void>? _flushing;
bool _supported = true;
bool _disposed = false;
/// Everything acknowledged on any device, as far as this device knows.
AttentionAcks get acks => _acks;
/// Acknowledgements made here that the server has not accepted yet.
AttentionAcks get pending => _pending;
/// False after the server answered `attention_acks` with something else
/// (an older server); reset on the next [connected].
bool get supported => _supported;
/// Reads the persisted offline queue once.
Future<void> load() => _loading ??= _load();
Future<void> _load() async {
String? stored;
try {
stored = await queue.read();
} catch (_) {
stored = null;
}
if (_disposed) return;
final queued = AttentionAcks.decode(stored);
_pending = queued.merge(_pending);
_apply(queued);
}
/// Records an acknowledgement made on this device: it applies here at once
/// and is sent to the server (now, or on the next [connected]).
Future<void> acknowledge({
Iterable<String> dismissed = const [],
Map<String, int> chatSeen = const {},
}) async {
final ack = AttentionAcks(
dismissed: {
for (final key in dismissed)
if (key.trim().isNotEmpty) key,
},
chatSeen: {
for (final entry in chatSeen.entries)
if (entry.key.isNotEmpty && entry.value > 0) entry.key: entry.value,
},
);
if (_disposed || ack.isEmpty) return;
await load();
if (_disposed) return;
_pending = _pending.merge(ack);
_apply(ack);
await _persist();
await flush();
}
/// Called on every connected transition of the shared socket: send what was
/// queued while disconnected, then read the server's whole set.
Future<void> connected() async {
if (_disposed) return;
_supported = true;
// Replies still awaited belong to the replaced socket and never arrive;
// fail them now so a stalled flush does not hold up this connection.
_failReplies(StateError('Connection replaced'));
await load();
await flush();
if (_disposed || !_supported) return;
try {
final reply = await _request('attention_acks');
_accept(reply);
} catch (_) {
// Offline or refused: the local state still applies; the next
// connection reads again.
}
}
/// Sends the queue in bounded batches, one request at a time.
Future<void> flush() => _flushing ??= _flush().whenComplete(() {
_flushing = null;
});
Future<void> _flush() async {
while (!_disposed && _supported && !_pending.isEmpty) {
final batch = attentionAckBatch(_pending);
try {
final reply = await _request('ack_attention', {
'attention_acks': batch.toJson(),
});
if (!_accept(reply)) return;
} on ProtocolError {
// The server refused this batch; it will never be accepted.
} catch (_) {
return; // Not connected or timed out: keep it for the next connection.
}
_pending = _pending.without(batch);
await _persist();
}
}
/// Folds an `attention_acks` reply; false when the server answered with
/// another type, i.e. it does not support shared acknowledgements.
bool _accept(JsonMap reply) {
if (reply['type'] != 'attention_acks') {
_supported = false;
return false;
}
_apply(AttentionAcks.fromJson(reply['attention_acks']));
return true;
}
void _onFrame(JsonMap frame) {
final id = frame['id'];
final reply = id is String ? _replies.remove(id) : null;
if (reply != null) {
if (frame['type'] == 'error') {
final reason = '${frame['error'] ?? ''}'.trim();
reply.completeError(
ProtocolError(reason.isEmpty ? 'server error' : reason),
);
} else {
reply.complete(frame);
}
return;
}
if (frame['type'] != 'attention_acks_changed') return;
_apply(AttentionAcks.fromJson(frame['attention_acks']));
}
/// One request: through [sendOnly] when available (reply matched by id),
/// else the gateway's ordinary request/reply call.
Future<JsonMap> _request(String type, [JsonMap fields = const {}]) {
final send = sendOnly;
if (send == null) return gateway.call(type, fields);
final String id;
try {
id = send(type, fields);
} catch (error) {
return Future.error(error);
}
final reply = Completer<JsonMap>();
_replies[id] = reply;
return reply.future.timeout(
replyTimeout,
onTimeout: () {
_replies.remove(id);
throw TimeoutException('$type timed out', replyTimeout);
},
);
}
void _apply(AttentionAcks incoming) {
if (_disposed) return;
final next = _acks.merge(incoming);
if (identical(next, _acks)) return;
_acks = next;
notifyListeners();
}
Future<void> _persist() async {
try {
await queue.write(_pending.encode());
} catch (_) {
// The queue still lives in memory for this session.
}
}
@override
void dispose() {
_disposed = true;
unawaited(_frames.cancel());
_failReplies(StateError('Attention sync disposed'));
super.dispose();
}
void _failReplies(Object error) {
final waiting = _replies.values.toList();
_replies.clear();
for (final reply in waiting) {
reply.completeError(error);
}
}
}
final _syncs = Expando<AttentionAckSync>('attention acknowledgement sync');
/// Makes [sync] the acknowledgement channel of [gateway], so feature
/// controllers created later for the same socket (the chat list) share it.
void bindAttentionAckSync(ApiGateway gateway, AttentionAckSync? sync) {
_syncs[gateway] = sync;
}
/// The acknowledgement channel bound to [gateway], if the app bound one.
AttentionAckSync? attentionAckSyncOf(ApiGateway gateway) => _syncs[gateway];