From b2ffc346c3301ad3412c48e9c7fc18db1d73281d Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Mon, 16 Nov 2026 08:01:50 +0100 Subject: [PATCH] Bound every Firebase and token HTTP call package:http has no timeout; a dead connection wedged sync forever. CliSession now wraps its client: 30 s to headers, 30 s per body chunk. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs --- lib/cli/cli_paths.dart | 26 ++++++++++ lib/cli/cli_session.dart | 35 ++++--------- lib/cli/timeout_client.dart | 58 +++++++++++++++++++++ pubspec.yaml | 2 +- test/cli/timeout_client_test.dart | 85 +++++++++++++++++++++++++++++++ 5 files changed, 181 insertions(+), 25 deletions(-) create mode 100644 lib/cli/cli_paths.dart create mode 100644 lib/cli/timeout_client.dart create mode 100644 test/cli/timeout_client_test.dart diff --git a/lib/cli/cli_paths.dart b/lib/cli/cli_paths.dart new file mode 100644 index 0000000..3cfe440 --- /dev/null +++ b/lib/cli/cli_paths.dart @@ -0,0 +1,26 @@ +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:todo/cli/cli_session.dart' show CliSession; + +/// Default data dir: `$XDG_DATA_HOME/todo-cli`, else `~/.local/share/todo-cli`. +String defaultDataDir(Map env) { + final xdg = env['XDG_DATA_HOME'] ?? ''; + final base = xdg.isNotEmpty + ? xdg + : p.join(env['HOME'] ?? '', '.local', 'share'); + return p.join(base, 'todo-cli'); +} + +/// Node ids of the installs Claude files notes through: the MCP server and +/// the CLI under the same data root as [defaultDataDir]. Missing ones are +/// skipped. +Set claudeNodeIds(Map env) { + final cli = defaultDataDir(env); + return { + for (final dir in [cli, p.join(p.dirname(cli), 'todo-mcp')]) + if (File(p.join(dir, CliSession.nodeIdFileName)) case final f + when f.existsSync()) + f.readAsStringSync().trim(), + }..remove(''); +} diff --git a/lib/cli/cli_session.dart b/lib/cli/cli_session.dart index 60ee67c..45c77d1 100644 --- a/lib/cli/cli_session.dart +++ b/lib/cli/cli_session.dart @@ -16,32 +16,13 @@ import 'package:http/http.dart' as http; import 'package:path/path.dart' as p; import 'package:todo/cli/file_credential_store.dart'; import 'package:todo/cli/pull_only_store.dart'; +import 'package:todo/cli/timeout_client.dart'; import 'package:todo/data/note_repository.dart'; import 'package:todo/sync/firebase_project.dart'; import 'package:todo/sync/sync_service.dart'; import 'package:uuid/uuid.dart'; -/// Default data dir: `$XDG_DATA_HOME/todo-cli`, else `~/.local/share/todo-cli`. -String defaultDataDir(Map env) { - final xdg = env['XDG_DATA_HOME'] ?? ''; - final base = xdg.isNotEmpty - ? xdg - : p.join(env['HOME'] ?? '', '.local', 'share'); - return p.join(base, 'todo-cli'); -} - -/// Node ids of the installs Claude files notes through: the MCP server and -/// the CLI under the same data root as [defaultDataDir]. Missing ones are -/// skipped. -Set claudeNodeIds(Map env) { - final cli = defaultDataDir(env); - return { - for (final dir in [cli, p.join(p.dirname(cli), 'todo-mcp')]) - if (File(p.join(dir, CliSession.nodeIdFileName)) case final f - when f.existsSync()) - f.readAsStringSync().trim(), - }..remove(''); -} +export 'package:todo/cli/cli_paths.dart'; /// The open state of one CLI invocation. Call [close] when done. class CliSession { @@ -83,13 +64,19 @@ class CliSession { /// Opens (creating on first use) the session rooted at [dataDir]. /// /// [seedCredentials] is todo's desktop session, read once and never written. - /// [httpClient] replaces the real network client (tests only). + /// [httpClient] replaces the real network client (tests only). Either way + /// every request is bounded by [requestTimeout] (see [TimeoutClient]). static Future open( String dataDir, { required String seedCredentials, String seedApp = 'todo', http.Client? httpClient, + Duration requestTimeout = const Duration(seconds: 30), }) async { + final network = TimeoutClient( + httpClient ?? http.Client(), + timeout: requestTimeout, + ); final dir = Directory(dataDir); await dir.create(recursive: true); // Holds a database-write credential: owner-only, like ~/.config/todo. @@ -102,7 +89,7 @@ class CliSession { ); final auth = FirebaseTokenProvider( apiKey: kProject.apiKey, - httpClient: httpClient, + httpClient: network, store: FileCredentialStore( file: File(p.join(dataDir, credentialsFileName)), seedFile: File(seedCredentials), @@ -118,7 +105,7 @@ class CliSession { final firebase = FirebaseRestClient( databaseUrl: kProject.databaseUrl, auth: auth, - httpClient: httpClient, + httpClient: network, ); return CliSession( dataDir, diff --git a/lib/cli/timeout_client.dart b/lib/cli/timeout_client.dart new file mode 100644 index 0000000..7aa3af5 --- /dev/null +++ b/lib/cli/timeout_client.dart @@ -0,0 +1,58 @@ +import 'dart:async'; + +import 'package:http/http.dart' as http; + +/// An HTTP client whose every request is bounded. +/// +/// `package:http` has no timeout of its own, and neither do the Firebase and +/// token clients built on it: one dead connection (after boot, a network +/// blip) made a sync wait forever and wedged the MCP server's serial queue. +/// [timeout] bounds the wait for the response headers and then each gap +/// between body chunks, so a large body that keeps moving is never cut off. +class TimeoutClient extends http.BaseClient { + /// Wraps [_inner]; each wait fails with a [TimeoutException] after [timeout]. + TimeoutClient(this._inner, {this.timeout = const Duration(seconds: 30)}); + + final http.Client _inner; + + /// Longest wait for the headers, and for the next body chunk. + final Duration timeout; + + @override + Future send(http.BaseRequest request) async { + final response = await _inner + .send(request) + .timeout( + timeout, + onTimeout: () => throw TimeoutException( + '${request.method} ${request.url.host} got no response', + timeout, + ), + ); + return http.StreamedResponse( + response.stream.timeout( + timeout, + onTimeout: (sink) { + sink + ..addError( + TimeoutException( + '${request.method} ${request.url.host} body stalled', + timeout, + ), + ) + ..close(); + }, + ), + response.statusCode, + contentLength: response.contentLength, + request: response.request, + headers: response.headers, + isRedirect: response.isRedirect, + persistentConnection: response.persistentConnection, + reasonPhrase: response.reasonPhrase, + ); + } + + @override + void close() => _inner.close(); +} diff --git a/pubspec.yaml b/pubspec.yaml index e909dee..e9bd7a5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 1.0.90+1 +version: 1.0.91+1 environment: sdk: ^3.12.2 diff --git a/test/cli/timeout_client_test.dart b/test/cli/timeout_client_test.dart new file mode 100644 index 0000000..56e3cf0 --- /dev/null +++ b/test/cli/timeout_client_test.dart @@ -0,0 +1,85 @@ +// Every Firebase and token call a CliSession makes is bounded: a request that +// never answers (dead connection, blackholed route) must fail with a +// TimeoutException instead of holding the MCP server's one-at-a-time queue. +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart' as http_testing; +import 'package:todo/cli/cli_session.dart'; +import 'package:todo/cli/timeout_client.dart'; + +import 'fake_rtdb.dart'; + +const _limit = Duration(milliseconds: 150); + +http.Client _answering({Stream>? body}) => + http_testing.MockClient.streaming( + (request, _) async => + http.StreamedResponse(body ?? Stream.value([111, 107]), 200), + ); + +void main() { + test('a fast response passes through untouched', () async { + final client = TimeoutClient(_answering(), timeout: _limit); + expect((await client.get(Uri.parse('http://x.test/'))).body, 'ok'); + }); + + test('[T-http-timeout] a request that never answers times out', () async { + final client = TimeoutClient( + http_testing.MockClient((_) => Completer().future), + timeout: _limit, + ); + await expectLater( + client.get(Uri.parse('http://x.test/')), + throwsA(isA()), + ); + }); + + test('a body that stalls after the headers times out', () async { + final stalled = StreamController>()..add([1]); + final client = TimeoutClient( + _answering(body: stalled.stream), + timeout: _limit, + ); + await expectLater( + client.get(Uri.parse('http://x.test/')), + throwsA(isA()), + ); + await stalled.close(); + }); + + test('a slow but moving body is not cut off', () async { + final slow = Stream.periodic( + const Duration(milliseconds: 60), + (i) => [i], + ).take(5); + final client = TimeoutClient(_answering(body: slow), timeout: _limit); + expect( + (await client.get(Uri.parse('http://x.test/'))).bodyBytes, + hasLength(5), + ); + }); + + test( + '[T-http-timeout] a CliSession sync against a dead network fails', + () async { + final tmp = Directory.systemTemp.createTempSync('timeout_client'); + addTearDown(() => tmp.deleteSync(recursive: true)); + final session = await CliSession.open( + '${tmp.path}/data', + seedCredentials: writeSeedCredentials(tmp).path, + httpClient: http_testing.MockClient( + (_) => Completer().future, + ), + requestTimeout: _limit, + ); + addTearDown(session.close); + await expectLater( + session.sync(push: true), + throwsA(isA()), + ); + }, + ); +}