App: replace a silent socket instead of hanging; blink the terminal cursor on a timer; keep one markdown cache entry per streamed reply
A socket that outlived a sleep or network change looked open, so every queued request waited its own 30 s timeout behind the last until the page was reopened. The client now replaces a socket whose request times out unheard (or after two timeouts in a row), and probes it with a ping after a quiet spell or on returning to the foreground. The terminal's blinking cursor ran a Ticker (a frame every vsync); a 530 ms timer now flips it. Streamed deltas no longer flood the markdown cache and evict finished answers. Adds tool/perf/idle_session_bench.mjs (idle frames, long-session heap, snapshot census) and notes/perf-hangs-idle.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -20,10 +20,28 @@ class PipelinesClient implements ApiGateway {
|
||||
this.connectionTimeout = const Duration(seconds: 5),
|
||||
this.backoffBase = const Duration(seconds: 1),
|
||||
this.backoffMax = const Duration(seconds: 30),
|
||||
this.probeTimeout = const Duration(seconds: 10),
|
||||
this.quietProbeAfter = const Duration(seconds: 30),
|
||||
this.replaceSilentSocket = true,
|
||||
}) : _factory = channelFactory ?? connectPipelinesChannel;
|
||||
|
||||
final ChannelFactory _factory;
|
||||
final Duration requestTimeout, connectionTimeout, backoffBase, backoffMax;
|
||||
|
||||
/// How long a liveness probe ([probe]) waits to hear anything at all from
|
||||
/// the server before the socket is treated as dead and replaced.
|
||||
final Duration probeTimeout;
|
||||
|
||||
/// A request sent after the socket has been quiet this long (wall clock,
|
||||
/// so a laptop's sleep counts) is accompanied by a [probe]. A socket that
|
||||
/// outlived a sleep often looks open but is dead: nothing tells the
|
||||
/// browser until it gives up retransmitting, minutes later.
|
||||
final Duration quietProbeAfter;
|
||||
|
||||
/// Whether a socket that leaves requests or a probe unheard is replaced
|
||||
/// (see [_timedOut] and [probe]). Off only for fixtures whose fake server
|
||||
/// deliberately answers nothing.
|
||||
final bool replaceSilentSocket;
|
||||
final _frames = StreamController<JsonMap>.broadcast();
|
||||
final _states = StreamController<ConnectionState>.broadcast();
|
||||
final Map<String, Completer<JsonMap>> _pending = {};
|
||||
@@ -39,6 +57,17 @@ class PipelinesClient implements ApiGateway {
|
||||
ConnectionState _state = const ConnectionState(ConnectionKind.idle);
|
||||
Future<void> _queue = Future.value();
|
||||
|
||||
/// Monotonic time, and when the socket last delivered anything.
|
||||
final Stopwatch _clock = Stopwatch()..start();
|
||||
Duration _heardAt = Duration.zero;
|
||||
|
||||
/// Requests in a row that timed out on this socket.
|
||||
int _timeouts = 0;
|
||||
Timer? _probe;
|
||||
|
||||
/// Wall-clock time of the socket's last traffic either way.
|
||||
DateTime _lastTraffic = DateTime.now();
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => _frames.stream;
|
||||
Stream<ConnectionState> get states => _states.stream;
|
||||
@@ -108,6 +137,9 @@ class PipelinesClient implements ApiGateway {
|
||||
]).timeout(connectionTimeout);
|
||||
if (generation != _generation) return;
|
||||
_attempt = 0;
|
||||
_timeouts = 0;
|
||||
_heardAt = _clock.elapsed;
|
||||
_lastTraffic = DateTime.now();
|
||||
_setState(const ConnectionState(ConnectionKind.connected));
|
||||
} catch (error) {
|
||||
if (generation == _generation) _closed(error.toString());
|
||||
@@ -187,8 +219,10 @@ class PipelinesClient implements ApiGateway {
|
||||
result.completeError(const NotConnectedError());
|
||||
return;
|
||||
}
|
||||
_probeIfQuiet();
|
||||
final id = 'flutter-${++_sequence}';
|
||||
_pending[id] = result;
|
||||
final sentAt = _clock.elapsed;
|
||||
final timer = Timer(requestTimeout, () {
|
||||
if (_pending.remove(id) != null) {
|
||||
result.completeError(
|
||||
@@ -196,6 +230,7 @@ class PipelinesClient implements ApiGateway {
|
||||
'request timed out after ${requestTimeout.inMilliseconds}ms',
|
||||
),
|
||||
);
|
||||
_timedOut(generation, sentAt);
|
||||
}
|
||||
});
|
||||
result.future.then<void>(
|
||||
@@ -220,7 +255,69 @@ class PipelinesClient implements ApiGateway {
|
||||
return id;
|
||||
}
|
||||
|
||||
/// A request went unanswered. Requests are answered in order on the
|
||||
/// server's request lane, so every later request would wait out its own
|
||||
/// timeout behind it, one after another: the app hangs until reopened.
|
||||
/// When the socket stayed silent the whole time (dead after a sleep or a
|
||||
/// network change), or a second request in a row timed out (the lane is
|
||||
/// stuck), the socket is replaced: queued requests fail at once and a
|
||||
/// fresh connection resubscribes.
|
||||
void _timedOut(int generation, Duration sentAt) {
|
||||
if (generation != _generation || _disposed || _manual) return;
|
||||
if (!replaceSilentSocket) return;
|
||||
_timeouts++;
|
||||
final silent = _heardAt <= sentAt;
|
||||
if (silent || _timeouts >= 2) {
|
||||
_closed(
|
||||
silent ? 'No reply from the server' : 'The server stopped replying',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks that the open socket still reaches the server: a ping is sent
|
||||
/// outside the request queue, and if nothing at all arrives within
|
||||
/// [probeTimeout] the socket is replaced. Call it when the app returns to
|
||||
/// the foreground; the client also sends one with the first request after
|
||||
/// a quiet spell.
|
||||
void probe() {
|
||||
final channel = _channel;
|
||||
if (channel == null ||
|
||||
!replaceSilentSocket ||
|
||||
_state.kind != ConnectionKind.connected ||
|
||||
_probe != null) {
|
||||
return;
|
||||
}
|
||||
final generation = _generation;
|
||||
final sentAt = _clock.elapsed;
|
||||
try {
|
||||
channel.sink.add(
|
||||
jsonEncode({'type': 'ping', 'id': 'flutter-probe-${++_sequence}'}),
|
||||
);
|
||||
} catch (_) {
|
||||
// A failed write surfaces through the socket's own error path.
|
||||
}
|
||||
_probe = Timer(probeTimeout, () {
|
||||
_probe = null;
|
||||
if (generation != _generation || _disposed || _manual) return;
|
||||
if (_heardAt <= sentAt) _closed('No reply from the server');
|
||||
});
|
||||
}
|
||||
|
||||
void _probeIfQuiet() {
|
||||
final now = DateTime.now();
|
||||
final quiet = now.difference(_lastTraffic);
|
||||
_lastTraffic = now;
|
||||
if (quiet > quietProbeAfter) probe();
|
||||
}
|
||||
|
||||
void _stopWatching() {
|
||||
_probe?.cancel();
|
||||
_probe = null;
|
||||
}
|
||||
|
||||
void _onMessage(dynamic data) {
|
||||
_heardAt = _clock.elapsed;
|
||||
_lastTraffic = DateTime.now();
|
||||
if (data is! String) return;
|
||||
final Object? decoded;
|
||||
try {
|
||||
@@ -231,8 +328,10 @@ class PipelinesClient implements ApiGateway {
|
||||
if (decoded is! Map<String, dynamic>) return;
|
||||
final message = decoded;
|
||||
final id = message['id'];
|
||||
if (id is String && id.startsWith('flutter-probe-')) return;
|
||||
final pending = id is String ? _pending.remove(id) : null;
|
||||
if (pending != null) {
|
||||
_timeouts = 0;
|
||||
if (message['type'] == 'error') {
|
||||
final reason = '${message['error'] ?? ''}'.trim();
|
||||
pending.completeError(
|
||||
@@ -259,6 +358,7 @@ class PipelinesClient implements ApiGateway {
|
||||
|
||||
void _closed(String reason) {
|
||||
_generation++;
|
||||
_stopWatching();
|
||||
_cancelOpening();
|
||||
final channel = _channel;
|
||||
final subscription = _subscription;
|
||||
@@ -293,6 +393,7 @@ class PipelinesClient implements ApiGateway {
|
||||
Future<void> disconnect() async {
|
||||
_manual = true;
|
||||
_reconnect?.cancel();
|
||||
_stopWatching();
|
||||
final generation = ++_generation;
|
||||
_cancelOpening();
|
||||
final channel = _channel;
|
||||
|
||||
Reference in New Issue
Block a user