diff --git a/logseq_db_types/lib/asset_descriptor.ml b/logseq_db_types/lib/asset_descriptor.ml index 0b38d7f7..4ce460a4 100644 --- a/logseq_db_types/lib/asset_descriptor.ml +++ b/logseq_db_types/lib/asset_descriptor.ml @@ -1,6 +1,7 @@ type version = { checksum : string ; file_type : string + ; download_size_hint : int64 option [@default None] } [@@deriving yojson] @@ -26,7 +27,7 @@ let version ~checksum ~file_type = | _ -> false) file_type) then Error "Invalid asset file type" - else Ok { checksum; file_type } + else Ok { checksum; file_type; download_size_hint = None } ;; let version_of_yojson json = @@ -66,7 +67,11 @@ let create ~uuid ~source ~current_checksum ~size ~dimensions = else Ok { uuid; source; current_checksum; size; dimensions } ;; -let equal_version a b = a = b +let with_download_size_hint version download_size_hint = + { version with download_size_hint } +;; + +let equal_version a b = a.checksum = b.checksum && a.file_type = b.file_type let of_yojson json = Result.bind (Json_codec.decode of_yojson json) (fun value -> diff --git a/logseq_db_types/lib/asset_descriptor.mli b/logseq_db_types/lib/asset_descriptor.mli index 48f89da9..babefbf9 100644 --- a/logseq_db_types/lib/asset_descriptor.mli +++ b/logseq_db_types/lib/asset_descriptor.mli @@ -1,7 +1,10 @@ -(** Graph metadata only; cache residency is not part of this value. *) +(** {1 TLDR} + Describes graph asset metadata. A version identifies bytes by checksum and + file type; a scheduled download can also carry a size estimate. *) type version = private { checksum : string ; file_type : string + ; download_size_hint : int64 option } type source = @@ -16,6 +19,13 @@ type t = private ; dimensions : (int * int) option } +(** {1 Minimal usage example} + Construct a managed version with [version ~checksum ~file_type], then pass + [Managed (Some version)] and the optional graph size to [create]. The fetch + scheduler attaches that size only to the version sent with the download. *) + +(** {1 Construction and validation} *) + val version : checksum:string -> file_type:string -> (version, string) result val create @@ -26,6 +36,10 @@ val create -> dimensions:(int * int) option -> (t, string) result +(** Attach request metadata to a scheduled fetch, not to the graph version. + The hint does not participate in version identity. *) +val with_download_size_hint : version -> int64 option -> version + val equal_version : version -> version -> bool val to_yojson : t -> Yojson.Safe.t diff --git a/logseq_db_types/lib/asset_upload_intent.ml b/logseq_db_types/lib/asset_upload_intent.ml index 8d58a69f..eb8ed9f4 100644 --- a/logseq_db_types/lib/asset_upload_intent.ml +++ b/logseq_db_types/lib/asset_upload_intent.ml @@ -49,7 +49,7 @@ let prepare || (not (String.is_valid_utf_8 title)) || String.contains title '\000' || size < 0L - || size > 104857600L + || size > 209715200L || staged_file = "" || staged_file <> Filename.basename staged_file || staged_file = "." diff --git a/logseq_db_worker/lib/effect_runner/effect_runner.ml b/logseq_db_worker/lib/effect_runner/effect_runner.ml index 84674f90..cb4e313c 100644 --- a/logseq_db_worker/lib/effect_runner/effect_runner.ml +++ b/logseq_db_worker/lib/effect_runner/effect_runner.ml @@ -3170,7 +3170,7 @@ let run_upload t (context : Sync.asset_context) instruction = { asset = intent.asset ; version = intent.version ; file = intent.staged_file - ; maximum_plaintext_bytes = 8 * 1024 * 1024 + ; maximum_plaintext_bytes = 200 * 1024 * 1024 }) with | Ok Sync.Asset_unit -> Ok () @@ -3608,7 +3608,7 @@ let run_asset t (context : Sync.asset_context) instruction = (Sync.Fetch_asset { asset = ticket.asset ; version = ticket.version - ; maximum_plaintext_bytes = 8 * 1024 * 1024 + ; maximum_plaintext_bytes = 200 * 1024 * 1024 })) (fun result -> Transfer.Downloaded diff --git a/logseq_db_worker/test/test_asset_upload.ml b/logseq_db_worker/test/test_asset_upload.ml index e7d5e011..85b2d5d5 100644 --- a/logseq_db_worker/test/test_asset_upload.ml +++ b/logseq_db_worker/test/test_asset_upload.ml @@ -27,9 +27,8 @@ let scope : C.graph_scope = } ;; -let intent = - get - (I.prepare +let prepare size = + I.prepare ~replace_reference:None ~operation_id:(uuid 2) ~origin:"https://sync.example" @@ -38,11 +37,40 @@ let intent = ~asset:(uuid 3) ~version:(get (A.version ~checksum:(String.make 64 'a') ~file_type:"png")) ~title:"Fixture image" - ~size:4L + ~size ~staged_file:"staged-file" ~target:(uuid 4) ~local_mutation:(uuid 5) - ~metadata_mutation:(uuid 6)) + ~metadata_mutation:(uuid 6) +;; + +let intent = get (prepare 4L) + +let durable_size_boundary () = + let maximum = 209715200L in + let prepared = + match prepare maximum with + | Ok prepared -> prepared + | Error message -> Alcotest.fail message + in + let uploading = get (I.advance (get (I.advance prepared Local_committed)) Uploading) in + let encoded = I.Pure_codec.encode uploading in + Alcotest.(check bool) "exact ceiling survives recovery" true + (I.Pure_codec.decode encoded = Ok uploading); + Alcotest.(check bool) "prepare rejects ceiling plus one" true + (Result.is_error (prepare (Int64.succ maximum))); + let oversized = + let rec replace index = + if index + 9 > String.length encoded then Alcotest.fail "missing size" + else if String.sub encoded index 9 = "209715200" then + String.sub encoded 0 index ^ "209715201" ^ + String.sub encoded (index + 9) (String.length encoded - index - 9) + else replace (index + 1) + in + replace 0 + in + Alcotest.(check bool) "recovery rejects ceiling plus one" true + (Result.is_error (I.Pure_codec.decode oversized)) ;; let one = function @@ -331,7 +359,9 @@ let pause_during_checkpoint () = let () = Alcotest.run "asset upload" - [ ( "public worker reducer" + [ ( "durable intent" + , [ Alcotest.test_case "200 MiB checkpoint boundary" `Quick durable_size_boundary ] ) + ; ( "public worker reducer" , List.map (fun (n, f) -> Alcotest.test_case n `Quick f) [ "presentation status", presentation_status diff --git a/logseq_db_worker/test/test_pure_reducer.ml b/logseq_db_worker/test/test_pure_reducer.ml index bc8de50a..79dd9885 100644 --- a/logseq_db_worker/test/test_pure_reducer.ml +++ b/logseq_db_worker/test/test_pure_reducer.ml @@ -373,7 +373,7 @@ let test_current_deletion_preserves_work_until_retirement () = module Asset = Logseq_db_types.Asset_descriptor module Transfer = Logseq_sync_pure_reducer.Asset_transfer -let asset_demand (scope : Sync.graph_scope) = +let asset_demand ?size (scope : Sync.graph_scope) = let version = Asset.version ~checksum:(String.make 64 'a') ~file_type:"png" |> Result.get_ok in @@ -382,7 +382,7 @@ let asset_demand (scope : Sync.graph_scope) = ~uuid:scope.Sync.graph_id ~source:(Managed (Some version)) ~current_checksum:None - ~size:None + ~size ~dimensions:None |> Result.get_ok in @@ -475,7 +475,8 @@ let asset_instructions effects = let test_asset_manual_retry_policy () = let state, scope = worker_open_graph () in - let demanded = Core.step state (asset_demand scope) in + let size = 25165824L in + let demanded = Core.step state (asset_demand ~size scope) in let local = lookup demanded.effects in let missing = Core.step @@ -490,6 +491,8 @@ let test_asset_manual_retry_policy () = (asset_instructions missing.effects) |> Option.get in + Alcotest.(check (option int64)) "worker schedules with the descriptor size" + (Some size) download.version.download_size_hint; let failed = Core.step missing.next diff --git a/logseq_overlay_db/lib/overlay_planner.ml b/logseq_overlay_db/lib/overlay_planner.ml index 45c28af7..f74b82ae 100644 --- a/logseq_overlay_db/lib/overlay_planner.ml +++ b/logseq_overlay_db/lib/overlay_planner.ml @@ -135,7 +135,7 @@ let validate = function else validate_append_tree ~page root | Types.Insert_blocks { tree; asset; _ } -> (match asset with - | Some asset when tree.children <> [] || asset.size < 0L || asset.size > 104857600L + | Some asset when tree.children <> [] || asset.size < 0L || asset.size > 209715200L -> Error "Asset insertion requires one block and a bounded size" | None | Some _ -> Outliner.Validation.validate_tree tree) | Set_asset_reference _ diff --git a/logseq_overlay_db/lib/persistence_outbox_v16.ml b/logseq_overlay_db/lib/persistence_outbox_v16.ml index 7ff82326..ac44990a 100644 --- a/logseq_overlay_db/lib/persistence_outbox_v16.ml +++ b/logseq_overlay_db/lib/persistence_outbox_v16.ml @@ -268,7 +268,7 @@ let mutation_of_wire = function | None -> Ok None | Some text -> Result.map Option.some (Graph.Uuid.of_string text) in - if asset.size >= 0L && asset.size <= 104857600L + if asset.size >= 0L && asset.size <= 209715200L then Ok (Some Types.{ replace_reference; version; size = asset.size }) else Error "Invalid persisted asset size" in diff --git a/logseq_sync/lib/effect_runner/effect_runner.ml b/logseq_sync/lib/effect_runner/effect_runner.ml index 44335839..5415390a 100644 --- a/logseq_sync/lib/effect_runner/effect_runner.ml +++ b/logseq_sync/lib/effect_runner/effect_runner.ml @@ -180,7 +180,7 @@ let existing_directory path = let local_store ?(asset_cache_budget_bytes = 268435456L) - ?(asset_maximum_file_bytes = 8 * 1024 * 1024) + ?(asset_maximum_file_bytes = 200 * 1024 * 1024) ?(asset_pending_budget_bytes = 268435456L) ~application_support_directory () @@ -189,7 +189,7 @@ let local_store asset_cache_budget_bytes <= 0L || asset_cache_budget_bytes > 268435456L || asset_maximum_file_bytes <= 0 - || asset_maximum_file_bytes > 8 * 1024 * 1024 + || asset_maximum_file_bytes > 200 * 1024 * 1024 || asset_pending_budget_bytes <= 0L || asset_pending_budget_bytes > 268435456L then Error (Invalid_dependency "Asset storage limits exceed the supported bounds") @@ -335,8 +335,8 @@ type key_entry = (* Transfer lanes bound request counts; this shared semaphore bounds the in-flight byte footprint of those lanes. Each admitted download or upload reserves its worst-case wire plus plaintext footprint before buffers are - held, in 64 KiB units, so total asset memory stays bounded independently - of the lane permits. *) + held, in 64 KiB units. A larger transfer takes the entire budget so it + cannot overlap another transfer. *) let asset_byte_unit = 65536 let asset_byte_budget_units = 1024 @@ -375,6 +375,7 @@ type t = ; mutable retired_websockets : Core.connection_scope list ; asset_download_slots : Eio.Semaphore.t ; asset_upload_slots : Eio.Semaphore.t + ; asset_large_slot : Eio.Semaphore.t ; asset_codec_slot : Eio.Semaphore.t ; asset_byte_budget : Eio.Semaphore.t ; asset_byte_reservation_lock : Eio.Semaphore.t @@ -404,6 +405,7 @@ let create ?(on_asset_diagnostic=(fun ~scope:_ ~operation:_ ~request_operation:_ ; retired_websockets = [] ; asset_download_slots = Eio.Semaphore.make 3 ; asset_upload_slots = Eio.Semaphore.make 1 + ; asset_large_slot = Eio.Semaphore.make 1 ; asset_codec_slot = Eio.Semaphore.make 1 ; asset_byte_budget = Eio.Semaphore.make asset_byte_budget_units ; asset_byte_reservation_lock = Eio.Semaphore.make 1 @@ -1480,6 +1482,7 @@ let asset_decode_failure error = report_asset_failure ~reason:reason_name source; match error with | Asset_codec.Checksum_mismatch -> Core.Asset_checksum_mismatch + | Wire_too_large | Plaintext_too_large -> Core.Asset_size_rejected | _ -> Core.Asset_invalid_content Failure_diagnostic.( of_source ~operation:"assetDownload" ~reason:reason_name source |> encode) ;; @@ -1515,10 +1518,8 @@ let asset_wire_bytes ~maximum_plaintext_bytes encrypted = ;; let with_byte_reservation t bytes work = - let units = (max bytes 0 + asset_byte_unit - 1) / asset_byte_unit in - if units > asset_byte_budget_units - then Error Core.Asset_size_rejected - else ( + let units = min asset_byte_budget_units ((max bytes 0 + asset_byte_unit - 1) / asset_byte_unit) in + ( let acquired = ref 0 in Fun.protect ~finally:(fun () -> @@ -1539,13 +1540,14 @@ let fetch_asset_admitted ~cache ~encryption ~maximum_plaintext_bytes + ~estimated_wire_bytes ~current ~(scope : Core.graph_scope) ~asset ~(version : Logseq_db_types.Asset_descriptor.version) = let ( let* ) = Result.bind in - if maximum_plaintext_bytes < 0 || maximum_plaintext_bytes > 100 * 1024 * 1024 + if maximum_plaintext_bytes < 0 || maximum_plaintext_bytes > 200 * 1024 * 1024 then Error (Core.Asset_invalid_content "Invalid asset size limit") else let* graph_key = asset_graph_key t scope encryption in @@ -1576,12 +1578,14 @@ let fetch_asset_admitted ; uri ; headers = [ "authorization", "Bearer " ^ token ] ; maximum_response_bytes - ; expected_content_type = Asset_binary + ; expected_content_type = Asset_download { estimated_wire_bytes } } in match t.dependencies.transport.perform_http ~sw:t.sw request with | Error message -> - last_failure := Core.Asset_network; + last_failure := + (if message = "HTTP body exceeds its configured bound" + then Core.Asset_size_rejected else Core.Asset_network); Error (Request_failed message) | Ok response when response.status = 401 -> last_failure := Core.Asset_authentication; @@ -1592,6 +1596,7 @@ let fetch_asset_admitted | Ok response -> Ok response) |> Result.map_error (fun cause -> let reason = match !last_failure with + | Core.Asset_size_rejected -> "sizeRejected" | Core.Asset_network -> "networkFailed" | Asset_revoked_access -> "revokedAccess" | _ -> "authenticationFailed" in @@ -1651,30 +1656,37 @@ let fetch_asset ~current ~scope ~asset - ~version + ~(version : Logseq_db_types.Asset_descriptor.version) = - with_asset_slot t.asset_download_slots (fun () -> - if t.closed || not (current ()) - then Error Core.Asset_cancelled - else ( - let encrypted = - match encryption with - | Plaintext -> false - | Encrypted _ -> true - in - let reservation = - asset_wire_bytes ~maximum_plaintext_bytes encrypted + maximum_plaintext_bytes - in - with_byte_reservation t reservation (fun () -> - fetch_asset_admitted - t - ~cache - ~encryption - ~maximum_plaintext_bytes - ~current - ~scope - ~asset - ~version))) + let encrypted = match encryption with Plaintext -> false | Encrypted _ -> true in + let wire_bytes maximum_plaintext_bytes = asset_wire_bytes ~maximum_plaintext_bytes encrypted in + let estimated_wire_bytes = + match version.download_size_hint with + | Some size when size >= 0L -> + Some (wire_bytes (Int64.to_int (min size (Int64.of_int maximum_plaintext_bytes)))) + | _ -> None + in + let fetch maximum_plaintext_bytes = + if t.closed || not (current ()) then Error Core.Asset_cancelled + else fetch_asset_admitted t ~cache ~encryption ~maximum_plaintext_bytes ~estimated_wire_bytes + ~current ~scope ~asset ~version + in + (* A small hint buys a concurrent, bounded buffer, not an exact-size check. + If that buffer is exceeded, fail without refetching. Without a hint, use + the single large permit for the full bound but keep the ordinary deadline. + Callers with a lower hard limit can reserve that amount directly. *) + let small_bound = 8 * 1024 * 1024 in + let small_limit = + match estimated_wire_bytes with + | Some bytes when bytes <= small_bound -> Some (min small_bound maximum_plaintext_bytes) + | None when maximum_plaintext_bytes <= 24 * 1024 * 1024 -> Some maximum_plaintext_bytes + | _ -> None + in + match small_limit with + | Some limit -> + with_asset_slot t.asset_download_slots (fun () -> + with_byte_reservation t (wire_bytes limit + limit) (fun () -> fetch limit)) + | None -> with_asset_slot t.asset_large_slot (fun () -> fetch maximum_plaintext_bytes) ;; let close_asset_scope_checked ?except_id t scope = @@ -1810,6 +1822,7 @@ let read_upload_source ~maximum_plaintext_bytes source_file = else ( let bytes = really_input_string input stat.st_size in match input_char input with + | _ when stat.st_size = maximum_plaintext_bytes -> Error Core.Asset_size_rejected | _ -> Error (Core.Asset_invalid_content "Asset upload source grew during reading") | exception End_of_file -> Ok bytes)) with @@ -1824,10 +1837,9 @@ let read_upload_source ~maximum_plaintext_bytes source_file = (Printexc.to_string error) |> encode)) ;; -let put_asset_admitted +let prepare_asset_upload t ~(context : Core.asset_context) - ~asset ~version ~source_file ~maximum_plaintext_bytes @@ -1837,7 +1849,7 @@ let put_asset_admitted let valid () = (not t.closed) && current () in if not (valid ()) then Error Core.Asset_cancelled - else if maximum_plaintext_bytes < 0 || maximum_plaintext_bytes > 100 * 1024 * 1024 + else if maximum_plaintext_bytes < 0 || maximum_plaintext_bytes > 200 * 1024 * 1024 then Error Core.Asset_size_rejected else ( let encryption = if context.encrypted then Encrypted context.key else Plaintext in @@ -1845,8 +1857,7 @@ let put_asset_admitted asset_graph_key t context.scope encryption |> Result.map_error (fun _ -> Core.Asset_locked) in - let* body = - with_asset_slot t.asset_codec_slot (fun () -> + with_asset_slot t.asset_codec_slot (fun () -> if not (valid ()) then Error Core.Asset_cancelled else @@ -1864,12 +1875,22 @@ let put_asset_admitted } in Asset_codec.encode ~maximum_plaintext_bytes ~crypto ~key:graph_key plaintext + |> Result.map (fun body -> String.length plaintext, body) |> Result.map_error (fun source -> Core.Asset_invalid_content Failure_diagnostic.( of_source ~operation:"assetUpload" ~reason:( if source = "Asset exceeds plaintext size limit" then "sizeRejected" else "cryptoInvalid") - source |> encode)))) - in + source |> encode))))) +;; + +let send_asset_upload + t ~(context : Core.asset_context) ~asset + ~(version : Logseq_db_types.Asset_descriptor.version) ~size ~body ~current + = + let ( let* ) = Result.bind in + let valid () = (not t.closed) && current () in + if not (valid ()) then Error Core.Asset_cancelled + else ( let base_url = context.scope.account.managed_sync_origin in let* () = Http.validate_base_url base_url @@ -1907,9 +1928,52 @@ let put_asset_admitted ; expected_content_type = Asset_binary } in - match t.dependencies.transport.perform_http ~sw:t.sw request with + let perform request = t.dependencies.transport.perform_http ~sw:t.sw request in + let control action = + let payload = Yojson.Safe.to_string (`Assoc + [ "action", `String action; "size", `Int size + ; "checksum", `String version.checksum ]) in + perform { request with operation = Post payload + ; headers = [ "authorization", "Bearer " ^ token + ; "content-type", "application/json" ] } + in + let transfer () = + if String.length body <= 100 * 1024 * 1024 then perform request + else + let* plan = control "prepare" in + if plan.status < 200 || plan.status >= 300 then Ok plan + else if not (valid ()) then Error "Asset upload expired" + else + let open Yojson.Safe.Util in + try + let json = Yojson.Safe.from_string plan.body in + match json |> member "mode" |> to_string with + | "present" -> control "complete" + | "proxy" -> perform request + | "direct" -> + let uri = Uri.of_string (json |> member "url" |> to_string) in + let allowed = [ "content-type"; "x-amz-meta-checksum" + ; "x-amz-meta-size"; "x-amz-meta-type"; "if-match"; "if-none-match" ] in + let headers = json |> member "headers" |> to_assoc + |> List.map (fun (name, value) -> String.lowercase_ascii name, to_string value) in + if Uri.scheme uri <> Some "https" || Uri.host uri = None + || Uri.userinfo uri <> None || Uri.fragment uri <> None + || not (List.for_all (fun (name, value) -> + List.mem name allowed && not (String.exists (fun ch -> ch < ' ' || ch = '\127') value)) headers) + || List.length headers <> List.length (List.sort_uniq String.compare (List.map fst headers)) + then Error "Invalid signed asset upload plan" + else ( + match perform { request with uri; headers } with + | Ok uploaded when uploaded.status = 412 || (uploaded.status >= 200 && uploaded.status < 300) -> + if valid () then control "complete" else Error "Asset upload expired" + | _ -> Error "Signed asset upload failed") + | _ -> Error "Invalid asset upload plan" + with Yojson.Json_error _ | Type_error _ | Invalid_argument _ -> + Error "Invalid asset upload plan" + in + match transfer () with | Error message -> - failure := Core.Asset_network; + failure := (if valid () then Core.Asset_network else Core.Asset_cancelled); Error (Request_failed message) | Ok response when response.status = 401 -> failure := Core.Asset_authentication; @@ -1954,22 +2018,34 @@ let put_asset ~maximum_plaintext_bytes ~current = - with_asset_slot t.asset_upload_slots (fun () -> - let reservation = - asset_wire_bytes - ~maximum_plaintext_bytes - (context.encrypted && Option.is_some context.key) - + maximum_plaintext_bytes + let prepare maximum_plaintext_bytes = + prepare_asset_upload t ~context ~version ~source_file ~maximum_plaintext_bytes ~current + in + let send (size, body) = send_asset_upload t ~context ~asset ~version ~size ~body ~current in + let large () = + with_asset_slot t.asset_large_slot (fun () -> + Result.bind (prepare maximum_plaintext_bytes) send) + in + if maximum_plaintext_bytes < 0 || maximum_plaintext_bytes > 200 * 1024 * 1024 + then Error Core.Asset_size_rejected + else + let size = + try (Unix.stat source_file).st_size with Unix.Unix_error _ -> 8 * 1024 * 1024 in - with_byte_reservation t reservation (fun () -> - put_asset_admitted - t - ~context - ~asset - ~version - ~source_file - ~maximum_plaintext_bytes - ~current)) + let bound = min size maximum_plaintext_bytes in + if bound > 24 * 1024 * 1024 then large () + else + let reservation = asset_wire_bytes ~maximum_plaintext_bytes:bound context.encrypted + bound in + match + with_asset_slot t.asset_upload_slots (fun () -> + with_byte_reservation t reservation (fun () -> + match prepare bound with + | Error Core.Asset_size_rejected when bound < maximum_plaintext_bytes -> None + | Error error -> Some (Error error) + | Ok prepared -> Some (send prepared))) + with + | None -> large () + | Some result -> result ;; let staged_asset_path t ~scope ~file = diff --git a/logseq_sync/lib/effect_runner/eio/http.ml b/logseq_sync/lib/effect_runner/eio/http.ml index 56b9773c..cac0a699 100644 --- a/logseq_sync/lib/effect_runner/eio/http.ml +++ b/logseq_sync/lib/effect_runner/eio/http.ml @@ -1,11 +1,13 @@ type operation = | Get | Put of string + | Post of string type expected_content_type = | Structured_response | Snapshot_artifact | Asset_binary + | Asset_download of { estimated_wire_bytes : int option } type request = { operation : operation @@ -153,14 +155,14 @@ let validate_response_content_type request headers = ( request.expected_content_type , Option.map media_type (response_header "content-type" headers) ) with - | (Snapshot_artifact | Asset_binary), None -> Ok () + | (Snapshot_artifact | Asset_binary | Asset_download _), None -> Ok () | Structured_response, None -> Error "sync HTTP response is missing Content-Type" | expected_content_type, Some value -> let accepted = match expected_content_type with | Structured_response -> structured_media_type value | Snapshot_artifact -> artifact_media_type value - | Asset_binary -> true + | Asset_binary | Asset_download _ -> true in if accepted then Ok () diff --git a/logseq_sync/lib/effect_runner/eio/http.mli b/logseq_sync/lib/effect_runner/eio/http.mli index e7bfc557..30101b31 100644 --- a/logseq_sync/lib/effect_runner/eio/http.mli +++ b/logseq_sync/lib/effect_runner/eio/http.mli @@ -1,11 +1,13 @@ type operation = | Get | Put of string + | Post of string type expected_content_type = | Structured_response | Snapshot_artifact | Asset_binary + | Asset_download of { estimated_wire_bytes : int option } type request = { operation : operation diff --git a/logseq_sync/lib/effect_runner/eio/http_eio.ml b/logseq_sync/lib/effect_runner/eio/http_eio.ml index 42692f32..3f9dede6 100644 --- a/logseq_sync/lib/effect_runner/eio/http_eio.ml +++ b/logseq_sync/lib/effect_runner/eio/http_eio.ml @@ -157,6 +157,7 @@ let with_attempt ~sw ~authenticator ~network ~clock ~response_budget request ~co match request.Http.operation with | Get -> `GET | Put _ -> `PUT + | Post _ -> `POST in let response_handler response body = guard (fun () -> @@ -182,7 +183,7 @@ let with_attempt ~sw ~authenticator ~network ~clock ~response_budget request ~co let request_headers = match request.Http.operation with | Get -> request.headers - | Put bytes -> + | Put bytes | Post bytes -> ("content-length", string_of_int (String.length bytes)) :: request.headers in @@ -208,7 +209,7 @@ let with_attempt ~sw ~authenticator ~network ~clock ~response_budget request ~co in (match request.Http.operation with | Get -> () - | Put bytes -> Httpun.Body.Writer.write_string writer bytes); + | Put bytes | Post bytes -> Httpun.Body.Writer.write_string writer bytes); Httpun.Body.Writer.close writer; Eio.Promise.await completed; Eio.Fiber.check (); @@ -294,7 +295,7 @@ let follow_redirects attempt request = then if match request.Http.operation with - | Put _ -> true + | Put _ | Post _ -> true | Get -> false then Error "Asset uploads cannot redirect" else if remaining = 0 @@ -312,10 +313,24 @@ let protected f = | exception_ -> Error (exception_message exception_) ;; +let response_deadline (request : Http.request) = + let asset_bytes = + match request.expected_content_type, request.operation with + | Asset_download { estimated_wire_bytes }, Get -> + Option.value estimated_wire_bytes ~default:0 + | Asset_binary, Put bytes -> String.length bytes + | _ -> 0 + in + if asset_bytes <= 8 * 1024 * 1024 + then 30. + else 30. +. (Float.of_int (min asset_bytes (280 * 1024 * 1024)) /. 262144.) +;; + let perform ~sw ~authenticator ~network ~clock request = Tls_client_eio.initialize_rng (); - let response_budget = ref 30. in - protected (fun () -> + let deadline = response_deadline request in + let response_budget = ref deadline in + let perform () = Result.bind (follow_redirects (request_once ~sw ~authenticator ~network ~clock ~response_budget) @@ -326,7 +341,12 @@ let perform ~sw ~authenticator ~network ~clock request = Result.map (fun () -> response) (Http.validate_response_content_type request response.headers) - else Ok response)) + else Ok response) + in + protected (fun () -> + match request.expected_content_type with + | Asset_download _ -> Eio.Time.with_timeout_exn clock deadline perform + | _ -> perform ()) ;; let remove_partial path = diff --git a/logseq_sync/lib/effect_runner/platform/platform_crypto_stubs.c b/logseq_sync/lib/effect_runner/platform/platform_crypto_stubs.c index 6fbaa9fc..0a8dff42 100644 --- a/logseq_sync/lib/effect_runner/platform/platform_crypto_stubs.c +++ b/logseq_sync/lib/effect_runner/platform/platform_crypto_stubs.c @@ -50,7 +50,7 @@ CAMLprim value logseq_journal_crypto_binary_call( value encrypt, value key, value iv, value input) { CAMLparam4(encrypt, key, iv, input); CAMLlocal2(result, payload); - const size_t limit = 8 * 1024 * 1024; + const size_t limit = 200 * 1024 * 1024; const int sealing = Bool_val(encrypt); const size_t key_length = caml_string_length(key); const size_t iv_length = caml_string_length(iv); diff --git a/logseq_sync/lib/effect_runner/protocol/asset_codec.ml b/logseq_sync/lib/effect_runner/protocol/asset_codec.ml index 72c6eafa..458d0471 100644 --- a/logseq_sync/lib/effect_runner/protocol/asset_codec.ml +++ b/logseq_sync/lib/effect_runner/protocol/asset_codec.ml @@ -8,7 +8,7 @@ type crypto = let checksum bytes = Digestif.SHA256.(to_hex (digest_string bytes)) let ( let* ) = Result.bind -let limit maximum = maximum >= 0 && maximum <= 100 * 1024 * 1024 +let limit maximum = maximum >= 0 && maximum <= 200 * 1024 * 1024 let encode ~maximum_plaintext_bytes ~crypto ~key bytes = if diff --git a/logseq_sync/lib/effect_runner/storage/bootstrap.ml b/logseq_sync/lib/effect_runner/storage/bootstrap.ml index c9a0c474..2c643949 100644 --- a/logseq_sync/lib/effect_runner/storage/bootstrap.ml +++ b/logseq_sync/lib/effect_runner/storage/bootstrap.ml @@ -775,7 +775,7 @@ module Asset_cache = struct if budget_bytes < 0L || maximum_file_bytes < 0 - || maximum_file_bytes > 100 * 1024 * 1024 + || maximum_file_bytes > 200 * 1024 * 1024 then Error (Invalid "Invalid cache size limits") else ( let directory = diff --git a/logseq_sync/lib/pure_reducer/asset_transfer.ml b/logseq_sync/lib/pure_reducer/asset_transfer.ml index 06d5720d..81dbe283 100644 --- a/logseq_sync/lib/pure_reducer/asset_transfer.ml +++ b/logseq_sync/lib/pure_reducer/asset_transfer.ml @@ -282,6 +282,7 @@ let pump t = then Option.map (fun version -> + let version = Asset.with_download_size_hint version entry.descriptor.size in let t, ticket = fresh_fetch t uuid version in t, Fetching ticket, Fetch ticket) (remote_version entry.descriptor) diff --git a/logseq_sync/lib/pure_reducer/core.ml b/logseq_sync/lib/pure_reducer/core.ml index 6a17cba7..811ed8a8 100644 --- a/logseq_sync/lib/pure_reducer/core.ml +++ b/logseq_sync/lib/pure_reducer/core.ml @@ -3858,7 +3858,7 @@ let request_asset core (request : asset_request) = match request.action with | Fetch_asset { maximum_plaintext_bytes; _ } | Put_asset_file { maximum_plaintext_bytes; _ } -> - maximum_plaintext_bytes >= 0 && maximum_plaintext_bytes <= 100 * 1024 * 1024 + maximum_plaintext_bytes >= 0 && maximum_plaintext_bytes <= 200 * 1024 * 1024 | Asset_retry_after seconds -> Float.is_finite seconds && seconds >= 0. | Commit_graph_asset_deletion deletion | Cancel_graph_asset_deletion deletion -> asset_deletion_scope deletion = request.scope diff --git a/logseq_sync/test/asset_native_interop.ml b/logseq_sync/test/asset_native_interop.ml index a9bcf621..514256b4 100644 --- a/logseq_sync/test/asset_native_interop.ml +++ b/logseq_sync/test/asset_native_interop.ml @@ -47,7 +47,7 @@ let () = let key = read (path "key.bin") in reject "plaintext above the native attachment limit" - (crypto.encrypt ~key ~plaintext:(String.make ((8 * 1024 * 1024) + 1) 'x')); + (crypto.encrypt ~key ~plaintext:(String.make ((200 * 1024 * 1024) + 1) 'x')); reject "invalid key length" (crypto.encrypt ~key:"short" ~plaintext:""); reject "invalid nonce length" diff --git a/logseq_sync/test/test_asset_codec.ml b/logseq_sync/test/test_asset_codec.ml index c1e56325..cc691b16 100644 --- a/logseq_sync/test/test_asset_codec.ml +++ b/logseq_sync/test/test_asset_codec.ml @@ -314,6 +314,16 @@ let transit_failures_never_become_raw () = (get (decode envelope)) ;; +let plaintext_size_boundary () = + let limit = 200 * 1024 * 1024 in + let bytes = String.make limit 'a' in + let encoded = get (C.encode ~maximum_plaintext_bytes:limit ~crypto ~key:None bytes) in + Alcotest.(check int) "exact limit accepted" limit (String.length encoded); + match C.encode ~maximum_plaintext_bytes:limit ~crypto ~key:None (bytes ^ "a") with + | Error "Asset exceeds plaintext size limit" -> () + | _ -> Alcotest.fail "one byte over must be rejected" +;; + let () = Alcotest.run "asset codec" @@ -332,6 +342,7 @@ let () = transit_failures_never_become_raw ; Alcotest.test_case "raw binary envelope" `Quick raw_bytes ; Alcotest.test_case "plaintext" `Quick plaintext + ; Alcotest.test_case "200 MiB boundary" `Slow plaintext_size_boundary ; Alcotest.test_case "invalid and oversized" `Quick validation ; Alcotest.test_case "bounded envelope shape" `Quick bounded_envelope_shape ] ) diff --git a/logseq_sync/test/transport_contract.ml b/logseq_sync/test/transport_contract.ml index dea3c72b..d19795b0 100644 --- a/logseq_sync/test/transport_contract.ml +++ b/logseq_sync/test/transport_contract.ml @@ -2456,7 +2456,7 @@ let scenarios = @ [ Alcotest.test_case "asset upload resource admission" `Quick asset_upload_admission ] ;; -let asset_download_budget maximum_plaintext_bytes expected_entered () = +let asset_download_budget ?size maximum_plaintext_bytes expected_entered () = let module Asset = Logseq_db_types.Asset_descriptor in with_support (fun support -> Eio_main.run (fun environment -> @@ -2474,6 +2474,7 @@ let asset_download_budget maximum_plaintext_bytes expected_entered () = in let version = Asset.version ~checksum:(String.make 64 '0') ~file_type:"bin" |> Result.get_ok + |> fun version -> Asset.with_download_size_hint version size in let cores = List.init 5 (fun index -> @@ -2512,7 +2513,7 @@ let asset_download_budget maximum_plaintext_bytes expected_entered () = Runner.shutdown t))) ;; -let asset_download_admission = asset_download_budget 4 3 +let asset_download_admission = asset_download_budget ~size:1024L (200 * 1024 * 1024) 3 let scenarios = scenarios @@ -2520,9 +2521,41 @@ let scenarios = "asset download resource admission" `Quick asset_download_admission + ; Alcotest.test_case "known 24 MiB downloads share the large lane" `Quick + (asset_download_budget ~size:25165824L (200 * 1024 * 1024) 1) ] ;; +let asset_download_without_size () = + let bytes = String.make ((8 * 1024 * 1024) + 1) 'x' in + let version = Logseq_db_types.Asset_descriptor.version + ~checksum:(Logseq_sync_effect_runner.Asset_codec.checksum bytes) ~file_type:"bin" + |> Result.get_ok in + let wire = response + ~headers:(Printf.sprintf "Content-Length: %d\r\n" (String.length bytes)) bytes in + let report = + with_peer [ case wire ] (fun ~environment ~sw ~support ~origin -> + let posted = ref [] in + let t = runner ~environment ~sw ~support ~posted ~invalidations:(ref 0) () in + let selected, scope = bootstrap ~mirror_absent:false origin in + let result = + asset_run t ~clock:(Eio.Stdenv.clock environment) ~posted selected.next scope + "download-over-small-bound" + (Core.Fetch_asset + { asset = scope.graph_id; version; maximum_plaintext_bytes = 200 * 1024 * 1024 }) + in + Alcotest.(check bool) "a legal asset above the small bound still downloads" true + (match result with Ok (Core.Asset_downloaded _) -> true | _ -> false); + Runner.shutdown t) + in + check_retired report; + Alcotest.(check int) "one GET for an unknown size above the small bound" 1 Yojson.Basic.Util.(report |> to_list |> List.length) +;; + +let scenarios = + scenarios @ [ Alcotest.test_case "unknown-size asset above small bound downloads once" `Quick asset_download_without_size ] +;; + let shared_asset_byte_budget = asset_download_budget 16777216 2 let scenarios = @@ -3343,6 +3376,49 @@ let delayed_case ?(tls_delay = 0.) ?(response_delay = 0.) wire = | _ -> assert false ;; +let test_slow_asset_download ~size () = + let module Transfer = Logseq_sync_pure_reducer.Asset_transfer in + let bytes = "slow asset" in + let version = Logseq_db_types.Asset_descriptor.version + ~checksum:(Logseq_sync_effect_runner.Asset_codec.checksum bytes) ~file_type:"bin" + |> Result.get_ok in + let report = + with_peer + [ delayed_case ~response_delay:1.8 + (response ~headers:"Content-Length: 10\r\n" bytes) ] + (fun ~environment ~sw ~support ~origin -> + let wall = Eio.Stdenv.clock environment in + let clock = scaled_clock wall 20. in + let posted = ref [] in + let runner = runner ~clock ~environment ~sw ~support ~posted + ~invalidations:(ref 0) () in + let selected, scope = bootstrap ~mirror_absent:false origin in + let descriptor = Logseq_db_types.Asset_descriptor.create ~uuid:scope.graph_id + ~source:(Managed (Some version)) ~current_checksum:None ~size ~dimensions:None + |> Result.get_ok in + let scheduler = Transfer.create + (Transfer.config ~active:2 ~foreground_reserved:1 ~pending:3 ~retries:0 |> Result.get_ok) + ~scope ~online:true ~unlocked:true in + let scheduler, work = Transfer.step scheduler + (Replace { consumer = "slow-download"; priority = Foreground; assets = [descriptor] }) in + let lookup = List.find_map (function Transfer.Check_cache ticket -> Some ticket | _ -> None) work + |> Option.get in + let _, work = Transfer.step scheduler (Cache_checked (lookup, Ok None)) in + let fetch = List.find_map (function Transfer.Fetch ticket -> Some ticket | _ -> None) work + |> Option.get in + let result = asset_run runner ~clock:wall ~posted selected.next scope "slow-download" + (Core.Fetch_asset { asset = fetch.asset; version = fetch.version; + maximum_plaintext_bytes = 200 * 1024 * 1024 }) in + Alcotest.(check bool) "declared size determines whether the first GET survives 30s" true + (match size, result with + | Some _, Ok (Core.Asset_downloaded _) | None, Error Core.Asset_network -> true + | _ -> false); + Runner.shutdown runner) + in + check_retired report; + Alcotest.(check int) "exactly one GET" 1 Yojson.Basic.Util.(report |> to_list |> List.length) +;; + let test_tls_slow_legal_handshake () = let report = with_peer @@ -3512,6 +3588,10 @@ let scenarios = "redirect response deadline remains shared" `Quick test_redirect_response_budget_is_shared + ; Alcotest.test_case "known 24 MiB gets a longer first GET" `Quick + (test_slow_asset_download ~size:(Some 25165824L)) + ; Alcotest.test_case "unknown size keeps one ordinary GET" `Quick + (test_slow_asset_download ~size:None) ] ;; diff --git a/swift/JournalE2EECrypto.swift b/swift/JournalE2EECrypto.swift index b2666944..40e69716 100644 --- a/swift/JournalE2EECrypto.swift +++ b/swift/JournalE2EECrypto.swift @@ -1217,9 +1217,9 @@ public func logseqJournalCryptoBinary( outputLength?.pointee = -1 guard let key, let input, let outputLength, keyLength == 32, inputLength >= 0, - (sealing == 1 && ivLength == 0 && inputLength <= 8 * 1024 * 1024) + (sealing == 1 && ivLength == 0 && inputLength <= 200 * 1024 * 1024) || (sealing == 0 && ivLength == 12 && inputLength >= 16 - && inputLength <= 8 * 1024 * 1024 + 16) + && inputLength <= 200 * 1024 * 1024 + 16) else { return nil } outputLength.pointee = -4 do {