Skip to content

Commit 9bcb3e4

Browse files
authored
perf(mobile): hash upload payloads in bounded worker chunks (#9747)
Follow-up to #9736, which moved upload hashing off the UI isolate with `compute`. `compute(_sha256Hex, bytes)` copies the whole prepared payload into the worker while the uploader keeps the original for the PUT. For a 100 MiB attachment that adds about 100 MiB to peak memory before the first request. This streams the payload to a worker isolate in 1 MiB chunks, with one chunk in flight at a time (the worker acks each chunk before the next is sent). Each chunk is copied with `TransferableTypedData.fromList` on its own slice, since sending a `sublistView` would copy the whole backing buffer. The digest, the `X-SHA-256` header, the signed Blossom `x` tag and the cancellation checks are unchanged. ### Validation In a 100 MiB AOT probe, peak RSS was 114 MiB hashing inline, 214 MiB with the whole-buffer `compute` handoff, and 141 MiB with acked 1 MiB chunks, at about the same hash time (611 / 622 / 614 ms). Added tests in `mobile/test/shared/relay/media_upload_test.dart`: the worker digest matches `crypto.sha256` for a 2 MiB + 123 byte payload, sends three chunks with at most 1 MiB in flight, and handles an empty payload. ### Regressions - UI responsiveness: the hash still runs off the UI isolate. The UI isolate now does one 1 MiB slice copy per chunk instead of one full copy. - Latency: hash time is about the same as with `compute` in the probe. Small uploads pay one isolate spawn, as before. --------- Signed-off-by: Tom Brow <tomb@block.xyz>
1 parent 890824f commit 9bcb3e4

2 files changed

Lines changed: 127 additions & 2 deletions

File tree

‎mobile/lib/shared/relay/media_upload.dart‎

Lines changed: 85 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import 'dart:async';
22
import 'dart:convert';
33
import 'dart:io';
4+
import 'dart:isolate';
45
import 'dart:math' as math;
56

67
import 'package:file_selector/file_selector.dart' as file_selector;
@@ -250,6 +251,7 @@ class MediaUploadService {
250251
final DateTime Function() _now;
251252
final http.Client _http;
252253
final bool _ownsHttpClient;
254+
final HashChunkObserver? _onHashChunk;
253255

254256
MediaUploadService({
255257
required String baseUrl,
@@ -266,7 +268,9 @@ class MediaUploadService {
266268
ReadClipboardImage? readClipboardImage,
267269
DateTime Function()? now,
268270
http.Client? httpClient,
271+
@visibleForTesting HashChunkObserver? onHashChunk,
269272
}) : _baseUrl = baseUrl,
273+
_onHashChunk = onHashChunk,
270274
_nsec = nsec,
271275
_pickGalleryImage = pickGalleryImage,
272276
_pickGalleryImages =
@@ -559,7 +563,7 @@ class MediaUploadService {
559563
throw Exception('unsupported file type: $mimeType');
560564
}
561565

562-
final sha256 = await compute(_sha256Hex, bytes);
566+
final sha256 = await sha256HexInWorker(bytes, onChunk: _onHashChunk);
563567
var response = await _sendUploadRequest(
564568
bytes: bytes,
565569
mimeType: mimeType,
@@ -800,7 +804,86 @@ Stream<List<int>> _uploadByteStream(
800804
}
801805
}
802806

803-
String _sha256Hex(Uint8List bytes) => crypto.sha256.convert(bytes).toString();
807+
const _hashChunkSize = 1024 * 1024;
808+
809+
/// A step in the chunked hash handoff: a chunk was sent to the worker, or the
810+
/// worker acknowledged it.
811+
enum HashChunkEvent { sent, acked }
812+
813+
/// Observes the chunked hash handoff in order. [bytes] is the total sent so
814+
/// far for [HashChunkEvent.sent], and the total the worker reports having
815+
/// received for [HashChunkEvent.acked].
816+
typedef HashChunkObserver = void Function(HashChunkEvent event, int bytes);
817+
818+
/// Hashes [bytes] on a worker isolate, one bounded chunk at a time, so the
819+
/// payload is never copied into the worker in full.
820+
@visibleForTesting
821+
Future<String> sha256HexInWorker(
822+
Uint8List bytes, {
823+
HashChunkObserver? onChunk,
824+
}) async {
825+
final port = ReceivePort();
826+
final messages = StreamIterator<Object?>(port);
827+
Isolate? worker;
828+
Future<Object> next() async {
829+
if (!await messages.moveNext()) throw StateError('hash port closed');
830+
final message = messages.current;
831+
if (message == null) throw StateError('hash worker exited early');
832+
if (message is List) throw RemoteError('${message[0]}', '${message[1]}');
833+
return message;
834+
}
835+
836+
try {
837+
worker = await Isolate.spawn(
838+
_hashChunks,
839+
port.sendPort,
840+
onError: port.sendPort,
841+
onExit: port.sendPort,
842+
);
843+
final chunks = await next() as SendPort;
844+
for (var start = 0; start < bytes.length; start += _hashChunkSize) {
845+
final end = math.min(start + _hashChunkSize, bytes.length);
846+
// fromList copies only this slice; sending the view itself would copy
847+
// the whole backing buffer.
848+
chunks.send(
849+
TransferableTypedData.fromList([
850+
Uint8List.sublistView(bytes, start, end),
851+
]),
852+
);
853+
onChunk?.call(HashChunkEvent.sent, end);
854+
// ack: one chunk in flight at a time
855+
final received = await next() as int;
856+
onChunk?.call(HashChunkEvent.acked, received);
857+
}
858+
chunks.send(null);
859+
return await next() as String;
860+
} finally {
861+
await messages.cancel();
862+
port.close();
863+
worker?.kill();
864+
}
865+
}
866+
867+
Future<void> _hashChunks(SendPort main) async {
868+
final chunks = ReceivePort();
869+
late crypto.Digest digest;
870+
final input = crypto.sha256.startChunkedConversion(
871+
ChunkedConversionSink<crypto.Digest>.withCallback(
872+
(digests) => digest = digests.single,
873+
),
874+
);
875+
main.send(chunks.sendPort);
876+
var received = 0;
877+
await for (final chunk in chunks) {
878+
if (chunk == null) break;
879+
final bytes = (chunk as TransferableTypedData).materialize().asUint8List();
880+
input.add(bytes);
881+
received += bytes.length;
882+
main.send(received);
883+
}
884+
input.close();
885+
main.send(digest.toString());
886+
}
804887

805888
String? _tryDetectImageMimeType(Uint8List bytes) {
806889
try {

‎mobile/test/shared/relay/media_upload_test.dart‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1191,7 +1191,9 @@ void main() {
11911191
final bytes = Uint8List(2 * 1024 * 1024)
11921192
..first = 1
11931193
..last = 2;
1194+
final hashEvents = <(HashChunkEvent, int)>[];
11941195
final service = MediaUploadService(
1196+
onHashChunk: (event, count) => hashEvents.add((event, count)),
11951197
baseUrl: 'https://relay.example',
11961198
nsec: nostr.Keys.generate().nsec,
11971199
httpClient: http_testing.MockClient((request) async {
@@ -1216,6 +1218,46 @@ void main() {
12161218
XFile.fromData(bytes, name: 'attachment.bin'),
12171219
);
12181220
expect(descriptor.size, bytes.length);
1221+
expect(hashEvents, [
1222+
(HashChunkEvent.sent, 1024 * 1024),
1223+
(HashChunkEvent.acked, 1024 * 1024),
1224+
(HashChunkEvent.sent, 2 * 1024 * 1024),
1225+
(HashChunkEvent.acked, 2 * 1024 * 1024),
1226+
]);
1227+
});
1228+
1229+
test(
1230+
'hashes in bounded worker chunks without copying the payload',
1231+
() async {
1232+
final bytes = Uint8List.fromList(
1233+
List.generate(2 * 1024 * 1024 + 123, (i) => (i * 31 + 7) & 0xff),
1234+
);
1235+
final events = <(HashChunkEvent, int)>[];
1236+
1237+
final digest = await sha256HexInWorker(
1238+
bytes,
1239+
onChunk: (event, count) => events.add((event, count)),
1240+
);
1241+
1242+
expect(digest, crypto.sha256.convert(bytes).toString());
1243+
// Each send is followed by the worker's ack of exactly the bytes sent
1244+
// so far, so only one chunk is ever in flight.
1245+
expect(events, [
1246+
(HashChunkEvent.sent, 1024 * 1024),
1247+
(HashChunkEvent.acked, 1024 * 1024),
1248+
(HashChunkEvent.sent, 2 * 1024 * 1024),
1249+
(HashChunkEvent.acked, 2 * 1024 * 1024),
1250+
(HashChunkEvent.sent, bytes.length),
1251+
(HashChunkEvent.acked, bytes.length),
1252+
]);
1253+
},
1254+
);
1255+
1256+
test('hashes an empty payload in the worker', () async {
1257+
expect(
1258+
await sha256HexInWorker(Uint8List(0)),
1259+
crypto.sha256.convert(const <int>[]).toString(),
1260+
);
12191261
});
12201262

12211263
test('sanitizes generic filenames to relay imeta constraints', () async {

0 commit comments

Comments
 (0)