mirror of
https://github.com/kuhyx/todo-app.git
synced 2026-11-19 05:34:28 +01:00
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWXgrX1QxVjqMiz6KFs
This commit is contained in:
parent
0ce9c42ff6
commit
b2ffc346c3
26
lib/cli/cli_paths.dart
Normal file
26
lib/cli/cli_paths.dart
Normal file
@ -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<String, String> 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<String> claudeNodeIds(Map<String, String> 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('');
|
||||
}
|
||||
@ -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<String, String> 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<String> claudeNodeIds(Map<String, String> 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<CliSession> 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,
|
||||
|
||||
58
lib/cli/timeout_client.dart
Normal file
58
lib/cli/timeout_client.dart
Normal file
@ -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<http.StreamedResponse> 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();
|
||||
}
|
||||
@ -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
|
||||
|
||||
85
test/cli/timeout_client_test.dart
Normal file
85
test/cli/timeout_client_test.dart
Normal file
@ -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<List<int>>? 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<http.Response>().future),
|
||||
timeout: _limit,
|
||||
);
|
||||
await expectLater(
|
||||
client.get(Uri.parse('http://x.test/')),
|
||||
throwsA(isA<TimeoutException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('a body that stalls after the headers times out', () async {
|
||||
final stalled = StreamController<List<int>>()..add([1]);
|
||||
final client = TimeoutClient(
|
||||
_answering(body: stalled.stream),
|
||||
timeout: _limit,
|
||||
);
|
||||
await expectLater(
|
||||
client.get(Uri.parse('http://x.test/')),
|
||||
throwsA(isA<TimeoutException>()),
|
||||
);
|
||||
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<http.Response>().future,
|
||||
),
|
||||
requestTimeout: _limit,
|
||||
);
|
||||
addTearDown(session.close);
|
||||
await expectLater(
|
||||
session.sync(push: true),
|
||||
throwsA(isA<TimeoutException>()),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user