Skip to content

V- Modal AI: Visual Video / Image Search - Flutter Video SDK

Release Flutter SDK from 7dd88239fd2e7a3f0c94b89e18ceaa003f233a32

vmodal-release-app4d4c800f2ff9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f7cab2a..ec454f4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,16 @@
+## 1.1.0
+
+- Streamed signed upload bodies with awaited socket backpressure, exact file
+ ranges, source-version checks, and bounded body/response timeouts.
+- Enforced one signed-upload concurrency budget across bulk multipart tasks and
+ coalesced monotonic progress before O(1) aggregation.
+- Added bounded image downloads to caller-owned sinks and atomic files, plus a
+ smaller per-call cap for buffered image responses.
+- Added response-body idle timeouts with attempt-scoped GET retries and bounded
+ chunked JSON decoding.
+- Added a throttled upload/RSS benchmark harness and public caller injection for
+ `HttpVmodalTransport` without adding native HTTP dependencies.
+
## 1.0.0
- Added the immutable `VModal`, `VModalProject`, and `VModalScope` facade.
diff --git a/README.md b/README.md
index f69cb89..4a67254 100644
--- a/README.md
+++ b/README.md
@@ -168,6 +168,13 @@ print('Ready: ${uploaded.fileName}');
Signed single upload is the production default for every file size. Multipart upload is experimental and must be enabled explicitly with `VideoUploadOptions(multipart: true)`; it fails with `FeatureDisabled` when the complete backend route family is unavailable.
+Uploads use exact file ranges, awaited socket streaming, coalesced progress, and
+one network-concurrency budget per bulk task. For image caches, use
+`writeImageFromUrl` with a caller-owned sink or `saveImageFromUrl` for atomic
+file replacement instead of buffering the image. See
+[the performance guide](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/doc/performance.md)
+for limits, timeout behavior, and the benchmark command.
+
## Designed for real mobile lifecycles
- Rotate credentials without rebuilding the client: `keys.rotate(newApiKey)`.
@@ -346,5 +353,3 @@ Get started today at [www.v-modal.com](https://www.v-modal.com), read the [devel
<img src="https://gettrack.link/p/github_sdk_flutter" width="1" height="1" alt="" style="display:none" />
-
-
diff --git a/RELEASE_METADATA b/RELEASE_METADATA
index 133bb47..e4cf292 100644
--- a/RELEASE_METADATA
+++ b/RELEASE_METADATA
@@ -1 +1 @@
-Source-vmx-api: f836cc003c6e8bbf52367cd8fb1ef82e09f1f193
+Source-vmx-api: 7dd88239fd2e7a3f0c94b89e18ceaa003f233a32
diff --git a/SOURCE_MANIFEST.sha256 b/SOURCE_MANIFEST.sha256
index 230cce9..5c5629d 100644
--- a/SOURCE_MANIFEST.sha256
+++ b/SOURCE_MANIFEST.sha256
@@ -2,16 +2,17 @@ e789cd4d1bed8a78ec8014c5c5913e300f81b63ea56a56aacb0dfec3b5e7ce2b ./.flutter-ver
fbbda2e7e29bbd860539a9ca18c478f3b02de140f25a872c19a6dbecd11bc94b ./.github/workflows/publish.yml
a98f72526420d47e76b9b4e67ac86acd06b7088ad1f4c35617b11b09e59346ea ./.gitleaks.toml
5115d06bd9913f466d50fcbf8ad8890372349060c54a4581f3481ea084cfdec6 ./.pubignore
-0e35aa931a7e39b40c6bac4c0a4ee4ddc6e0de1e26d8f0a47d4f7e72326f3574 ./CHANGELOG.md
+c2d0f70729c0293aaf35ea6c0d701dbda4a97b0bc0f7d08b7e29845b24944255 ./CHANGELOG.md
37b7148216ac6090e36adfb699d642b8dd1e1b8ba99870e65e88733947a59fa6 ./LICENSE
-b10b6747e23e7a3833882317c86c78cfa9b187faeb9914407d82fabc1c712bcf ./README.md
-e21bc90a60861b62b32f7b74d9c4bfda8d6fdf40cdaffe15c4a51025d6ba41a4 ./RELEASE_METADATA
+d63378f391ef251ea0afb8841c6886841cab25352d845630c1a117f83e281723 ./README.md
+a7c75e0532999a4f8c486aa112bf83d89461b1a0fdfc18a55a4e41553b63f705 ./RELEASE_METADATA
def7e4f643adff5b01b877b6a7fa5b2381612b693c0bf06bd232ee0f7197d342 ./analysis_options.yaml
8c2d096dc399d9bea2fcc5ae19d987e7458c8503cf2a7edf1f1497ae00d681aa ./build.sh
4f18642680fb433554a5523d00bd99e0d650af340bcaebe628f59f63ac84e458 ./dartdoc_options.yaml
75461620cf3a062f4dad10e034952b82cca461b483788de1f46c539aca8b0f0f ./doc/manage_api_key.md
+a66d39da0983a994474fa516f81fd41bbb131efbd69c955891a41781a76daf24 ./doc/performance.md
cae6114908952cf81a908b7fcc8c0ba4ce3f866e9dbaf974303273f334e0e3f6 ./doc/release.md
-20aed670d90634d385e08b8010f54a18ba24cc3ed90c04261a4abaaf62bc0d71 ./doc/sdk_contract.md
+7d849dcf1d4c8537ee33e8fdd6282d3bbe2244e68a9c997dcaf77f23db1b5562 ./doc/sdk_contract.md
2c07c5319044416d722732f731cc709fc6f6f3e375861bb6b5326a8768258de5 ./doc/sdk_doc.md
6139d92cf19577ec2d920daa5416d2982e425f63639f858201c91caf39b109bf ./doc/search_app.md
7b0acfc01cfa4c8bf3af8aeb19741e65b8e9406935d9ab8e0f4cb84547483e55 ./doc/transcode_360.md
@@ -78,7 +79,7 @@ fd367b6c43006d61b730f674970dd48b9f662c8f2264e52ffc1558102a2c9f2d ./example/01_f
add68b905971dedfcc0d0b5b7118030de5925ba8c081ad9815463699e3a444ad ./example/01_full_app/ios/Runner/SceneDelegate.swift
5e8f4908dacea6f29b2a790e4d38bf5fded69096063f9a27a2f21584d62b30c0 ./example/01_full_app/ios/RunnerTests/RunnerTests.swift
f008f1671accf86a236929d5163da59f7e53015a53ef1578a5e8c31699077311 ./example/01_full_app/lib/main.dart
-b47637ff3628c6e7d897a5f6eed123cd74bb6b98850352325bfad8ca239a2538 ./example/01_full_app/pubspec.lock
+be95ef4175d5612d170388c188fffecacb136f56d9d77ffc97eecd6bc611d409 ./example/01_full_app/pubspec.lock
875af508f7c6d9654985b402c26364d4ca6b1c06b3846a71a77997b905e2ad6e ./example/01_full_app/pubspec.yaml
90a79c18d158515dab7616e273e9effd9cc0726c56fe6ce3cc123b5a8a8337cc ./example/01_full_app/test/widget_test.dart
3c54909945bc3d6fe78d70a0f673377b6ab6b0c6c4b86c02291f5fbefdc9736f ./example/02_users/README.md
@@ -89,30 +90,30 @@ a15f6dfd128db08dff98caa715b2c5041812f794fbfe283098bb98b94b345841 ./example/02_u
b373342c889d099d99a3209cb01cea188b53eb5b43ae26cad952abf5fda833bd ./example/02_users/lib/src/example_session.dart
94fc4c3cfb6774eee9f39c1d97447abab52105ce6be85457d8f9d25bff3014ab ./example/02_users/lib/user_examples.dart
4d7075d4d50457aa65b2a91d4bcdf9778ae95e86c6c276a91172dcc5cd60017c ./example/02_users/lib/user_streams.dart
-3e2586912a086f3687fb05d2b7d0f268bd5ad02d4a2d01bc1075cb4aa93ceb39 ./example/02_users/pubspec.lock
+8b94cce29d65df6bee41121595fb8181ffca9d54ef018036fe76fab96166c828 ./example/02_users/pubspec.lock
fa541e11cb4b9b791630b658c6856743ec4c31d957deb285ed031e7d4c2d48c6 ./example/02_users/pubspec.yaml
31f28ca22dfb931fe963d2f766d8b5cba3c2722bca839787a506f1a692393a8c ./example/02_users/test/user_examples_test.dart
23756b83470b1f25f6a7e6b5a6270f123a5224e49fd8e2eda36001358951b688 ./install.sh
7becacd31a8d134fa435b39cd819798d5fbf58f89b9f30c50362e2dcf757aaed ./lib/src/adaptive_upload.dart
9464fff0c519a1ce70cddefb3e3eaa95d07b97ccdaf5b8381c01d7c88767ae83 ./lib/src/api_key_provider.dart
-d796fc674bb0b8c784fac0f0470b6ff816c98d9ace4b90f593912e5479e45d4e ./lib/src/client.dart
-3dbff9f98c140c586e363dc650c60efc6754cf0d09f16f5fd937706ca4eb59f4 ./lib/src/collection_uploads.dart
-58e4e7162a6c46d2981935649a3f1d40c969dc1fc3a81cab34f518673a479e6a ./lib/src/config.dart
+cffedb3aa8d7b94d0afbe946cf6af41ec4d9b588a6fdbb6d224c2a31e103da3b ./lib/src/client.dart
+e253b7c657eac4f7598d196e3943a05ab3a4da8568d5f45da41112bfb8e0c532 ./lib/src/collection_uploads.dart
+3591a3bfd33164aadcd65b5d5b02bafc5f36b577a304a0e87bec8fb7ac34bb8b ./lib/src/config.dart
d3e03d9a72a499659c70f2296115d1d3138b9370a017e027d8255f85f7fb1c5c ./lib/src/content_scope.dart
873d969cfed5c725d34df0fd0c8769462b56992cf523710fcf741a81fa1bbcad ./lib/src/errors.dart
-8fcee5e6ae16462935bdd3b520b7ed5f15724074f9b244ed8271511e57d21af6 ./lib/src/http.dart
+027174edd680e69e067453695f62680fd90b16c78f74a6999ab926cd2fd257dc ./lib/src/http.dart
7670598bf28a23808d0e0bd3e3ea1ec7270fbc450caef2ecc1c0ab0921d17538 ./lib/src/models.dart
-ed22b7665e09c9f2f4158c225affe6527b7d3eb921db0ccdf06c01c8cf31db96 ./lib/src/resources.dart
+248cc2f57edbcd5c8686ea03854403d704a3d8c18086dc525a5609226728ad92 ./lib/src/resources.dart
43770c621bffccf69eacebd1e3b297503ca288093c848f0e8ccbd118d7f0d88a ./lib/src/routes.dart
27056230065682f3ea3aa747c39c08950dcdca87387f4733adfad18f4b345b06 ./lib/src/routes.g.dart
42331852249c8f99874a5e3889c752fd344ad8a5301ede246d5a4fbccb4191f2 ./lib/src/transcode.dart
-f0e69d1016f82fbad2a96434129a54a0129f095a0e138cce555db37c8120023f ./lib/src/transport.dart
-9b42b147074ac0d54e23ffd148877750f04eb050a9061827459bd5e676522bed ./lib/src/upload.dart
+b2ccf933ff5406ecd0bdbe9ad695ccf790926ceb8bbfcd4068490d2d7683fcc9 ./lib/src/transport.dart
+8a9ab7a18da892c10f4004d0188f71cf60c31d3207b08617d70f0a7e4fde4d0e ./lib/src/upload.dart
785e261474d92bc6aa5da8a4dcc9429577b590dbeda2098da2c581d862e3f6a8 ./lib/src/utils.dart
b226ddcc0b8cb58b4753545752c2df1c6301bdf76842730e7f6ecf2d06d29892 ./lib/src/vmodal.dart
-5cc38f87cde8643b914a6f54f2e691d4c12a36533be9177ae6174905055230f7 ./lib/vmodal_sdk_flutter.dart
+14f02410389d19abb09ca40ff69c6267f3ad0b8b40ab115aa6e2c76bf43bfeef ./lib/vmodal_sdk_flutter.dart
72fff91181fd3e25fd9afd766930a67025205b61096fd35c55cbdd9a3178ecf0 ./pubspec.lock
-2b969fbd1d82d89a5dc7822032ce9fe0df4bda625da969bc8e93c57e43fcf2c2 ./pubspec.yaml
+d419b05ec4674460d54f1143107138b11027ac6a842ae13b95b1509f1bea6235 ./pubspec.yaml
a80b38547f5d9ca1874f60e71c648e3fc12ab5f7cb88d1bead6d5b863d3c0245 ./readme_assets/dev_homepage.jpg
c56419d129059b64551e06f074e88ef62676f25938dc2a1fe28a6ab3f2ba8547 ./readme_assets/logo_vmodal_owl.jpeg
3198051c448338c5331baef7e17ff32bfbaf1265b59543a8aca2baf57513feed ./run.sh
@@ -120,23 +121,24 @@ d2dfce0e68717f8626ecaadb4552f7471ced1dbdfe6a51182e0d62c24a1b718b ./security_che
ae6bda64ca6d1bd107e60a60dfb5732b284402f0de3fe6b9a83c4ea5a9a97c70 ./test.sh
be59599b9ba77d031e9b4bad7f8d5c59efd2687888c5b73be4fbea115902106b ./test/adaptive_upload_test.dart
002abcc5d95c0cf20375adefe4ee2472581a615e64f5726bf361dd5c679cdea7 ./test/auth_http_test.dart
-29dbaadfb34d6c39048edc7e2caccd16ecfbdfaddfc29519326d719de4741936 ./test/client_test.dart
-ba941377f1ee717091dd30522609d028f32cd60df575564c75ab0228c2543d35 ./test/config_routes_test.dart
+3cb772c473b1657f2aaeebd8281e4d9cfee1aaa10b70badb70a1df8d5d7bc389 ./test/client_test.dart
+56eb465d0c149368f68dce9d54e48ad8f61476b912525d5783fac7de7b7c2943 ./test/config_routes_test.dart
4b9358bc8c8eb76b84dffc1c85d699169d890b4878af967f490bcddfcd6bd869 ./test/docs_reference_test.dart
b45470d8e7674bcb87828a8dcf231ac29afb4418774972c66e60cea9788270db ./test/errors_leak_test.dart
-a998f548e5e7bf975222cabd530302e47e45bd7cdc21697fbd333ae7d98965c2 ./test/fakes.dart
+d132b6dceb89804a47418245845547a25fcf8f89f56b292ee70a404d63364865 ./test/fakes.dart
0a1394c90829b91541aa01e9786e3195aae04fc49a7b92775dbf404bf2802107 ./test/fakes_test.dart
14368b598ece0ce9b2e249148a10a92f2c80e38427c077013a1515826f4365bd ./test/fixtures/routes_contract.json
-fd2bad0ad87fbf2f15f7e9845b830db58408bb4c502c6ff105f39e4e7cce1905 ./test/multipart_upload_test.dart
-cfcc97997e08295d08e08f27b3ad860088075f3822947f6b6200553847f859ec ./test/new_api_surface_test.dart
-86b093ffdab0bc6b2d412cd8f41667058bbc1117cedae9082d2635e98ef6488e ./test/regression_manifest_test.dart
-ec2d3ab09457fdccf30fc338585b89cf466f5d8f7fc8ce5f6c0ae52357390277 ./test/resources_models_test.dart
+959b19196513005ffd19bded8e4a2867a0fa84c8e85eae84aeebcc7fc70f8f88 ./test/multipart_upload_test.dart
+348b9581f6262acaaf96012a3d57685b0b45c3663c1497f14135663de7a60954 ./test/new_api_surface_test.dart
+58222c7f00e8aa8070df89d59278ce0d18842f53a7544261aa4a63ae4b1dd608 ./test/regression_manifest_test.dart
+13fc92ce0d804731aaee7a3bf3b145cb213d67a2ff18ebc271a32f2aba404679 ./test/resources_models_test.dart
8619ce113bb8669612f9a2a16b1b334ac68435c5972e84828a789511467fcb77 ./test/shell_scripts_test.dart
deacf67ef61894d8fd7d3cdd7648bace527917fe2097c65140286d324ec8b1aa ./test/transcode_upload_test.dart
-79e3de3c03451cd9d62327430106edf861da6aeb97b546bbac2d93a0bcbbe3d3 ./test/transport_test.dart
-c13557f89597f0be73f48dc8463aa7513e9e814c0e6a0ab871e441834687abb1 ./test/upload_test.dart
+7f62ef6965a51fee7123689003432dd013936b4189504222333cedb55c82dcc2 ./test/transport_test.dart
+c4aa3c091992668ee531412a7fc783106769df7d75147eb06271492027b0c100 ./test/upload_test.dart
af4a5b0eaca0bc1b2ef86cb88900fb67185b619cd90e6b5598ff9276a147d0b5 ./test/workflow_layout_test.dart
406de1350b79662fcaf007cb0cacd7a6b71b83815dc7cd3c7b561fcfba5600a3 ./tool/check_route_sync.dart
d5f5f9246656a5c275c5ab5863dbf3945d8ef6b1c9042c9d1912cfafce93646f ./tool/flutter_checksums.txt
d09e2ee68e0e238b86e54a8248a0da92db81c953ce691628708bffd63fa3e737 ./tool/live_test.dart
-f9ef953b6a5e57aae1e113ba233e96843cbe7cfe9ebd56b99a17efd51cc009a5 ./tool/release_manifest.dart
+d0eb57dd08a93b8afe4dc8f078db8b7ba7bdfc926292c2cff183c6489104c776 ./tool/perf_benchmark.dart
+659036b205fa10868d9b1b5861f5ac18931d41740b8145d50914a6b555ff9071 ./tool/release_manifest.dart
diff --git a/doc/performance.md b/doc/performance.md
new file mode 100644
index 0000000..916dff1
--- /dev/null
+++ b/doc/performance.md
@@ -0,0 +1,63 @@
+# Mobile performance and memory
+
+The SDK streams signed upload bodies and file ranges. A bulk task uses one
+signed-PUT budget across every file and multipart part, so
+`VideoUploadOptions.maxConcurrency` is a task ceiling rather than a nested
+multiplier. Progress is monotonic and coalesced at a 1% byte advance or 250 ms,
+with the final non-empty 100% event always delivered.
+
+`SdkConfig.timeout` bounds request setup and each signed-upload phase.
+`SdkConfig.idleTimeout` bounds silence while an API response body is consumed;
+it defaults to `timeout`. A retryable GET uses a fresh attempt cancellation token,
+so an attempt timeout does not cancel the caller's token. POST and multipart
+operations are never automatically replayed after a body timeout.
+
+## Bounded image persistence
+
+`getImageFromUrl` still returns `Uint8List`. Set `maxBytes` to a positive value
+no larger than the SDK's 64 MiB binary ceiling when the caller needs a smaller
+limit. To avoid a second in-memory image buffer, stream into a caller-owned sink:
+
+```dart
+final sink = cacheFile.openWrite();
+await client.images.writeImageFromUrl(url, sink, maxBytes: 8 * 1024 * 1024);
+await sink.close();
+```
+
+The SDK awaits the stream but does not close that sink. Use
+`saveImageFromUrl(url, file, maxBytes: ...)` when the SDK should own the file
+sink. It writes a unique sibling temporary file and renames it only after a
+complete bounded response, leaving an existing destination unchanged on error.
+
+## Native control clients
+
+Cronet and Cupertino remain application dependencies, not SDK defaults. A
+native `package:http` client can be injected through the public transport:
+
+```dart
+final config = SdkConfig(token: runtimeApiKey);
+final transport = HttpVmodalTransport(config, client: appOwnedNativeClient);
+final client = VmodalClient(config: config, transport: transport);
+```
+
+Use a client instance dedicated to that `VmodalClient`; closing the SDK client
+closes its supplied transports. Native clients affect control requests only.
+Signed media PUTs continue through `SignedUploadTransport`, whose integrity,
+cancellation, timeout, redirect, and header rules must be preserved by any
+custom adapter.
+
+## Benchmark harness
+
+Run the throttled local harness from the package root:
+
+```bash
+dart run tool/perf_benchmark.dart --sizes=5,64,100 --delay-ms=1
+```
+
+It reports JSON lines for single and bulk multipart runs: wall time, MiB/s,
+peak/current RSS growth, UI progress events, signed PUT count/bytes, and maximum
+active signed PUTs. Desktop results catch regressions but do not substitute for
+profile/release measurements on at least one mid-range Android device and one
+iPhone. Compare the default `http.Client` with a caller-injected native client
+in the application that owns the platform dependency; do not change the SDK
+default without device evidence.
diff --git a/doc/sdk_contract.md b/doc/sdk_contract.md
index 03140f3..e9f3ee5 100644
--- a/doc/sdk_contract.md
+++ b/doc/sdk_contract.md
@@ -16,13 +16,15 @@ behavior. `test/fixtures/routes_contract.json` is the reviewed normalized mirror
| Indexes | `jobsList`, `createIndex`, `indexStatus`, `deleteIndex` | Active |
| Admin | `userStats`, `usage`, `cacheStats` | Active; split external/users API bases |
| R2 | `presignUploadFile`, `presignUploadFolderVideo` | Active users API routes |
-| Images | `getUrl`, `getUrlBulk`, `getImageFromUrl`, `getImageBulkFromUrls` | Active image routes |
+| Images | `getUrl`, `getUrlBulk`, `getImageFromUrl`, `writeImageFromUrl`, `saveImageFromUrl`, `getImageBulkFromUrls` | Active image routes; buffered, sink, and atomic-file download choices |
| Multipart | explicit `VideoUploadOptions(multipart: true)` | Experimental; never selected by size |
| GDrive/SQL/auto-index/folder scan | compatibility methods | Disabled before transport |
| Google Drive collection upload | no public method | Mounted upstream but deprecated by SDK contract |
-Every operation uses the centralized `Routes`, `VmodalHttp`, bounded response
-reader, retry classifier, and cancellation token. Gateway payload serializers
+Every operation uses the centralized `Routes`, `VmodalHttp`, bounded chunked
+response readers, retry classifier, and cancellation token. `SdkConfig.timeout`
+bounds request/upload phases; `idleTimeout` bounds silence between response-body
+events and defaults to `timeout`. Gateway payload serializers
remove caller identity; only unsafe direct mode may emit trusted identity fields.
Application-visible error bodies and details retain their structured shape, but
the SDK replaces Unix, Windows, UNC, and `file:` filesystem paths with `****`
diff --git a/lib/src/client.dart b/lib/src/client.dart
index e35d3c7..ee5d245 100644
--- a/lib/src/client.dart
+++ b/lib/src/client.dart
@@ -7,7 +7,7 @@ import 'transport.dart';
import 'upload.dart';
/// Version of the Dart SDK contract represented by this package.
-const String vmodalSdkVersion = '1.0.0';
+const String vmodalSdkVersion = '1.1.0';
/// Owns configuration, transports, and feature resources for one app session.
///
diff --git a/lib/src/collection_uploads.dart b/lib/src/collection_uploads.dart
index 2d6230c..8a49ee5 100644
--- a/lib/src/collection_uploads.dart
+++ b/lib/src/collection_uploads.dart
@@ -160,20 +160,24 @@ extension CollectionUploads on CollectionsResource {
}) {
final resolved = options.resolvedFor(source.contentLength);
resolved.validate(source.contentLength);
- return UploadTask<VideoUploadResponse>.start(
- (CancellationToken cancellation, void Function(UploadProgress) emit) =>
- _videoUploadRun(
- source,
- collectionName,
- subCollectionName,
- mode,
- modality,
- ttl,
- resolved,
- cancellation,
- emit,
- ),
- );
+ return UploadTask<VideoUploadResponse>.start((
+ CancellationToken cancellation,
+ void Function(UploadProgress) emit,
+ ) {
+ final permits = _UploadPermitPool(resolved.maxConcurrency);
+ return _videoUploadRun(
+ source,
+ collectionName,
+ subCollectionName,
+ mode,
+ modality,
+ ttl,
+ resolved,
+ cancellation,
+ emit,
+ permits,
+ );
+ });
}
/// Starts an ordered bulk upload with aggregate progress.
@@ -195,6 +199,25 @@ extension CollectionUploads on CollectionsResource {
for (var i = 0; i < sources.length; i++) {
resolved[i].validate(sources[i].contentLength);
}
+ final sessionKeys = <String>{};
+ for (var i = 0; i < sources.length; i++) {
+ if (!resolved[i].multipart) continue;
+ final key = _UploadContract(
+ source: sources[i],
+ baseUrl: http.config.normalizedBaseUrl,
+ userId: http.config.normalizedUserId,
+ collection: collectionName,
+ stream: subCollectionName,
+ mode: mode,
+ modality: modality,
+ partSize: resolved[i].partSizeBytes,
+ ).key;
+ if (!sessionKeys.add(key)) {
+ throw const ValidationException(
+ 'bulk multipart upload contains a duplicate source contract',
+ );
+ }
+ }
return UploadTask<VideoUploadBulkResponse>.start((
CancellationToken cancellation,
void Function(UploadProgress) emit,
@@ -210,10 +233,31 @@ extension CollectionUploads on CollectionsResource {
(int value, UploadSource source) => value + source.contentLength,
);
final sent = List<int>.filled(sources.length, 0);
+ final gates = List<UploadProgressGate>.generate(
+ sources.length,
+ (_) => UploadProgressGate(),
+ );
final results = List<VideoUploadResponse?>.filled(sources.length, null);
+ final budget = resolved.fold<int>(
+ options.maxConcurrency.clamp(1, 16),
+ (int value, VideoUploadOptions item) => min(value, item.maxConcurrency),
+ );
+ final permits = _UploadPermitPool(budget);
+ var sentTotal = 0;
var cursor = 0;
Object? firstError;
StackTrace? firstStack;
+ void report(int index, UploadProgress progress) {
+ final value = gates[index].next(progress);
+ if (value == null) return;
+ final next = max(sent[index], value.uploadedBytes);
+ final delta = next - sent[index];
+ if (delta <= 0) return;
+ sent[index] = next;
+ sentTotal += delta;
+ emit(UploadProgress(sentTotal, total));
+ }
+
Future<void> worker() async {
while (!cancellation.isCanceled && firstError == null) {
final index = cursor++;
@@ -228,17 +272,16 @@ extension CollectionUploads on CollectionsResource {
ttl,
resolved[index],
cancellation,
- (UploadProgress progress) {
- sent[index] = max(sent[index], progress.uploadedBytes);
- emit(
- UploadProgress(
- sent.fold<int>(0, (int a, int b) => a + b),
- total,
- ),
- );
- },
+ (UploadProgress progress) => report(index, progress),
+ permits,
+ );
+ report(
+ index,
+ UploadProgress(
+ sources[index].contentLength,
+ sources[index].contentLength,
+ ),
);
- sent[index] = sources[index].contentLength;
} on Object catch (error, stack) {
firstError ??= error;
firstStack ??= stack;
@@ -273,6 +316,7 @@ extension CollectionUploads on CollectionsResource {
VideoUploadOptions options,
CancellationToken cancellation,
void Function(UploadProgress) emit,
+ _UploadPermitPool permits,
) async {
if (!options.transcoder.isPassthrough) {
return _transcodeUploadRun(
@@ -285,6 +329,7 @@ extension CollectionUploads on CollectionsResource {
options,
cancellation,
emit,
+ permits,
);
}
if (!options.multipart) {
@@ -297,6 +342,7 @@ extension CollectionUploads on CollectionsResource {
ttl,
cancellation,
emit,
+ permits,
);
}
try {
@@ -310,6 +356,7 @@ extension CollectionUploads on CollectionsResource {
options,
cancellation,
emit,
+ permits,
);
} on ApiException catch (error) {
if (error.statusCode != 404) rethrow;
@@ -332,6 +379,7 @@ extension CollectionUploads on CollectionsResource {
VideoUploadOptions options,
CancellationToken cancellation,
void Function(UploadProgress) emit,
+ _UploadPermitPool permits,
) async {
final input = source.localFile;
if (input == null) {
@@ -363,6 +411,7 @@ extension CollectionUploads on CollectionsResource {
pass,
cancellation,
emit,
+ permits,
);
if (produced) {
if (await result.output.exists()) await result.output.delete();
@@ -392,6 +441,7 @@ extension CollectionUploads on CollectionsResource {
int ttl,
CancellationToken cancellation,
void Function(UploadProgress) emit,
+ _UploadPermitPool permits,
) async {
cancellation.throwIfCanceled();
final signed = await http.request(
@@ -402,12 +452,15 @@ extension CollectionUploads on CollectionsResource {
);
cancellation.throwIfCanceled();
final url = _signedUri('${signed['url'] ?? ''}');
- final result = await signedUploads.upload(
- source: source,
- url: url,
- method: '${signed['method'] ?? 'PUT'}',
- cancellation: cancellation,
- onProgress: emit,
+ final result = await permits.run(
+ cancellation,
+ () => signedUploads.upload(
+ source: source,
+ url: url,
+ method: '${signed['method'] ?? 'PUT'}',
+ cancellation: cancellation,
+ onProgress: emit,
+ ),
);
cancellation.throwIfCanceled();
final done = await _uploadDone(
@@ -445,6 +498,7 @@ extension CollectionUploads on CollectionsResource {
VideoUploadOptions options,
CancellationToken cancellation,
void Function(UploadProgress) emit,
+ _UploadPermitPool permits,
) async {
final contract = _UploadContract(
source: source,
@@ -538,12 +592,13 @@ extension CollectionUploads on CollectionsResource {
for (final entry in valid.entries)
entry.key: intValue(entry.value['size_bytes']),
};
+ var sentTotal = sentByPart.values.fold<int>(0, (int a, int b) => a + b);
var lastProgress = 0;
void report() {
- final total = sentByPart.values
- .fold<int>(0, (int a, int b) => a + b)
- .clamp(0, source.contentLength);
- lastProgress = max(lastProgress, total);
+ lastProgress = max(
+ lastProgress,
+ sentTotal.clamp(0, source.contentLength),
+ );
emit(UploadProgress(lastProgress, source.contentLength));
}
@@ -593,12 +648,15 @@ extension CollectionUploads on CollectionsResource {
options,
cancellation,
(UploadProgress progress) {
- sentByPart[number] = max(
- sentByPart[number] ?? 0,
- progress.uploadedBytes,
- );
- report();
+ final previous = sentByPart[number] ?? 0;
+ final next = max(previous, progress.uploadedBytes);
+ if (next > previous) {
+ sentByPart[number] = next;
+ sentTotal += next - previous;
+ report();
+ }
},
+ permits,
);
uploaded.add(part);
} on Object catch (error, stack) {
@@ -620,7 +678,9 @@ extension CollectionUploads on CollectionsResource {
for (final part in uploaded) {
attempts += part.attempts;
session.partMd5[part.number] = part.md5;
+ final previous = sentByPart[part.number] ?? 0;
sentByPart[part.number] = part.size;
+ sentTotal += max(0, part.size - previous);
}
await options.store.save(sessionKey, session.toJson(contract));
report();
@@ -713,6 +773,7 @@ extension CollectionUploads on CollectionsResource {
VideoUploadOptions options,
CancellationToken cancellation,
void Function(UploadProgress) emit,
+ _UploadPermitPool permits,
) async {
final offset = (number - 1) * session.partSize;
final length = _partLength(source.contentLength, session.partSize, number);
@@ -723,16 +784,19 @@ extension CollectionUploads on CollectionsResource {
final headers = objectMap(
item['headers'],
).map((String key, Object? value) => MapEntry(key, '$value'));
- final result = await signedUploads.upload(
- source: source,
- url: _signedUri('${item['url'] ?? ''}'),
- method: '${item['method'] ?? 'PUT'}',
- offset: offset,
- length: length,
- headers: headers,
- timeout: options.partTimeout,
- cancellation: cancellation,
- onProgress: emit,
+ final result = await permits.run(
+ cancellation,
+ () => signedUploads.upload(
+ source: source,
+ url: _signedUri('${item['url'] ?? ''}'),
+ method: '${item['method'] ?? 'PUT'}',
+ offset: offset,
+ length: length,
+ headers: headers,
+ timeout: options.partTimeout,
+ cancellation: cancellation,
+ onProgress: emit,
+ ),
);
final expected = result.localMd5.isEmpty
? await md5Hex(source, offset: offset, length: length)
@@ -1044,6 +1108,64 @@ class _UploadedPart {
final int attempts;
}
+class _UploadPermitPool {
+ _UploadPermitPool(int size) : _available = max(1, size);
+
+ int _available;
+ final List<_PermitWaiter> _waiters = <_PermitWaiter>[];
+
+ Future<T> run<T>(
+ CancellationToken cancellation,
+ Future<T> Function() operation,
+ ) async {
+ await _acquire(cancellation);
+ try {
+ cancellation.throwIfCanceled();
+ return await operation();
+ } finally {
+ _release();
+ }
+ }
+
+ Future<void> _acquire(CancellationToken cancellation) async {
+ cancellation.throwIfCanceled();
+ if (_available > 0) {
+ _available--;
+ return;
+ }
+ final waiter = _PermitWaiter();
+ _waiters.add(waiter);
+ await Future.any(<Future<void>>[
+ waiter.ready.future,
+ cancellation.whenCanceled,
+ ]);
+ if (cancellation.isCanceled) {
+ if (waiter.granted) {
+ _release();
+ } else {
+ _waiters.remove(waiter);
+ }
+ throw const OperationCanceled();
+ }
+ }
+
+ void _release() {
+ while (_waiters.isNotEmpty) {
+ final waiter = _waiters.removeAt(0);
+ if (waiter.ready.isCompleted) continue;
+ waiter.granted = true;
+ waiter.ready.complete();
+ return;
+ }
+ _available++;
+ }
+}
+
+class _PermitWaiter {
+ final Completer<void> ready = Completer<void>();
+ bool granted = false;
+}
+
Map<String, Object?> _uploadParams(
UploadSource source,
String collection,
diff --git a/lib/src/config.dart b/lib/src/config.dart
index 8dba791..e4ab988 100644
--- a/lib/src/config.dart
+++ b/lib/src/config.dart
@@ -35,16 +35,21 @@ class SdkConfig {
this.email = '',
this.token = '',
this.timeout = const Duration(seconds: 30),
+ Duration? idleTimeout,
this.mode = 'gateway',
this.maxRetries = 1,
this.apiKeyProvider,
- }) : baseUrl = baseUrl ?? publicGatewayUrl {
+ }) : baseUrl = baseUrl ?? publicGatewayUrl,
+ idleTimeout = idleTimeout ?? timeout {
if (timeout <= Duration.zero) {
throw const ValidationException('timeout must be positive');
}
if (maxRetries < 0) {
throw const ValidationException('max_retries must not be negative');
}
+ if (this.idleTimeout <= Duration.zero) {
+ throw const ValidationException('idle_timeout must be positive');
+ }
if (!const <String>{'gateway', 'direct'}.contains(normalizedMode)) {
throw const ValidationException('mode must be gateway or direct');
}
@@ -66,9 +71,14 @@ class SdkConfig {
/// Static API key used when [apiKeyProvider] is absent.
final String token;
- /// Maximum duration for an SDK request.
+ /// Maximum duration for establishing an SDK request or upload phase.
final Duration timeout;
+ /// Maximum silence allowed while consuming a response body.
+ ///
+ /// Defaults to [timeout] when omitted.
+ final Duration idleTimeout;
+
/// Connection mode, either `gateway` or `direct`.
final String mode;
@@ -103,6 +113,7 @@ class SdkConfig {
String? email,
String? token,
Duration? timeout,
+ Duration? idleTimeout,
String? mode,
int? maxRetries,
ApiKeyProvider? apiKeyProvider,
@@ -113,6 +124,7 @@ class SdkConfig {
email: email ?? this.email,
token: token ?? this.token,
timeout: timeout ?? this.timeout,
+ idleTimeout: idleTimeout ?? this.idleTimeout,
mode: mode ?? this.mode,
maxRetries: maxRetries ?? this.maxRetries,
apiKeyProvider: apiKeyProvider ?? this.apiKeyProvider,
@@ -130,6 +142,7 @@ class SdkConfig {
String? email,
String? token,
Duration? timeout,
+ Duration? idleTimeout,
String? mode,
int? maxRetries,
ApiKeyProvider? apiKeyProvider,
@@ -169,6 +182,7 @@ class SdkConfig {
(seconds == null
? const Duration(seconds: 30)
: Duration(milliseconds: (seconds * 1000).round())),
+ idleTimeout: idleTimeout,
mode: mode ?? 'gateway',
maxRetries:
maxRetries ?? int.tryParse(env['VMODAL_MAX_RETRIES'] ?? '') ?? 1,
@@ -185,6 +199,7 @@ class SdkConfig {
'emailConfigured=${email.isNotEmpty}, '
'tokenConfigured=${token.isNotEmpty}, '
'timeoutMs=${timeout.inMilliseconds}, '
+ 'idleTimeoutMs=${idleTimeout.inMilliseconds}, '
'mode=$normalizedMode, '
'maxRetries=$maxRetries, '
'apiKeyProviderConfigured=${apiKeyProvider != null})';
diff --git a/lib/src/http.dart b/lib/src/http.dart
index 8f2e45c..8432613 100644
--- a/lib/src/http.dart
+++ b/lib/src/http.dart
@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:convert';
+import 'dart:io';
import 'dart:typed_data';
import 'config.dart';
@@ -8,6 +9,8 @@ import 'transport.dart';
import 'utils.dart';
typedef DelayStrategy = Future<void> Function(Duration duration);
+typedef ResponseReader<T> =
+ Future<T> Function(VmodalResponse response, CancellationToken cancellation);
class VmodalHttp {
VmodalHttp(this.config, this.transport, {DelayStrategy? delay})
@@ -89,10 +92,12 @@ class VmodalHttp {
String path, {
Object? json,
Map<String, Object?> params = const <String, Object?>{},
+ int? maxBytes,
CancellationToken? cancellation,
}) async {
+ final limit = _binaryLimit(maxBytes);
final token = cancellation ?? CancellationToken();
- final response = await _execute(
+ return _executeRead<Uint8List>(
method,
path,
headers: headers(),
@@ -100,8 +105,44 @@ class VmodalHttp {
params: params,
responseMode: VmodalResponseMode.bytes,
cancellation: token,
+ reader: (VmodalResponse response, CancellationToken attempt) =>
+ readBounded(
+ response,
+ limit,
+ cancellation: attempt,
+ idleTimeout: config.idleTimeout,
+ ),
+ );
+ }
+
+ Future<void> requestBytesToSink(
+ String method,
+ String path, {
+ required IOSink sink,
+ Object? json,
+ Map<String, Object?> params = const <String, Object?>{},
+ int? maxBytes,
+ CancellationToken? cancellation,
+ }) async {
+ final limit = _binaryLimit(maxBytes);
+ final token = cancellation ?? CancellationToken();
+ await _executeRead<void>(
+ method,
+ path,
+ headers: headers(),
+ json: json,
+ params: params,
+ responseMode: VmodalResponseMode.bytes,
+ cancellation: token,
+ reader: (VmodalResponse response, CancellationToken attempt) =>
+ writeBounded(
+ response,
+ sink,
+ limit,
+ cancellation: attempt,
+ idleTimeout: config.idleTimeout,
+ ),
);
- return readBounded(response, binaryResponseLimitBytes, cancellation: token);
}
Future<Map<String, Object?>> _requestJson(
@@ -116,7 +157,7 @@ class VmodalHttp {
CancellationToken? cancellation,
}) async {
final token = cancellation ?? CancellationToken();
- final response = await _execute(
+ return _executeRead<Map<String, Object?>>(
method,
path,
headers: headers,
@@ -126,21 +167,17 @@ class VmodalHttp {
params: params,
usersApi: usersApi,
cancellation: token,
+ reader: (VmodalResponse response, CancellationToken attempt) =>
+ readJsonObjectBounded(
+ response,
+ jsonResponseLimitBytes,
+ cancellation: attempt,
+ idleTimeout: config.idleTimeout,
+ ),
);
- final bytes = await readBounded(
- response,
- jsonResponseLimitBytes,
- cancellation: token,
- );
- if (bytes.isEmpty) return <String, Object?>{};
- final value = jsonDecodeStrict(bytes);
- if (value is! Map) {
- throw const MalformedResponse('JSON object response required');
- }
- return objectMap(value);
}
- Future<VmodalResponse> _execute(
+ Future<T> _executeRead<T>(
String method,
String path, {
required Map<String, String> headers,
@@ -151,38 +188,52 @@ class VmodalHttp {
bool usersApi = false,
VmodalResponseMode responseMode = VmodalResponseMode.json,
required CancellationToken cancellation,
+ required ResponseReader<T> reader,
}) async {
final normalized = method.toUpperCase();
final canRetry = normalized == 'GET' || normalized == 'HEAD';
final uri = _uri(path, params, usersApi: usersApi);
- final request = VmodalRequest(
- method: normalized,
- uri: uri,
- headers: headers,
- jsonBody: json,
- formFields: data,
- files: files,
- responseMode: responseMode,
- cancellation: cancellation,
- );
for (var attempt = 0; attempt <= config.normalizedMaxRetries; attempt++) {
cancellation.throwIfCanceled();
+ final attemptCancellation = CancellationToken();
+ final removeCancel = cancellation.onCancel(attemptCancellation.cancel);
try {
+ final request = VmodalRequest(
+ method: normalized,
+ uri: uri,
+ headers: headers,
+ jsonBody: json,
+ formFields: data,
+ files: files,
+ responseMode: responseMode,
+ cancellation: attemptCancellation,
+ );
final response = await transport.send(request);
if (canRetry &&
const <int>{500, 502, 503, 504}.contains(response.statusCode) &&
attempt < config.normalizedMaxRetries) {
- await _discard(response, cancellation);
+ await _discard(response, attemptCancellation);
await _delay(Duration(milliseconds: 50 * (attempt + 1)));
continue;
}
if (response.statusCode < 200 || response.statusCode > 299) {
- await _raiseForStatus(response, cancellation);
+ await _raiseForStatus(response, attemptCancellation);
}
- return response;
+ final value = await reader(response, attemptCancellation);
+ cancellation.throwIfCanceled();
+ return value;
+ } on OperationCanceled {
+ if (cancellation.isCanceled) rethrow;
+ if (!canRetry || attempt >= config.normalizedMaxRetries) {
+ throw const TransportException();
+ }
+ await _delay(Duration(milliseconds: 50 * (attempt + 1)));
} on TransportException {
+ if (cancellation.isCanceled) throw const OperationCanceled();
if (!canRetry || attempt >= config.normalizedMaxRetries) rethrow;
await _delay(Duration(milliseconds: 50 * (attempt + 1)));
+ } finally {
+ removeCancel();
}
}
throw const TransportException();
@@ -196,6 +247,7 @@ class VmodalHttp {
response,
errorResponseLimitBytes,
cancellation: token,
+ idleTimeout: config.idleTimeout,
);
Object? body;
if (bytes.isNotEmpty) {
@@ -246,7 +298,12 @@ class VmodalHttp {
VmodalResponse response,
CancellationToken token,
) async {
- await readBounded(response, errorResponseLimitBytes, cancellation: token);
+ await readBounded(
+ response,
+ errorResponseLimitBytes,
+ cancellation: token,
+ idleTimeout: config.idleTimeout,
+ );
}
Uri _uri(String path, Map<String, Object?> params, {required bool usersApi}) {
@@ -315,4 +372,14 @@ class VmodalHttp {
);
}
}
+
+ int _binaryLimit(int? maxBytes) {
+ if (maxBytes == null) return binaryResponseLimitBytes;
+ if (maxBytes <= 0 || maxBytes > binaryResponseLimitBytes) {
+ throw const ValidationException(
+ 'max_bytes must be positive and no larger than the SDK binary limit',
+ );
+ }
+ return maxBytes;
+ }
}
diff --git a/lib/src/resources.dart b/lib/src/resources.dart
index 5e76df5..cb95b39 100644
--- a/lib/src/resources.dart
+++ b/lib/src/resources.dart
@@ -1,3 +1,5 @@
+import 'dart:io';
+import 'dart:math';
import 'dart:typed_data';
import 'errors.dart';
@@ -554,6 +556,7 @@ class ImagesResource {
Future<Uint8List> getImageFromUrl(
String urlPreSigned, {
String? userid,
+ int? maxBytes,
CancellationToken? cancellation,
}) => http.requestBytes(
'POST',
@@ -564,9 +567,67 @@ class ImagesResource {
(userid?.trim().isNotEmpty ?? false))
'userid': userid,
},
+ maxBytes: maxBytes,
cancellation: cancellation,
);
+ /// Streams an image into a caller-owned [sink] without closing it.
+ Future<void> writeImageFromUrl(
+ String urlPreSigned,
+ IOSink sink, {
+ String? userid,
+ int? maxBytes,
+ CancellationToken? cancellation,
+ }) => http.requestBytesToSink(
+ 'POST',
+ Routes.full(Routes.imageGetImage),
+ sink: sink,
+ json: <String, Object?>{
+ 'url_pre_signed': urlPreSigned,
+ if (http.config.normalizedMode == 'direct' &&
+ (userid?.trim().isNotEmpty ?? false))
+ 'userid': userid,
+ },
+ maxBytes: maxBytes,
+ cancellation: cancellation,
+ );
+
+ /// Atomically downloads an image into [destination].
+ Future<File> saveImageFromUrl(
+ String urlPreSigned,
+ File destination, {
+ String? userid,
+ int? maxBytes,
+ CancellationToken? cancellation,
+ }) async {
+ final temp = File(
+ '${destination.path}.${DateTime.now().microsecondsSinceEpoch}-'
+ '${Random.secure().nextInt(1 << 32)}.tmp',
+ );
+ final sink = temp.openWrite();
+ try {
+ await writeImageFromUrl(
+ urlPreSigned,
+ sink,
+ userid: userid,
+ maxBytes: maxBytes,
+ cancellation: cancellation,
+ );
+ await sink.flush();
+ await sink.close();
+ await temp.rename(destination.path);
+ return destination;
+ } on Object catch (error, stack) {
+ try {
+ await sink.close();
+ } on Object {
+ // The sink may already be closed after a source-stream error.
+ }
+ if (await temp.exists()) await temp.delete();
+ Error.throwWithStackTrace(error, stack);
+ }
+ }
+
/// Downloads several images represented by [urls].
Future<ImageGetBulkResponse> getImageBulkFromUrls(
List<String> urls, {
diff --git a/lib/src/transport.dart b/lib/src/transport.dart
index bcac5ed..a8e8bd7 100644
--- a/lib/src/transport.dart
+++ b/lib/src/transport.dart
@@ -22,6 +22,7 @@ enum VmodalResponseMode {
/// Cooperative cancellation signal shared with an in-flight operation.
class CancellationToken {
final Completer<void> _abort = Completer<void>();
+ final Set<void Function()> _callbacks = <void Function()>{};
/// Whether [cancel] has been called.
bool get isCanceled => _abort.isCompleted;
@@ -31,7 +32,23 @@ class CancellationToken {
/// Requests cancellation. Repeated calls have no effect.
void cancel() {
- if (!_abort.isCompleted) _abort.complete();
+ if (_abort.isCompleted) return;
+ _abort.complete();
+ final callbacks = List<void Function()>.from(_callbacks);
+ _callbacks.clear();
+ for (final callback in callbacks) {
+ callback();
+ }
+ }
+
+ /// @nodoc
+ void Function() onCancel(void Function() callback) {
+ if (isCanceled) {
+ callback();
+ return () {};
+ }
+ _callbacks.add(callback);
+ return () => _callbacks.remove(callback);
}
/// Throws [OperationCanceled] after cancellation has been requested.
@@ -316,6 +333,7 @@ Future<Uint8List> readBounded(
VmodalResponse response,
int limitBytes, {
CancellationToken? cancellation,
+ Duration? idleTimeout,
}) async {
if (limitBytes <= 0) {
throw const ValidationException('response limit is invalid');
@@ -329,7 +347,11 @@ Future<Uint8List> readBounded(
}
final builder = BytesBuilder(copy: false);
var total = 0;
- await for (final chunk in response.body) {
+ await for (final chunk in _bodyWithIdleTimeout(
+ response.body,
+ cancellation,
+ idleTimeout,
+ )) {
cancellation?.throwIfCanceled();
if (chunk.length > limitBytes - total) {
cancellation?.cancel();
@@ -340,3 +362,114 @@ Future<Uint8List> readBounded(
}
return builder.takeBytes();
}
+
+Future<Map<String, Object?>> readJsonObjectBounded(
+ VmodalResponse response,
+ int limitBytes, {
+ CancellationToken? cancellation,
+ Duration? idleTimeout,
+}) async {
+ if (limitBytes <= 0) {
+ throw const ValidationException('response limit is invalid');
+ }
+ if (response.contentLength < -1) {
+ throw const MalformedResponse('invalid Content-Length');
+ }
+ if (response.contentLength > limitBytes) {
+ cancellation?.cancel();
+ throw ResponseTooLarge(limitBytes, response.contentLength);
+ }
+ var byteCount = 0;
+ var valueCount = 0;
+ Object? decoded;
+ Stream<List<int>> counted() async* {
+ await for (final chunk in _bodyWithIdleTimeout(
+ response.body,
+ cancellation,
+ idleTimeout,
+ )) {
+ cancellation?.throwIfCanceled();
+ if (chunk.length > limitBytes - byteCount) {
+ cancellation?.cancel();
+ throw ResponseTooLarge(limitBytes, byteCount + chunk.length);
+ }
+ byteCount += chunk.length;
+ yield chunk;
+ }
+ }
+
+ try {
+ final text = utf8.decoder.bind(counted());
+ await for (final value in json.decoder.bind(text)) {
+ valueCount++;
+ decoded = value;
+ }
+ } on FormatException {
+ if (byteCount == 0) return <String, Object?>{};
+ throw const MalformedResponse();
+ }
+ if (byteCount == 0) return <String, Object?>{};
+ if (valueCount != 1 || decoded is! Map<Object?, Object?>) {
+ throw const MalformedResponse('JSON object response required');
+ }
+ final value = decoded;
+ if (value.keys.any((Object? key) => key is! String)) {
+ throw const MalformedResponse('JSON object keys must be strings');
+ }
+ return Map<String, Object?>.from(value);
+}
+
+Future<void> writeBounded(
+ VmodalResponse response,
+ IOSink sink,
+ int limitBytes, {
+ CancellationToken? cancellation,
+ Duration? idleTimeout,
+}) async {
+ if (limitBytes <= 0) {
+ throw const ValidationException('response limit is invalid');
+ }
+ if (response.contentLength < -1) {
+ throw const MalformedResponse('invalid Content-Length');
+ }
+ if (response.contentLength > limitBytes) {
+ cancellation?.cancel();
+ throw ResponseTooLarge(limitBytes, response.contentLength);
+ }
+ var total = 0;
+ Stream<List<int>> bounded() async* {
+ await for (final chunk in _bodyWithIdleTimeout(
+ response.body,
+ cancellation,
+ idleTimeout,
+ )) {
+ cancellation?.throwIfCanceled();
+ if (chunk.length > limitBytes - total) {
+ cancellation?.cancel();
+ throw ResponseTooLarge(limitBytes, total + chunk.length);
+ }
+ total += chunk.length;
+ yield chunk;
+ }
+ }
+
+ await sink.addStream(bounded());
+}
+
+Stream<List<int>> _bodyWithIdleTimeout(
+ Stream<List<int>> body,
+ CancellationToken? cancellation,
+ Duration? idleTimeout,
+) {
+ if (idleTimeout == null) return body;
+ return body.timeout(
+ idleTimeout,
+ onTimeout: (EventSink<List<int>> sink) {
+ sink.addError(
+ TransportException(TimeoutException('response body idle timeout')),
+ );
+ sink.close();
+ cancellation?.cancel();
+ },
+ );
+}
diff --git a/lib/src/upload.dart b/lib/src/upload.dart
index efa4e8f..b27f61f 100644
--- a/lib/src/upload.dart
+++ b/lib/src/upload.dart
@@ -44,7 +44,7 @@ class UploadSource {
}
final stat = file.statSync();
final name = file.uri.pathSegments.last;
- return UploadSource(
+ final source = UploadSource(
fileName: name,
contentLength: stat.size,
contentType: contentType ?? guessContentType(name),
@@ -52,8 +52,9 @@ class UploadSource {
versionTag: '${stat.size}:${stat.modified.millisecondsSinceEpoch}',
localFile: file,
opener: file.openRead,
- rangeOpener: (int offset) => file.openRead(offset),
);
+ source._fileBacked = true;
+ return source;
}
/// Name associated with the uploaded object.
@@ -77,6 +78,7 @@ class UploadSource {
final File? localFile;
final Stream<List<int>> Function() _opener;
final Stream<List<int>> Function(int offset)? _rangeOpener;
+ bool _fileBacked = false;
/// Opens a validated source range.
///
@@ -87,6 +89,29 @@ class UploadSource {
if (offset < 0 || wanted < 0 || offset + wanted > contentLength) {
throw const ValidationException('upload source range is invalid');
}
+ if (_fileBacked) {
+ final file = localFile!;
+ await _validateFileVersion(file);
+ var left = wanted;
+ await for (final chunk in file.openRead(offset, offset + wanted)) {
+ if (left == 0) break;
+ final count = left < chunk.length ? left : chunk.length;
+ if (count == chunk.length) {
+ yield chunk;
+ } else if (chunk is Uint8List) {
+ yield Uint8List.sublistView(chunk, 0, count);
+ } else {
+ final copy = Uint8List(count)..setRange(0, count, chunk);
+ yield copy;
+ }
+ left -= count;
+ }
+ await _validateFileVersion(file);
+ if (left != 0) {
+ throw const TransportException('upload source ended early');
+ }
+ return;
+ }
final direct = _rangeOpener;
var skip = direct == null ? offset : 0;
var left = wanted;
@@ -104,7 +129,8 @@ class UploadSource {
if (left == 0) break;
final count = left < chunk.length - start ? left : chunk.length - start;
if (count > 0) {
- yield Uint8List.fromList(chunk.sublist(start, start + count));
+ final copy = Uint8List(count)..setRange(0, count, chunk, start);
+ yield copy;
left -= count;
}
if (left == 0) break;
@@ -113,6 +139,14 @@ class UploadSource {
throw const TransportException('upload source ended early');
}
}
+
+ Future<void> _validateFileVersion(File file) async {
+ final stat = await file.stat();
+ final current = '${stat.size}:${stat.modified.millisecondsSinceEpoch}';
+ if (current != versionTag) {
+ throw const TransportException('upload source changed during upload');
+ }
+ }
}
/// Monotonic upload progress snapshot.
@@ -141,6 +175,48 @@ typedef UploadRunner<T> =
void Function(UploadProgress progress) emit,
);
+/// @nodoc
+class UploadProgressGate {
+ UploadProgressGate({int Function()? monotonicMilliseconds}) {
+ if (monotonicMilliseconds == null) {
+ _watch.start();
+ _clock = () => _watch.elapsedMilliseconds;
+ } else {
+ _clock = monotonicMilliseconds;
+ }
+ }
+
+ final Stopwatch _watch = Stopwatch();
+ late final int Function() _clock;
+ int _seenBytes = 0;
+ int _emittedBytes = 0;
+ int? _emittedAt;
+ bool _terminalEmitted = false;
+
+ UploadProgress? next(UploadProgress value) {
+ final safe = value.uploadedBytes.clamp(_seenBytes, value.totalBytes);
+ _seenBytes = safe;
+ final terminal = value.totalBytes > 0 && safe == value.totalBytes;
+ if (terminal && !_terminalEmitted) {
+ _terminalEmitted = true;
+ _emittedBytes = safe;
+ _emittedAt = _clock();
+ return UploadProgress(safe, value.totalBytes);
+ }
+ if (safe <= _emittedBytes) return null;
+ final now = _clock();
+ final first = _emittedAt == null;
+ final byteReady =
+ value.totalBytes > 0 &&
+ (safe - _emittedBytes) * 100 >= value.totalBytes;
+ final timeReady = !first && now - _emittedAt! >= 250;
+ if (!first && !byteReady && !timeReady) return null;
+ _emittedBytes = safe;
+ _emittedAt = now;
+ return UploadProgress(safe, value.totalBytes);
+ }
+}
+
/// Running upload with result, progress, state, and cooperative cancellation.
class UploadTask<T> {
/// Starts [runner] immediately.
@@ -155,7 +231,7 @@ class UploadTask<T> {
/// Token passed to the running upload operation.
final CancellationToken cancellation = CancellationToken();
UploadTaskState _state = UploadTaskState.running;
- int _lastBytes = 0;
+ final UploadProgressGate _progressGate = UploadProgressGate();
/// Completes with the typed upload response or the task error.
Future<T> get result => _result.future;
@@ -197,9 +273,8 @@ class UploadTask<T> {
void _emit(UploadProgress value) {
if (_state != UploadTaskState.running) return;
- final safe = value.uploadedBytes.clamp(_lastBytes, value.totalBytes);
- _lastBytes = safe;
- _progress.add(UploadProgress(safe, value.totalBytes));
+ final safe = _progressGate.next(value);
+ if (safe != null) _progress.add(safe);
}
}
@@ -284,8 +359,16 @@ class IoSignedUploadTransport implements SignedUploadTransport {
final wanted = length ?? source.contentLength - offset;
HttpClientRequest? request;
var sent = 0;
+ var digestClosed = false;
+ void Function() removeCancel = () {};
final digestSink = _DigestSink();
final digest = md5.startChunkedConversion(digestSink);
+ void closeDigest() {
+ if (digestClosed) return;
+ digestClosed = true;
+ digest.close();
+ }
+
try {
request = await _client
.openUrl(method.toUpperCase(), url)
@@ -294,29 +377,69 @@ class IoSignedUploadTransport implements SignedUploadTransport {
request.contentLength = wanted;
request.headers.contentType = ContentType.parse(source.contentType);
safeHeaders.forEach(request.headers.set);
- unawaited(
- cancellation.whenCanceled.then((_) {
- request?.abort(const OperationCanceled());
- }),
+ removeCancel = cancellation.onCancel(
+ () => request?.abort(const OperationCanceled()),
);
- await for (final chunk in source.open(offset: offset, length: wanted)) {
- cancellation.throwIfCanceled();
- request.add(chunk);
- digest.add(chunk);
- sent += chunk.length;
- onProgress?.call(UploadProgress(sent, wanted));
+ Stream<List<int>> body() async* {
+ await for (final chunk in source.open(offset: offset, length: wanted)) {
+ cancellation.throwIfCanceled();
+ if (chunk.length > wanted - sent) {
+ throw const TransportException(
+ 'upload source exceeded the requested range',
+ );
+ }
+ digest.add(chunk);
+ sent += chunk.length;
+ onProgress?.call(UploadProgress(sent, wanted));
+ yield chunk;
+ }
+ if (sent != wanted) {
+ throw const TransportException(
+ 'upload source length did not match Content-Length',
+ );
+ }
}
- digest.close();
- final response = await request.close().timeout(timeout ?? defaultTimeout);
+
+ final phaseTimeout = timeout ?? defaultTimeout;
+ await request
+ .addStream(body())
+ .timeout(
+ phaseTimeout,
+ onTimeout: () {
+ final error = TimeoutException('signed upload body timeout');
+ request?.abort(error);
+ throw error;
+ },
+ );
+ closeDigest();
+ final response = await request.close().timeout(
+ phaseTimeout,
+ onTimeout: () {
+ final error = TimeoutException('signed upload response timeout');
+ request?.abort(error);
+ throw error;
+ },
+ );
if (response.statusCode < 200 || response.statusCode > 299) {
- final bytes = await _readIoBounded(response, errorResponseLimitBytes);
+ final bytes = await _readIoBounded(
+ response,
+ errorResponseLimitBytes,
+ phaseTimeout,
+ );
throw ApiException(
'signed upload failed',
statusCode: response.statusCode,
body: strRedactServerPaths(utf8.decode(bytes, allowMalformed: true)),
);
}
- await response.drain<void>();
+ await response.drain<void>().timeout(
+ phaseTimeout,
+ onTimeout: () {
+ final error = TimeoutException('signed upload response body timeout');
+ request?.abort(error);
+ throw error;
+ },
+ );
return SignedUploadResult(
statusCode: response.statusCode,
etag: (response.headers.value('etag') ?? '').replaceAll('"', '').trim(),
@@ -328,16 +451,15 @@ class IoSignedUploadTransport implements SignedUploadTransport {
rethrow;
} on Object catch (error) {
request?.abort(error);
- try {
- digest.close();
- } on Object {
- // Digest may already be closed after all bytes were sent.
- }
+ closeDigest();
+ if (cancellation.isCanceled) throw const OperationCanceled();
throw SignedUploadFailure(
sentBytes: sent,
localMd5: digestSink.value?.toString() ?? '',
cause: error,
);
+ } finally {
+ removeCancel();
}
}
@@ -518,12 +640,16 @@ class _DigestSink implements Sink<Digest> {
void close() {}
}
-Future<Uint8List> _readIoBounded(HttpClientResponse response, int limit) async {
+Future<Uint8List> _readIoBounded(
+ HttpClientResponse response,
+ int limit,
+ Duration idleTimeout,
+) async {
final declared = response.contentLength;
if (declared > limit) throw ResponseTooLarge(limit, declared);
final out = BytesBuilder(copy: false);
var count = 0;
- await for (final chunk in response) {
+ await for (final chunk in response.timeout(idleTimeout)) {
if (chunk.length > limit - count) {
throw ResponseTooLarge(limit, count + chunk.length);
}
diff --git a/lib/vmodal_sdk_flutter.dart b/lib/vmodal_sdk_flutter.dart
index 6be3e68..77a8b3b 100644
--- a/lib/vmodal_sdk_flutter.dart
+++ b/lib/vmodal_sdk_flutter.dart
@@ -42,6 +42,7 @@ export 'src/transcode.dart';
export 'src/transport.dart'
show
CancellationToken,
+ HttpVmodalTransport,
VmodalFilePart,
VmodalRequest,
VmodalResponse,
diff --git a/pubspec.yaml b/pubspec.yaml
index 8882d39..3ad9582 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,6 +1,6 @@
name: vmodal_sdk_flutter
description: Typed VModal API client for Flutter applications on Android and iOS.
-version: 1.0.0
+version: 1.1.0
license: MIT
repository: https://github.com/v-modal/vmodal_sdk_flutter
issue_tracker: https://github.com/v-modal/vmodal_sdk_flutter/issues
diff --git a/test/client_test.dart b/test/client_test.dart
index 5f9089d..a01e9df 100644
--- a/test/client_test.dart
+++ b/test/client_test.dart
@@ -1,9 +1,20 @@
import 'package:flutter_test/flutter_test.dart';
+import 'package:http/http.dart' as package_http;
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
import 'fakes.dart';
void main() {
+ test(
+ 'public HTTP transport accepts a caller-selected package client',
+ () async {
+ final config = SdkConfig(baseUrl: 'https://gateway.test', token: 'key');
+ final wire = package_http.Client();
+ final transport = HttpVmodalTransport(config, client: wire);
+ await transport.close();
+ },
+ );
+
test('fromEnvironment transfers bootstrap transport ownership', () async {
final api = FakeTransport()
..addResponse(
diff --git a/test/config_routes_test.dart b/test/config_routes_test.dart
index 98481d8..8f14c39 100644
--- a/test/config_routes_test.dart
+++ b/test/config_routes_test.dart
@@ -61,6 +61,7 @@ void main() {
expect(config.toString(), isNot(contains(key)));
expect(config.toString(), isNot(contains(user)));
expect(strUsersBaseUrl(config.normalizedBaseUrl), 'https://gateway.test');
+ expect(config.idleTimeout, config.timeout);
});
test('invalid configuration fails before transport', () {
@@ -76,5 +77,9 @@ void main() {
() => SdkConfig(timeout: Duration.zero),
throwsA(isA<ValidationException>()),
);
+ expect(
+ () => SdkConfig(idleTimeout: Duration.zero),
+ throwsA(isA<ValidationException>()),
+ );
});
}
diff --git a/test/fakes.dart b/test/fakes.dart
index 731521b..9a1f03a 100644
--- a/test/fakes.dart
+++ b/test/fakes.dart
@@ -105,6 +105,8 @@ class FakeSignedUploadTransport implements SignedUploadTransport {
int maxActive = 0;
bool closed = false;
int closeCalls = 0;
+ Duration delay = Duration.zero;
+ bool sourceMd5 = false;
@override
Future<SignedUploadResult> upload({
@@ -134,13 +136,28 @@ class FakeSignedUploadTransport implements SignedUploadTransport {
? const SignedUploadResult(statusCode: 200, etag: 'etag')
: queued.removeAt(0);
try {
+ if (delay > Duration.zero) {
+ await Future.any(<Future<void>>[
+ Future<void>.delayed(delay),
+ cancellation.whenCanceled,
+ ]);
+ cancellation.throwIfCanceled();
+ }
var sent = 0;
await for (final chunk in source.open(offset: offset, length: wanted)) {
cancellation.throwIfCanceled();
sent += chunk.length;
onProgress?.call(UploadProgress(sent, wanted));
}
- if (value is SignedUploadResult) return value;
+ if (value is SignedUploadResult) {
+ if (!sourceMd5 || value.etag != 'etag') return value;
+ final digest = await md5Hex(source, offset: offset, length: wanted);
+ return SignedUploadResult(
+ statusCode: value.statusCode,
+ etag: digest,
+ localMd5: digest,
+ );
+ }
throw value;
} finally {
active--;
diff --git a/test/multipart_upload_test.dart b/test/multipart_upload_test.dart
index 7004a09..ff23bed 100644
--- a/test/multipart_upload_test.dart
+++ b/test/multipart_upload_test.dart
@@ -143,6 +143,133 @@ void main() {
expect(statusCalls, 2);
});
+ test(
+ 'adaptive bulk multipart shares its conservative signed budget',
+ () async {
+ const mib = 1024 * 1024;
+ final sources = List<UploadSource>.generate(
+ 2,
+ (int index) => UploadSource(
+ fileName: '$index.mp4',
+ contentLength: 6 * mib,
+ sourceId: 'source-$index',
+ versionTag: 'v1',
+ opener: () => _bytes(6 * mib, index + 1),
+ ),
+ );
+ final digests = <String, List<String>>{};
+ for (final source in sources) {
+ digests[source.fileName] = <String>[
+ await md5Hex(source, offset: 0, length: 5 * mib),
+ await md5Hex(source, offset: 5 * mib, length: mib),
+ ];
+ }
+ final statusCalls = <String, int>{};
+ final api = HandlerTransport((VmodalRequest request) async {
+ final path = request.uri.path;
+ if (path.endsWith(Routes.externalUploadMultipartCreate)) {
+ final body = request.jsonBody! as Map<String, Object?>;
+ final name = '${body['filename']}';
+ return jsonResponse(
+ '{"request_id":"r-$name","upload_id":"$name","key":"k-$name",'
+ '"part_count":2,"part_size_bytes":${5 * mib}}',
+ );
+ }
+ if (path.endsWith(Routes.externalUploadMultipartStatus)) {
+ final name = request.uri.queryParameters['upload_id']!;
+ final count = (statusCalls[name] ?? 0) + 1;
+ statusCalls[name] = count;
+ if (count == 1) {
+ return jsonResponse('{"status":"uploading","parts":[]}');
+ }
+ final md5s = digests[name]!;
+ return jsonResponse(
+ '{"status":"uploading","parts":['
+ '{"part_number":1,"etag":"${md5s[0]}","size_bytes":${5 * mib}},'
+ '{"part_number":2,"etag":"${md5s[1]}","size_bytes":$mib}]}',
+ );
+ }
+ if (path.endsWith(Routes.externalUploadMultipartSignParts)) {
+ final body = request.jsonBody! as Map<String, Object?>;
+ final name = '${body['upload_id']}';
+ final numbers = body['part_numbers']! as List<Object?>;
+ final parts = numbers
+ .map(
+ (Object? number) =>
+ '{"part_number":$number,'
+ '"url":"https://objects.test/$name/$number",'
+ '"method":"PUT"}',
+ )
+ .join(',');
+ return jsonResponse('{"parts":[$parts]}');
+ }
+ if (path.endsWith(Routes.externalUploadMultipartComplete)) {
+ return jsonResponse('{"etag":"complete-etag"}');
+ }
+ if (path.endsWith(Routes.externalUploadDone)) {
+ return jsonResponse('{"dest_path":"done"}');
+ }
+ throw StateError('unexpected route: $path');
+ });
+ final signed = FakeSignedUploadTransport()
+ ..delay = const Duration(milliseconds: 10)
+ ..sourceMd5 = true;
+ final client = VmodalClient(
+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),
+ transport: api,
+ signedUploadTransport: signed,
+ );
+ final result = await client.collections
+ .videoUploadBulk(
+ sources,
+ collectionName: 'g',
+ subCollectionName: 's',
+ options: VideoUploadOptions(
+ multipart: true,
+ maxConcurrency: 4,
+ adaptiveConditions: const UploadConditions(
+ deviceMemory: UploadDeviceMemory.low,
+ ),
+ sessionStore: MemoryUploadSessionStore(),
+ ),
+ )
+ .result;
+ expect(
+ result.data.map((VideoUploadResponse item) => item.fileName),
+ <String>['0.mp4', '1.mp4'],
+ );
+ expect(signed.maxActive, 1);
+ },
+ );
+
+ test('bulk multipart rejects duplicate checkpoint contracts', () {
+ const mib = 1024 * 1024;
+ final source = UploadSource(
+ fileName: 'a.mp4',
+ contentLength: 6 * mib,
+ sourceId: 'same-source',
+ versionTag: 'v1',
+ opener: () => _bytes(6 * mib, 1),
+ );
+ final client = VmodalClient(
+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),
+ transport: FakeTransport(),
+ signedUploadTransport: FakeSignedUploadTransport(),
+ );
+ expect(
+ () => client.collections.videoUploadBulk(
+ <UploadSource>[source, source],
+ collectionName: 'g',
+ subCollectionName: 's',
+ options: const VideoUploadOptions(
+ multipart: true,
+ partSizeBytes: 5 * mib,
+ ),
+ ),
+ throwsA(isA<ValidationException>()),
+ );
+ });
+
test('file checkpoint rejects oversized and malformed state', () async {
final dir = await Directory.systemTemp.createTemp('vmodal-checkpoint-');
addTearDown(() => dir.delete(recursive: true));
diff --git a/test/new_api_surface_test.dart b/test/new_api_surface_test.dart
index b7318e7..809c9b0 100644
--- a/test/new_api_surface_test.dart
+++ b/test/new_api_surface_test.dart
@@ -259,7 +259,8 @@ void main() {
expect(cfg.api.requests, hasLength(9));
for (final request in cfg.api.requests) {
- expect(request.cancellation, same(cancel));
+ expect(request.cancellation, isNot(same(cancel)));
+ expect(request.cancellation.isCanceled, isFalse);
}
final values = cfg.api.requests.map(requestValues).toList();
for (final index in <int>[0, 1, 2, 3, 4, 5, 7, 8]) {
@@ -364,7 +365,8 @@ void main() {
),
<String>['global', 'user_123'],
);
- expect(cfg.api.requests.single.cancellation, same(cancel));
+ expect(cfg.api.requests.single.cancellation, isNot(same(cancel)));
+ expect(cfg.api.requests.single.cancellation.isCanceled, isFalse);
expect(cfg.api.requests.single.uri.queryParameters['mode'], 'vid_file');
cfg.api.addJson(<String, Object?>{
diff --git a/test/regression_manifest_test.dart b/test/regression_manifest_test.dart
index 22584d9..51a77b0 100644
--- a/test/regression_manifest_test.dart
+++ b/test/regression_manifest_test.dart
@@ -153,6 +153,7 @@ void main() {
'run.sh',
'test.sh',
'tool/live_test.dart',
+ 'tool/perf_benchmark.dart',
'example/01_full_app/README.md',
'example/01_full_app/lib/main.dart',
'example/01_full_app/asset/video_10frames.mp4',
diff --git a/test/resources_models_test.dart b/test/resources_models_test.dart
index 9af0c58..6b79093 100644
--- a/test/resources_models_test.dart
+++ b/test/resources_models_test.dart
@@ -1,4 +1,5 @@
import 'dart:convert';
+import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
@@ -87,6 +88,139 @@ void main() {
expect(row, isNot(contains('user_id')));
});
+ test('image bytes honor a smaller per-call limit before buffering', () async {
+ final fake = FakeTransport()
+ ..addResponse(
+ VmodalResponse(
+ statusCode: 200,
+ contentLength: 4,
+ body: Stream<List<int>>.value(<int>[1, 2, 3, 4]),
+ ),
+ );
+ final client = VmodalClient(
+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),
+ transport: fake,
+ signedUploadTransport: FakeSignedUploadTransport(),
+ );
+ await expectLater(
+ client.images.getImageFromUrl('https://objects.test/a', maxBytes: 3),
+ throwsA(isA<ResponseTooLarge>()),
+ );
+ });
+
+ test('image sink streams bytes and remains caller owned', () async {
+ final dir = await Directory.systemTemp.createTemp('vmodal-image-');
+ addTearDown(() => dir.delete(recursive: true));
+ final fake = FakeTransport()
+ ..addResponse(
+ VmodalResponse(
+ statusCode: 200,
+ contentLength: -1,
+ body: Stream<List<int>>.fromIterable(<List<int>>[
+ <int>[1, 2],
+ <int>[3, 4],
+ ]),
+ ),
+ );
+ final client = VmodalClient(
+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),
+ transport: fake,
+ signedUploadTransport: FakeSignedUploadTransport(),
+ );
+ final file = File('${dir.path}/a.jpg');
+ final sink = file.openWrite();
+ await client.images.writeImageFromUrl(
+ 'https://objects.test/a',
+ sink,
+ maxBytes: 4,
+ );
+ sink.add(<int>[5]);
+ await sink.close();
+ expect(await file.readAsBytes(), <int>[1, 2, 3, 4, 5]);
+ });
+
+ test(
+ 'atomic image file download preserves destination on overflow',
+ () async {
+ final dir = await Directory.systemTemp.createTemp('vmodal-image-');
+ addTearDown(() => dir.delete(recursive: true));
+ final destination = File('${dir.path}/a.jpg');
+ await destination.writeAsBytes(<int>[9], flush: true);
+ final fake = FakeTransport()
+ ..addResponse(
+ VmodalResponse(
+ statusCode: 200,
+ contentLength: -1,
+ body: Stream<List<int>>.fromIterable(<List<int>>[
+ <int>[1, 2],
+ <int>[3, 4, 5],
+ ]),
+ ),
+ );
+ final client = VmodalClient(
+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),
+ transport: fake,
+ signedUploadTransport: FakeSignedUploadTransport(),
+ );
+ await expectLater(
+ client.images.saveImageFromUrl(
+ 'https://objects.test/a',
+ destination,
+ maxBytes: 4,
+ ),
+ throwsA(isA<ResponseTooLarge>()),
+ );
+ expect(await destination.readAsBytes(), <int>[9]);
+ expect(await dir.list().length, 1);
+ },
+ );
+
+ test('atomic image file download replaces destination on success', () async {
+ final dir = await Directory.systemTemp.createTemp('vmodal-image-');
+ addTearDown(() => dir.delete(recursive: true));
+ final destination = File('${dir.path}/a.jpg');
+ await destination.writeAsBytes(<int>[9], flush: true);
+ final fake = FakeTransport()
+ ..addResponse(
+ VmodalResponse(
+ statusCode: 200,
+ contentLength: 3,
+ body: Stream<List<int>>.value(<int>[1, 2, 3]),
+ ),
+ );
+ final client = VmodalClient(
+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),
+ transport: fake,
+ signedUploadTransport: FakeSignedUploadTransport(),
+ );
+ expect(
+ await client.images.saveImageFromUrl(
+ 'https://objects.test/a',
+ destination,
+ ),
+ destination,
+ );
+ expect(await destination.readAsBytes(), <int>[1, 2, 3]);
+ expect(await dir.list().length, 1);
+ });
+
+ test('image per-call cap cannot raise the SDK binary ceiling', () async {
+ final fake = FakeTransport();
+ final client = VmodalClient(
+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),
+ transport: fake,
+ signedUploadTransport: FakeSignedUploadTransport(),
+ );
+ await expectLater(
+ client.images.getImageFromUrl(
+ 'https://objects.test/a',
+ maxBytes: 65 * 1024 * 1024,
+ ),
+ throwsA(isA<ValidationException>()),
+ );
+ expect(fake.requests, isEmpty);
+ });
+
test('resource paths and users API base are exact', () async {
final fake = FakeTransport()
..addResponse(jsonResponse('{"user_id":"u"}'))
diff --git a/test/transport_test.dart b/test/transport_test.dart
index a31c9c9..d14fb42 100644
--- a/test/transport_test.dart
+++ b/test/transport_test.dart
@@ -1,9 +1,11 @@
import 'dart:async';
+import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:vmodal_sdk_flutter/src/http.dart';
-import 'package:vmodal_sdk_flutter/src/transport.dart' show readBounded;
+import 'package:vmodal_sdk_flutter/src/transport.dart'
+ show readBounded, readJsonObjectBounded;
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
import 'fakes.dart';
@@ -78,6 +80,76 @@ void main() {
);
});
+ test(
+ 'chunked JSON preserves UTF-8, empty, and strict trailing semantics',
+ () async {
+ final bytes = Uint8List.fromList(utf8.encode('{"name":"東京"}'));
+ final chunked = VmodalResponse(
+ statusCode: 200,
+ contentLength: bytes.length,
+ body: Stream<List<int>>.fromIterable(
+ bytes.map((int value) => <int>[value]),
+ ),
+ );
+ expect(await readJsonObjectBounded(chunked, 100), <String, Object?>{
+ 'name': '東京',
+ });
+ expect(
+ await readJsonObjectBounded(
+ const VmodalResponse(
+ statusCode: 200,
+ contentLength: 0,
+ body: Stream<List<int>>.empty(),
+ ),
+ 100,
+ ),
+ isEmpty,
+ );
+ await expectLater(
+ readJsonObjectBounded(
+ VmodalResponse(
+ statusCode: 200,
+ contentLength: -1,
+ body: Stream<List<int>>.value(utf8.encode('{} {}')),
+ ),
+ 100,
+ ),
+ throwsA(isA<MalformedResponse>()),
+ );
+ await expectLater(
+ readJsonObjectBounded(
+ VmodalResponse(
+ statusCode: 200,
+ contentLength: 2,
+ body: Stream<List<int>>.value(<int>[0xc3, 0x28]),
+ ),
+ 100,
+ ),
+ throwsA(isA<MalformedResponse>()),
+ );
+ },
+ );
+
+ test('chunked JSON enforces its raw byte limit before decode', () async {
+ final token = CancellationToken();
+ await expectLater(
+ readJsonObjectBounded(
+ VmodalResponse(
+ statusCode: 200,
+ contentLength: -1,
+ body: Stream<List<int>>.fromIterable(<List<int>>[
+ <int>[123, 34],
+ <int>[97, 34, 58, 49, 125],
+ ]),
+ ),
+ 4,
+ cancellation: token,
+ ),
+ throwsA(isA<ResponseTooLarge>()),
+ );
+ expect(token.isCanceled, isTrue);
+ });
+
test('canceling one response does not affect a concurrent request', () async {
final firstReady = Completer<void>();
final releaseSecond = Completer<void>();
@@ -115,4 +187,103 @@ void main() {
await expectLater(one, throwsA(isA<OperationCanceled>()));
expect((await two)['status'], 'ok');
});
+
+ test('GET body idle timeout retries with a fresh attempt token', () async {
+ var calls = 0;
+ final fake = HandlerTransport((VmodalRequest request) async {
+ calls++;
+ if (calls == 1) {
+ return VmodalResponse(
+ statusCode: 200,
+ contentLength: -1,
+ body: (() async* {
+ yield <int>[123];
+ await Future<void>.delayed(const Duration(milliseconds: 50));
+ yield <int>[125];
+ })(),
+ );
+ }
+ return jsonResponse('{"status":"ok"}');
+ });
+ final caller = CancellationToken();
+ final http = VmodalHttp(
+ SdkConfig(
+ baseUrl: 'https://gateway.test',
+ token: 'key',
+ idleTimeout: const Duration(milliseconds: 10),
+ ),
+ fake,
+ delay: (_) async {},
+ );
+ expect(
+ (await http.request(
+ 'GET',
+ '/api/external/v1/health',
+ cancellation: caller,
+ ))['status'],
+ 'ok',
+ );
+ expect(calls, 2);
+ expect(fake.requests[0].cancellation.isCanceled, isTrue);
+ expect(fake.requests[1].cancellation.isCanceled, isFalse);
+ expect(caller.isCanceled, isFalse);
+ });
+
+ test('POST body idle timeout aborts once without retrying', () async {
+ final fake = HandlerTransport((VmodalRequest request) async {
+ return VmodalResponse(
+ statusCode: 200,
+ contentLength: -1,
+ body: (() async* {
+ yield <int>[123];
+ await Future<void>.delayed(const Duration(milliseconds: 50));
+ yield <int>[125];
+ })(),
+ );
+ });
+ final caller = CancellationToken();
+ final http = VmodalHttp(
+ SdkConfig(
+ baseUrl: 'https://gateway.test',
+ token: 'key',
+ idleTimeout: const Duration(milliseconds: 10),
+ ),
+ fake,
+ );
+ await expectLater(
+ http.request('POST', '/api/external/v1/health', cancellation: caller),
+ throwsA(isA<TransportException>()),
+ );
+ expect(fake.requests, hasLength(1));
+ expect(fake.requests.single.cancellation.isCanceled, isTrue);
+ expect(caller.isCanceled, isFalse);
+ });
+
+ test('attempt timeout cancellation does not poison a GET retry', () async {
+ var calls = 0;
+ final fake = HandlerTransport((VmodalRequest request) async {
+ calls++;
+ if (calls == 1) {
+ request.cancellation.cancel();
+ throw TransportException(TimeoutException('headers'));
+ }
+ return jsonResponse('{"status":"ok"}');
+ });
+ final caller = CancellationToken();
+ final http = VmodalHttp(
+ SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),
+ fake,
+ delay: (_) async {},
+ );
+ expect(
+ (await http.request(
+ 'GET',
+ '/api/external/v1/health',
+ cancellation: caller,
+ ))['status'],
+ 'ok',
+ );
+ expect(calls, 2);
+ expect(caller.isCanceled, isFalse);
+ });
}
diff --git a/test/upload_test.dart b/test/upload_test.dart
index 9e9b740..2a9f7b0 100644
--- a/test/upload_test.dart
+++ b/test/upload_test.dart
@@ -1,5 +1,8 @@
import 'dart:async';
+import 'dart:io';
+import 'dart:typed_data';
+import 'package:crypto/crypto.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
@@ -42,6 +45,180 @@ void main() {
);
});
+ test(
+ 'file source opens exact full, offset, final, and empty ranges',
+ () async {
+ final dir = await Directory.systemTemp.createTemp('vmodal-source-');
+ addTearDown(() => dir.delete(recursive: true));
+ final file = File('${dir.path}/a.mp4');
+ await file.writeAsBytes(<int>[0, 1, 2, 3, 4, 5, 6], flush: true);
+ final source = UploadSource.fromFile(file);
+
+ Future<List<int>> read(int offset, int length) => source
+ .open(offset: offset, length: length)
+ .expand((List<int> value) => value)
+ .toList();
+
+ expect(await read(0, 7), <int>[0, 1, 2, 3, 4, 5, 6]);
+ expect(await read(2, 3), <int>[2, 3, 4]);
+ expect(await read(5, 2), <int>[5, 6]);
+ expect(await read(7, 0), isEmpty);
+ },
+ );
+
+ test('custom source keeps a defensive snapshot of mutable chunks', () async {
+ final bytes = Uint8List.fromList(<int>[1, 2, 3, 4]);
+ final source = UploadSource(
+ fileName: 'a.mp4',
+ contentLength: bytes.length,
+ opener: () => Stream<List<int>>.value(bytes),
+ );
+ final chunk = await source.open().single;
+ bytes.fillRange(0, bytes.length, 9);
+ expect(chunk, <int>[1, 2, 3, 4]);
+ });
+
+ test('file source rejects truncation after source creation', () async {
+ final dir = await Directory.systemTemp.createTemp('vmodal-source-');
+ addTearDown(() => dir.delete(recursive: true));
+ final file = File('${dir.path}/a.mp4');
+ await file.writeAsBytes(<int>[0, 1, 2, 3], flush: true);
+ final source = UploadSource.fromFile(file);
+ await file.writeAsBytes(<int>[0, 1], flush: true);
+ await expectLater(
+ source.open().drain<void>(),
+ throwsA(isA<TransportException>()),
+ );
+ });
+
+ test('progress gate emits first, byte, time, and terminal events', () {
+ var elapsed = 0;
+ final gate = UploadProgressGate(monotonicMilliseconds: () => elapsed);
+ final emitted = <int>[];
+
+ void add(int value) {
+ final progress = gate.next(UploadProgress(value, 1000));
+ if (progress != null) emitted.add(progress.uploadedBytes);
+ }
+
+ add(1);
+ add(5);
+ elapsed = 250;
+ add(6);
+ add(16);
+ add(15);
+ add(1000);
+ add(1000);
+ expect(emitted, <int>[1, 6, 16, 1000]);
+ });
+
+ test(
+ 'IO signed transport streams exact bytes with integrity progress',
+ () async {
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ addTearDown(() => server.close(force: true));
+ final received = Completer<List<int>>();
+ server.listen((HttpRequest request) async {
+ final bytes = await request.fold<List<int>>(
+ <int>[],
+ (List<int> out, List<int> chunk) => out..addAll(chunk),
+ );
+ received.complete(bytes);
+ request.response.headers.set('etag', md5.convert(bytes).toString());
+ await request.response.close();
+ });
+ final source = UploadSource(
+ fileName: 'a.mp4',
+ contentLength: 5,
+ opener: () => Stream<List<int>>.fromIterable(<List<int>>[
+ <int>[1, 2],
+ <int>[3, 4, 5],
+ ]),
+ );
+ final transport = IoSignedUploadTransport(const Duration(seconds: 2));
+ addTearDown(transport.close);
+ final progress = <int>[];
+ final result = await transport.upload(
+ source: source,
+ url: Uri.parse('http://127.0.0.1:${server.port}/upload'),
+ cancellation: CancellationToken(),
+ onProgress: (UploadProgress value) {
+ progress.add(value.uploadedBytes);
+ },
+ );
+ expect(await received.future, <int>[1, 2, 3, 4, 5]);
+ expect(result.localMd5, md5.convert(<int>[1, 2, 3, 4, 5]).toString());
+ expect(result.etag, result.localMd5);
+ expect(progress, <int>[2, 5]);
+ },
+ );
+
+ test(
+ 'IO signed transport aborts an awaited body stream on cancellation',
+ () async {
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ addTearDown(() => server.close(force: true));
+ server.listen((HttpRequest request) async {
+ await request.drain<void>();
+ await request.response.close();
+ });
+ final source = UploadSource(
+ fileName: 'a.mp4',
+ contentLength: 4,
+ opener: () async* {
+ yield <int>[1, 2];
+ await Future<void>.delayed(const Duration(milliseconds: 50));
+ yield <int>[3, 4];
+ },
+ );
+ final token = CancellationToken();
+ final transport = IoSignedUploadTransport(const Duration(seconds: 2));
+ addTearDown(transport.close);
+ await expectLater(
+ transport.upload(
+ source: source,
+ url: Uri.parse('http://127.0.0.1:${server.port}/upload'),
+ cancellation: token,
+ onProgress: (_) => token.cancel(),
+ ),
+ throwsA(isA<OperationCanceled>()),
+ );
+ },
+ );
+
+ test('IO signed timeout keeps full sent-byte and digest metadata', () async {
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ addTearDown(() => server.close(force: true));
+ server.listen((HttpRequest request) async {
+ await request.drain<void>();
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ await request.response.close();
+ });
+ final source = UploadSource(
+ fileName: 'a.mp4',
+ contentLength: 4,
+ opener: () => Stream<List<int>>.value(<int>[1, 2, 3, 4]),
+ );
+ final transport = IoSignedUploadTransport(const Duration(milliseconds: 20));
+ addTearDown(transport.close);
+ await expectLater(
+ transport.upload(
+ source: source,
+ url: Uri.parse('http://127.0.0.1:${server.port}/upload'),
+ cancellation: CancellationToken(),
+ ),
+ throwsA(
+ isA<SignedUploadFailure>()
+ .having((SignedUploadFailure error) => error.sentBytes, 'sent', 4)
+ .having(
+ (SignedUploadFailure error) => error.localMd5,
+ 'md5',
+ md5.convert(<int>[1, 2, 3, 4]).toString(),
+ ),
+ ),
+ );
+ });
+
test(
'signed single upload streams, isolates headers, then finalizes',
() async {
@@ -162,4 +339,44 @@ void main() {
]);
expect(signed.maxActive, 1);
});
+
+ test('single-upload bulk shares one signed network budget', () async {
+ final api = HandlerTransport((VmodalRequest request) async {
+ if (request.uri.path.endsWith(Routes.externalUploadGetSignedUrl)) {
+ final name = request.uri.queryParameters['filename'];
+ return jsonResponse(
+ '{"url":"https://objects.test/$name","method":"PUT","key":"$name"}',
+ );
+ }
+ if (request.uri.path.endsWith(Routes.externalUploadDone)) {
+ return jsonResponse('{"dest_path":"done"}');
+ }
+ throw StateError('unexpected route: ${request.uri.path}');
+ });
+ final signed = FakeSignedUploadTransport()
+ ..delay = const Duration(milliseconds: 10);
+ final client = VmodalClient(
+ config: SdkConfig(baseUrl: 'https://gateway.test', token: 'key'),
+ transport: api,
+ signedUploadTransport: signed,
+ );
+ final sources = List<UploadSource>.generate(
+ 5,
+ (int index) => UploadSource(
+ fileName: '$index.mp4',
+ contentLength: 1,
+ sourceId: 'source-$index',
+ opener: () => Stream<List<int>>.value(<int>[index]),
+ ),
+ );
+ await client.collections
+ .videoUploadBulk(
+ sources,
+ collectionName: 'g',
+ subCollectionName: 's',
+ options: const VideoUploadOptions(maxConcurrency: 2),
+ )
+ .result;
+ expect(signed.maxActive, 2);
+ });
}
diff --git a/tool/perf_benchmark.dart b/tool/perf_benchmark.dart
new file mode 100644
index 0000000..185bb5f
--- /dev/null
+++ b/tool/perf_benchmark.dart
@@ -0,0 +1,279 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:math';
+import 'dart:typed_data';
+
+import 'package:crypto/crypto.dart';
+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';
+
+Future<void> main(List<String> args) async {
+ final values = _args(args);
+ final sizes = (values['sizes'] ?? '5,64,100')
+ .split(',')
+ .map(int.parse)
+ .toList();
+ final delay = Duration(milliseconds: int.parse(values['delay-ms'] ?? '1'));
+ final dir = await Directory.systemTemp.createTemp('vmodal-perf-');
+ final objects = await _ObjectServer.start(delay);
+ final api = _BenchmarkApi(objects);
+ final signed = IoSignedUploadTransport(const Duration(minutes: 10));
+ final client = VmodalClient(
+ config: SdkConfig(
+ baseUrl: 'http://127.0.0.1:3099',
+ token: 'benchmark-key',
+ timeout: const Duration(minutes: 10),
+ ),
+ transport: api,
+ signedUploadTransport: signed,
+ );
+ try {
+ final sources = <UploadSource>[];
+ for (var i = 0; i < sizes.length; i++) {
+ final file = await _file(dir, 'perf-$i.bin', sizes[i] * 1024 * 1024);
+ final source = UploadSource.fromFile(file);
+ sources.add(source);
+ final task = client.collections.videoUpload(
+ source,
+ collectionName: 'perf',
+ subCollectionName: 'single',
+ );
+ await _measure('single-${sizes[i]}MiB', task, objects);
+ }
+ objects.parts.clear();
+ final bulk = client.collections.videoUploadBulk(
+ sources,
+ collectionName: 'perf',
+ subCollectionName: 'multipart',
+ options: VideoUploadOptions(
+ multipart: true,
+ partSizeBytes: 5 * 1024 * 1024,
+ maxConcurrency: 4,
+ sessionStore: MemoryUploadSessionStore(),
+ ),
+ );
+ await _measure('bulk-multipart-${sizes.join('-')}MiB', bulk, objects);
+ } finally {
+ await client.close();
+ await objects.close();
+ await dir.delete(recursive: true);
+ }
+}
+
+Future<void> _measure<T>(
+ String name,
+ UploadTask<T> task,
+ _ObjectServer objects,
+) async {
+ final startRss = ProcessInfo.currentRss;
+ var peakRss = startRss;
+ var events = 0;
+ final beforeBytes = objects.bytes;
+ final beforeRequests = objects.requests;
+ final watch = Stopwatch()..start();
+ final sampler = Timer.periodic(const Duration(milliseconds: 10), (_) {
+ peakRss = max(peakRss, ProcessInfo.currentRss);
+ });
+ final sub = task.progress.listen((_) => events++);
+ await task.result;
+ await sub.cancel();
+ sampler.cancel();
+ watch.stop();
+ final bytes = objects.bytes - beforeBytes;
+ final seconds = watch.elapsedMicroseconds / Duration.microsecondsPerSecond;
+ stdout.writeln(
+ jsonEncode(<String, Object?>{
+ 'name': name,
+ 'wall_ms': watch.elapsedMilliseconds,
+ 'mib_per_second': seconds == 0 ? 0 : bytes / 1024 / 1024 / seconds,
+ 'peak_rss_bytes': peakRss,
+ 'rss_growth_bytes': max(0, peakRss - startRss),
+ 'ui_progress_events': events,
+ 'signed_puts': objects.requests - beforeRequests,
+ 'signed_bytes': bytes,
+ 'max_active_signed_puts': objects.maxActive,
+ }),
+ );
+ objects.maxActive = 0;
+}
+
+Future<File> _file(Directory dir, String name, int length) async {
+ final file = File('${dir.path}/$name');
+ final out = await file.open(mode: FileMode.write);
+ final chunk = Uint8List(1024 * 1024);
+ for (var i = 0; i < chunk.length; i++) {
+ chunk[i] = i % 251;
+ }
+ var left = length;
+ while (left > 0) {
+ final count = min(left, chunk.length);
+ await out.writeFrom(chunk, 0, count);
+ left -= count;
+ }
+ await out.close();
+ return file;
+}
+
+Map<String, String> _args(List<String> args) {
+ final out = <String, String>{};
+ for (final arg in args) {
+ if (!arg.startsWith('--') || !arg.contains('=')) continue;
+ final index = arg.indexOf('=');
+ out[arg.substring(2, index)] = arg.substring(index + 1);
+ }
+ return out;
+}
+
+class _ObjectServer {
+ _ObjectServer(this.server, this.delay);
+
+ final HttpServer server;
+ final Duration delay;
+ final Map<String, Map<int, _Part>> parts = <String, Map<int, _Part>>{};
+ int bytes = 0;
+ int requests = 0;
+ int active = 0;
+ int maxActive = 0;
+
+ static Future<_ObjectServer> start(Duration delay) async {
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ final value = _ObjectServer(server, delay);
+ server.listen(value._handle);
+ return value;
+ }
+
+ Uri url(String name, int number) => Uri.parse(
+ 'http://127.0.0.1:${server.port}/${Uri.encodeComponent(name)}/$number',
+ );
+
+ Future<void> _handle(HttpRequest request) async {
+ requests++;
+ active++;
+ maxActive = max(maxActive, active);
+ final name = Uri.decodeComponent(request.uri.pathSegments[0]);
+ final number = int.parse(request.uri.pathSegments[1]);
+ final sink = _DigestSink();
+ final input = md5.startChunkedConversion(sink);
+ var size = 0;
+ try {
+ await for (final chunk in request) {
+ input.add(chunk);
+ size += chunk.length;
+ bytes += chunk.length;
+ if (delay > Duration.zero) await Future<void>.delayed(delay);
+ }
+ input.close();
+ final digest = sink.value.toString();
+ parts.putIfAbsent(name, () => <int, _Part>{})[number] = _Part(
+ size,
+ digest,
+ );
+ request.response.headers.set('etag', digest);
+ await request.response.close();
+ } finally {
+ active--;
+ }
+ }
+
+ Future<void> close() => server.close(force: true);
+}
+
+class _BenchmarkApi implements VmodalTransport {
+ _BenchmarkApi(this.objects);
+
+ final _ObjectServer objects;
+ final Map<String, String> sessions = <String, String>{};
+
+ @override
+ Future<VmodalResponse> send(VmodalRequest request) async {
+ final path = request.uri.path;
+ if (path.endsWith(Routes.externalUploadGetSignedUrl)) {
+ final name = request.uri.queryParameters['filename']!;
+ return _json(<String, Object?>{
+ 'url': '${objects.url(name, 1)}',
+ 'method': 'PUT',
+ 'key': name,
+ });
+ }
+ if (path.endsWith(Routes.externalUploadMultipartCreate)) {
+ final body = request.jsonBody! as Map<String, Object?>;
+ final name = '${body['filename']}';
+ final size = body['size_bytes']! as int;
+ final partSize = body['part_size_bytes']! as int;
+ sessions[name] = name;
+ return _json(<String, Object?>{
+ 'request_id': 'r-$name',
+ 'upload_id': name,
+ 'key': name,
+ 'part_count': 1 + (size - 1) ~/ partSize,
+ 'part_size_bytes': partSize,
+ });
+ }
+ if (path.endsWith(Routes.externalUploadMultipartStatus)) {
+ final name = request.uri.queryParameters['upload_id']!;
+ final rows = (objects.parts[name] ?? <int, _Part>{}).entries
+ .map(
+ (MapEntry<int, _Part> item) => <String, Object?>{
+ 'part_number': item.key,
+ 'size_bytes': item.value.size,
+ 'etag': item.value.md5,
+ },
+ )
+ .toList();
+ return _json(<String, Object?>{'status': 'uploading', 'parts': rows});
+ }
+ if (path.endsWith(Routes.externalUploadMultipartSignParts)) {
+ final body = request.jsonBody! as Map<String, Object?>;
+ final name = '${body['upload_id']}';
+ final numbers = (body['part_numbers']! as List).cast<int>();
+ return _json(<String, Object?>{
+ 'parts': numbers
+ .map(
+ (int number) => <String, Object?>{
+ 'part_number': number,
+ 'url': '${objects.url(name, number)}',
+ 'method': 'PUT',
+ },
+ )
+ .toList(),
+ });
+ }
+ if (path.endsWith(Routes.externalUploadMultipartComplete)) {
+ return _json(<String, Object?>{'etag': 'complete'});
+ }
+ if (path.endsWith(Routes.externalUploadDone)) {
+ return _json(<String, Object?>{'dest_path': 'benchmark'});
+ }
+ throw StateError('unexpected benchmark route: $path');
+ }
+
+ VmodalResponse _json(Map<String, Object?> value) {
+ final bytes = utf8.encode(jsonEncode(value));
+ return VmodalResponse(
+ statusCode: 200,
+ contentLength: bytes.length,
+ headers: const <String, String>{'content-type': 'application/json'},
+ body: Stream<List<int>>.value(bytes),
+ );
+ }
+
+ @override
+ Future<void> close() async {}
+}
+
+class _Part {
+ const _Part(this.size, this.md5);
+
+ final int size;
+ final String md5;
+}
+
+class _DigestSink implements Sink<Digest> {
+ Digest? value;
+
+ @override
+ void add(Digest data) => value = data;
+
+ @override
+ void close() {}
+}
diff --git a/tool/release_manifest.dart b/tool/release_manifest.dart
index 450c47f..64a041e 100644
--- a/tool/release_manifest.dart
+++ b/tool/release_manifest.dart
@@ -102,6 +102,7 @@ Future<void> _export(Directory root, Directory destination) async {
'tool/flutter_checksums.txt',
'tool/check_route_sync.dart',
'tool/live_test.dart',
+ 'tool/perf_benchmark.dart',
'tool/release_manifest.dart',
];
for (final name in roots) {