From 9bcb3e45a426bc4b232f4731f46d6015ed0781ab Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Thu, 19 Nov 2026 14:21:26 -0800 Subject: [PATCH] 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 --- mobile/lib/shared/relay/media_upload.dart | 87 ++++++++++++++++++- .../test/shared/relay/media_upload_test.dart | 42 +++++++++ 2 files changed, 127 insertions(+), 2 deletions(-) diff --git a/mobile/lib/shared/relay/media_upload.dart b/mobile/lib/shared/relay/media_upload.dart index fa58685478..6a70b587b3 100644 --- a/mobile/lib/shared/relay/media_upload.dart +++ b/mobile/lib/shared/relay/media_upload.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import 'dart:isolate'; import 'dart:math' as math; import 'package:file_selector/file_selector.dart' as file_selector; @@ -250,6 +251,7 @@ class MediaUploadService { final DateTime Function() _now; final http.Client _http; final bool _ownsHttpClient; + final HashChunkObserver? _onHashChunk; MediaUploadService({ required String baseUrl, @@ -266,7 +268,9 @@ class MediaUploadService { ReadClipboardImage? readClipboardImage, DateTime Function()? now, http.Client? httpClient, + @visibleForTesting HashChunkObserver? onHashChunk, }) : _baseUrl = baseUrl, + _onHashChunk = onHashChunk, _nsec = nsec, _pickGalleryImage = pickGalleryImage, _pickGalleryImages = @@ -559,7 +563,7 @@ class MediaUploadService { throw Exception('unsupported file type: $mimeType'); } - final sha256 = await compute(_sha256Hex, bytes); + final sha256 = await sha256HexInWorker(bytes, onChunk: _onHashChunk); var response = await _sendUploadRequest( bytes: bytes, mimeType: mimeType, @@ -800,7 +804,86 @@ Stream> _uploadByteStream( } } -String _sha256Hex(Uint8List bytes) => crypto.sha256.convert(bytes).toString(); +const _hashChunkSize = 1024 * 1024; + +/// A step in the chunked hash handoff: a chunk was sent to the worker, or the +/// worker acknowledged it. +enum HashChunkEvent { sent, acked } + +/// Observes the chunked hash handoff in order. [bytes] is the total sent so +/// far for [HashChunkEvent.sent], and the total the worker reports having +/// received for [HashChunkEvent.acked]. +typedef HashChunkObserver = void Function(HashChunkEvent event, int bytes); + +/// Hashes [bytes] on a worker isolate, one bounded chunk at a time, so the +/// payload is never copied into the worker in full. +@visibleForTesting +Future sha256HexInWorker( + Uint8List bytes, { + HashChunkObserver? onChunk, +}) async { + final port = ReceivePort(); + final messages = StreamIterator(port); + Isolate? worker; + Future next() async { + if (!await messages.moveNext()) throw StateError('hash port closed'); + final message = messages.current; + if (message == null) throw StateError('hash worker exited early'); + if (message is List) throw RemoteError('${message[0]}', '${message[1]}'); + return message; + } + + try { + worker = await Isolate.spawn( + _hashChunks, + port.sendPort, + onError: port.sendPort, + onExit: port.sendPort, + ); + final chunks = await next() as SendPort; + for (var start = 0; start < bytes.length; start += _hashChunkSize) { + final end = math.min(start + _hashChunkSize, bytes.length); + // fromList copies only this slice; sending the view itself would copy + // the whole backing buffer. + chunks.send( + TransferableTypedData.fromList([ + Uint8List.sublistView(bytes, start, end), + ]), + ); + onChunk?.call(HashChunkEvent.sent, end); + // ack: one chunk in flight at a time + final received = await next() as int; + onChunk?.call(HashChunkEvent.acked, received); + } + chunks.send(null); + return await next() as String; + } finally { + await messages.cancel(); + port.close(); + worker?.kill(); + } +} + +Future _hashChunks(SendPort main) async { + final chunks = ReceivePort(); + late crypto.Digest digest; + final input = crypto.sha256.startChunkedConversion( + ChunkedConversionSink.withCallback( + (digests) => digest = digests.single, + ), + ); + main.send(chunks.sendPort); + var received = 0; + await for (final chunk in chunks) { + if (chunk == null) break; + final bytes = (chunk as TransferableTypedData).materialize().asUint8List(); + input.add(bytes); + received += bytes.length; + main.send(received); + } + input.close(); + main.send(digest.toString()); +} String? _tryDetectImageMimeType(Uint8List bytes) { try { diff --git a/mobile/test/shared/relay/media_upload_test.dart b/mobile/test/shared/relay/media_upload_test.dart index 10a3a4d408..2470a5d18d 100644 --- a/mobile/test/shared/relay/media_upload_test.dart +++ b/mobile/test/shared/relay/media_upload_test.dart @@ -1191,7 +1191,9 @@ void main() { final bytes = Uint8List(2 * 1024 * 1024) ..first = 1 ..last = 2; + final hashEvents = <(HashChunkEvent, int)>[]; final service = MediaUploadService( + onHashChunk: (event, count) => hashEvents.add((event, count)), baseUrl: 'https://relay.example', nsec: nostr.Keys.generate().nsec, httpClient: http_testing.MockClient((request) async { @@ -1216,6 +1218,46 @@ void main() { XFile.fromData(bytes, name: 'attachment.bin'), ); expect(descriptor.size, bytes.length); + expect(hashEvents, [ + (HashChunkEvent.sent, 1024 * 1024), + (HashChunkEvent.acked, 1024 * 1024), + (HashChunkEvent.sent, 2 * 1024 * 1024), + (HashChunkEvent.acked, 2 * 1024 * 1024), + ]); + }); + + test( + 'hashes in bounded worker chunks without copying the payload', + () async { + final bytes = Uint8List.fromList( + List.generate(2 * 1024 * 1024 + 123, (i) => (i * 31 + 7) & 0xff), + ); + final events = <(HashChunkEvent, int)>[]; + + final digest = await sha256HexInWorker( + bytes, + onChunk: (event, count) => events.add((event, count)), + ); + + expect(digest, crypto.sha256.convert(bytes).toString()); + // Each send is followed by the worker's ack of exactly the bytes sent + // so far, so only one chunk is ever in flight. + expect(events, [ + (HashChunkEvent.sent, 1024 * 1024), + (HashChunkEvent.acked, 1024 * 1024), + (HashChunkEvent.sent, 2 * 1024 * 1024), + (HashChunkEvent.acked, 2 * 1024 * 1024), + (HashChunkEvent.sent, bytes.length), + (HashChunkEvent.acked, bytes.length), + ]); + }, + ); + + test('hashes an empty payload in the worker', () async { + expect( + await sha256HexInWorker(Uint8List(0)), + crypto.sha256.convert(const []).toString(), + ); }); test('sanitizes generic filenames to relay imeta constraints', () async {