Retry transient media signing worker startup once

Signed-off-by: Tom Brow <tomb@block.xyz>
This commit is contained in:
Tom Brow
2026-10-18 15:17:52 -07:00
parent aee8135424
commit 6c5102ac40
3 changed files with 183 additions and 98 deletions

View File

@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
@@ -106,23 +107,36 @@ class MediaGetAuthService {
return result;
}
/// Keeps an in-flight consumer pending through one queue-saturation retry.
/// Keeps a consumer pending through one saturation or worker-startup retry.
///
/// Waits for the existing queue snapshot, then competes for normal admission.
/// At most 64 consumers may wait or retry in addition to the 64 signing jobs.
/// Excess waiters and second rejections fail without a retry loop.
/// Excess waiters and second failures are terminal. Only isolate spawn failures
/// are retried: signing/configuration errors and ambiguous remote runtime
/// errors are not evidence of a transient worker-startup failure.
Future<Map<String, String>> headersForAsyncWithRetry(String url) async {
try {
return await headersForAsync(url);
} on MediaAuthQueueFull catch (error) {
if (_pendingRetries >= _maxPendingRetries) rethrow;
_pendingRetries++;
try {
await error.drained;
return await headersForAsync(url);
} finally {
_pendingRetries--;
}
return _retryAfter(url, error.drained);
} on IsolateSpawnException {
return _retryAfter(url, _signingTail);
}
}
Future<Map<String, String>> _retryAfter(
String url,
Future<void> drained,
) async {
if (_pendingRetries >= _maxPendingRetries) {
throw MediaAuthQueueFull(drained);
}
_pendingRetries++;
try {
await drained;
return await headersForAsync(url);
} finally {
_pendingRetries--;
}
}

View File

@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
import 'package:buzz/features/channels/message_content.dart';
import 'package:buzz/shared/relay/media_auth.dart';
@@ -13,19 +14,38 @@ import 'package:http/testing.dart';
import 'package:video_player_platform_interface/video_player_platform_interface.dart';
class _SaturatedAuth extends MediaGetAuthService {
_SaturatedAuth({this.alwaysReject = false})
_SaturatedAuth({this.alwaysReject = false, this.workerFailure = false})
: super(baseUrl: 'https://example.com', nsec: null);
final bool alwaysReject;
final bool workerFailure;
final drained = Completer<void>();
int calls = 0;
@override
Future<Map<String, String>> headersForAsync(String url) async {
calls++;
if (calls == 1 || alwaysReject) throw MediaAuthQueueFull(drained.future);
if (calls == 1 || alwaysReject) {
if (workerFailure) {
await drained.future;
throw IsolateSpawnException('worker unavailable');
}
throw MediaAuthQueueFull(drained.future);
}
return {'Authorization': 'test-proof'};
}
}
class _PermanentFailureAuth extends MediaGetAuthService {
_PermanentFailureAuth(this.error)
: super(baseUrl: 'https://example.com', nsec: null);
final Object error;
int calls = 0;
@override
Future<Map<String, String>> headersForAsync(String url) async {
calls++;
throw error;
}
}
class _VideoPlatform extends VideoPlayerPlatform {
final sources = <DataSource>[];
@override
@@ -61,6 +81,21 @@ class _VideoPlatform extends VideoPlayerPlatform {
}
void main() {
test('permanent and ambiguous runtime failures are never retried', () async {
for (final error in [
ArgumentError('invalid signing key'),
StateError('signing failed'),
RemoteError('worker runtime error', ''),
]) {
final auth = _PermanentFailureAuth(error);
await expectLater(
auth.headersForAsyncWithRetry('https://example.com/media/a'),
throwsA(same(error)),
);
expect(auth.calls, 1);
}
});
test('bounds retry waiters before signing capacity drains', () async {
final auth = _SaturatedAuth(alwaysReject: true);
var rejected = 0;
@@ -102,97 +137,130 @@ void main() {
expect(auth.calls, 2);
});
testWidgets('mounted image succeeds after signing capacity drains', (
tester,
) async {
final auth = _SaturatedAuth();
final png = base64Decode(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=',
test('startup failures share the bounded retry permits', () async {
final auth = _SaturatedAuth(alwaysReject: true, workerFailure: true);
final requests = List.generate(
80,
(_) => auth
.headersForAsyncWithRetry('https://example.com/media/a')
.then<Object>((value) => value, onError: (Object error) => error),
);
var fetches = 0;
final client = MockClient((request) async {
fetches++;
expect(request.headers['Authorization'], 'test-proof');
return http.Response.bytes(png, 200);
});
await tester.pumpWidget(
MaterialApp(
home: Image(
image: MediaImageProvider(
url: 'https://example.com/media/recovery.png',
auth: auth,
client: client,
),
errorBuilder: (_, _, _) => const Text('failed'),
),
),
);
await tester.pump();
final element = tester.element(find.byType(Image));
expect(auth.calls, 1);
expect(fetches, 0);
auth.drained.complete();
await tester.runAsync(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
});
await tester.pumpAndSettle();
expect(tester.element(find.byType(Image)), same(element));
expect(auth.calls, 2);
expect(fetches, 1);
expect(tester.widget<RawImage>(find.byType(RawImage)).image, isNotNull);
expect(find.text('failed'), findsNothing);
await tester.pumpWidget(const SizedBox());
PaintingBinding.instance.imageCache.clear();
PaintingBinding.instance.imageCache.clearLiveImages();
client.close();
final results = await Future.wait(requests);
expect(results.whereType<MediaAuthQueueFull>(), hasLength(16));
expect(results.whereType<IsolateSpawnException>(), hasLength(64));
expect(auth.calls, 144);
await expectLater(
auth.headersForAsyncWithRetry('https://example.com/media/a'),
throwsA(isA<IsolateSpawnException>()),
);
expect(auth.calls, 146);
});
testWidgets(
'mounted posterless video succeeds after signing capacity drains',
(tester) async {
const url = 'https://example.com/media/recovery.mp4';
final auth = _SaturatedAuth();
final previous = VideoPlayerPlatform.instance;
final platform = _VideoPlatform();
VideoPlayerPlatform.instance = platform;
addTearDown(() => VideoPlayerPlatform.instance = previous);
await tester.pumpWidget(
ProviderScope(
overrides: [mediaGetAuthServiceProvider.overrideWithValue(auth)],
child: MaterialApp(
theme: AppTheme.light(),
home: const AppMarkdownTheme(
child: Scaffold(
body: MessageContent(
content: '![video]($url)',
tags: [
['imeta', 'url $url', 'm video/mp4'],
],
test('startup recovery is bounded to one retry', () async {
final auth = _SaturatedAuth(alwaysReject: true, workerFailure: true);
auth.drained.complete();
await expectLater(
auth.headersForAsyncWithRetry('https://example.com/media/a'),
throwsA(isA<IsolateSpawnException>()),
);
expect(auth.calls, 2);
});
for (final workerFailure in [false, true]) {
testWidgets(
'mounted image workerFailure=$workerFailure succeeds after signing capacity drains',
(tester) async {
final auth = _SaturatedAuth(workerFailure: workerFailure);
final png = base64Decode(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=',
);
var fetches = 0;
final client = MockClient((request) async {
fetches++;
expect(request.headers['Authorization'], 'test-proof');
return http.Response.bytes(png, 200);
});
await tester.pumpWidget(
MaterialApp(
home: Image(
image: MediaImageProvider(
url: 'https://example.com/media/recovery.png',
auth: auth,
client: client,
),
errorBuilder: (_, _, _) => const Text('failed'),
),
),
);
await tester.pump();
final element = tester.element(find.byType(Image));
expect(auth.calls, 1);
expect(fetches, 0);
auth.drained.complete();
await tester.runAsync(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
});
await tester.pumpAndSettle();
expect(tester.element(find.byType(Image)), same(element));
expect(auth.calls, 2);
expect(fetches, 1);
expect(tester.widget<RawImage>(find.byType(RawImage)).image, isNotNull);
expect(find.text('failed'), findsNothing);
await tester.pumpWidget(const SizedBox());
PaintingBinding.instance.imageCache.clear();
PaintingBinding.instance.imageCache.clearLiveImages();
client.close();
},
);
testWidgets(
'mounted posterless video workerFailure=$workerFailure succeeds after signing capacity drains',
(tester) async {
const url = 'https://example.com/media/recovery.mp4';
final auth = _SaturatedAuth(workerFailure: workerFailure);
final previous = VideoPlayerPlatform.instance;
final platform = _VideoPlatform();
VideoPlayerPlatform.instance = platform;
addTearDown(() => VideoPlayerPlatform.instance = previous);
await tester.pumpWidget(
ProviderScope(
overrides: [mediaGetAuthServiceProvider.overrideWithValue(auth)],
child: MaterialApp(
theme: AppTheme.light(),
home: const AppMarkdownTheme(
child: Scaffold(
body: MessageContent(
content: '![video]($url)',
tags: [
['imeta', 'url $url', 'm video/mp4'],
],
),
),
),
),
),
),
);
await tester.pump();
final element = tester.element(find.byType(MessageContent));
expect(auth.calls, 1);
expect(platform.sources, isEmpty);
auth.drained.complete();
await tester.pumpAndSettle();
expect(tester.element(find.byType(MessageContent)), same(element));
expect(auth.calls, 2);
expect(
platform.sources.single.httpHeaders['Authorization'],
'test-proof',
);
expect(
find.byKey(const ValueKey('message-media-video-first-frame:$url')),
findsOneWidget,
);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
await tester.pump();
},
);
);
await tester.pump();
final element = tester.element(find.byType(MessageContent));
expect(auth.calls, 1);
expect(platform.sources, isEmpty);
auth.drained.complete();
await tester.pumpAndSettle();
expect(tester.element(find.byType(MessageContent)), same(element));
expect(auth.calls, 2);
expect(
platform.sources.single.httpHeaders['Authorization'],
'test-proof',
);
expect(
find.byKey(const ValueKey('message-media-video-first-frame:$url')),
findsOneWidget,
);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
await tester.pump();
},
);
}
}

View File

@@ -48,7 +48,10 @@ void main() {
),
);
await tester.pumpAndSettle();
expect(auth.requests, [url]);
expect(
auth.requests,
failure.value is IsolateSpawnException ? [url, url] : [url],
);
expect(find.text('Video attachment'), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox.shrink());