diff --git a/shared/src/logseq/core/graph_runtime.ml b/shared/src/logseq/core/graph_runtime.ml index 77964f08..c4614f87 100644 --- a/shared/src/logseq/core/graph_runtime.ml +++ b/shared/src/logseq/core/graph_runtime.ml @@ -240,6 +240,7 @@ let rebase_operation runtime server_t projected operation = Ops.save runtime.path { operation with state = Ops.Conflicted message }; Ops.Conflicted message | Ok tx -> + let tx = Journal_sync.pending_tx !projected tx in projected := Journal_sync.replay !projected operation.operation_id (Ops.outliner_op operation.intent) tx; if operation.base_t <> server_t then @@ -554,13 +555,14 @@ let prepare_sync_batch runtime operations = else Ok () in let* tx = stored_transaction runtime before operation in - let items = Dev_sync.Sync_apply.normalize_tx_data_for_rebase (Dev_sync.Transit_codec.of_string tx) in + let tx = Journal_sync.pending_tx before tx in + let items = Dev_sync.Sync_apply.normalize_tx_data_for_rebase tx in Hashtbl.iter (fun uuid value -> Hashtbl.replace created uuid value) (Dev_sync.Sync_replay.tx_self_created items); if Dev_sync.Sync_replay.pending_tx_unresolvable (Ds.conn_db runtime.conn) ~created items then Error "pending transaction is waiting for confirmed dependencies" else - let* wire = Journal_sync.encode runtime.encrypt_title tx in + let* wire = Journal_sync.encode runtime.encrypt_title items in Ok (tx, (Ops.outliner_op operation.intent, wire)) in let rec loop before reversed = function @@ -726,9 +728,10 @@ let stage ?journal_tasks runtime (operation : Ops.pending_operation) = in let ( let* ) = Result.bind in let* normalized = Ops.normalize_operation before operation in - let* operations = Projection.compile before normalized.intent in - let report = Ds.with_tx (Dev_sync.Sync_replay.display_db_from_server before) operations in let now = int_of_float (Unix.gettimeofday () *. 1000.) in + (* Persist the edit time in the resolved transaction so retries reuse it. *) + let* operations = Projection.compile ~updated_at:now before normalized.intent in + let report = Ds.with_tx (Dev_sync.Sync_replay.display_db_from_server before) operations in (* Template copies can add tags too (a date variable creates a journal), so repeat until no new template applies; each template applies in one pass. *) let rec apply_templates applied templates additions txs db pass = @@ -736,7 +739,7 @@ let stage ?journal_tasks runtime (operation : Ops.pending_operation) = match template with | None -> Ok (templates, additions, txs, db) | Some template -> - let* operations = Projection.compile db template in + let* operations = Projection.compile ~updated_at:now db template in let pass = Ds.with_tx db operations in let applied = List.fold_left (fun applied (d : Ds.datom) -> if d.added && d.a = "logseq.property/used-template" then diff --git a/shared/src/logseq/core/journal_sync.ml b/shared/src/logseq/core/journal_sync.ml index 268384b0..ad8318b0 100644 --- a/shared/src/logseq/core/journal_sync.ml +++ b/shared/src/logseq/core/journal_sync.ml @@ -109,18 +109,44 @@ let capture_report ?creator report = let capture ?creator db tx = capture_report ?creator (Ds.with_tx (Dev.Sync_replay.display_db_from_server db) tx) +let pending_tx db tx = + let reconcile items = + let newer = Hashtbl.create 4 in + let timestamp value = Graph_read.int_value (Some (Dev.Ds_wire.value_of_transit value)) in + List.iter (function + | Wire.Array (Wire.Keyword "db/add" :: (Wire.Array [Wire.Keyword "block/uuid"; Wire.Uuid uuid] as entity) + :: Wire.Keyword "block/updated-at" :: value :: _) -> + let current = Option.bind (Ds.entid db "block/uuid" (Ds.Uuid uuid)) + (fun eid -> Graph_read.int_value (Graph_read.value db eid "block/updated-at")) in + (match current, timestamp value with + | Some current, Some written when current >= written -> Hashtbl.replace newer entity current + | _ -> ()) + | _ -> ()) items; + (* Preserve the recorded edit time on disk. Suppress stale writes and their + paired retractions against the current base for both replay and upload. *) + if Hashtbl.length newer = 0 then items + else List.filter (function + | Wire.Array (Wire.Keyword ("db/add" | "db/retract") :: entity :: Wire.Keyword "block/updated-at" :: value :: _) -> + (match Hashtbl.find_opt newer entity, timestamp value with + | Some current, Some written -> written > current + | _ -> true) + | _ -> true) items + in + match Dev.Transit_codec.of_string tx with + | Wire.Array items -> Wire.Array (reconcile items) + | Wire.List items -> Wire.List (reconcile items) + | tx -> tx + let replay db operation_id outliner_op tx = let conn = Ds.conn_from_db (Dev.Sync_replay.display_db_from_server db) in let entry = - { Dev.Sync_client_op.tx_id = operation_id; tx = Dev.Transit_codec.of_string tx; - outliner_op = Some outliner_op } + { Dev.Sync_client_op.tx_id = operation_id; tx; outliner_op = Some outliner_op } in Dev.Sync_replay.replay_pending_entry "mobile" conn entry; Ds.conn_db conn -let encode encrypt tx = +let encode encrypt items = try - let items = Dev.Sync_apply.normalize_tx_data_for_rebase (Dev.Transit_codec.of_string tx) in Result.map (fun items -> Dev.Transit_codec.to_string (Wire.Array items)) (map_protected encrypt items) with error -> Error (Printexc.to_string error) diff --git a/shared/src/logseq/core/journal_sync.mli b/shared/src/logseq/core/journal_sync.mli index d73e82ae..acfb766e 100644 --- a/shared/src/logseq/core/journal_sync.mli +++ b/shared/src/logseq/core/journal_sync.mli @@ -12,8 +12,9 @@ val decode : string -> (journal, string) result val extend_report : Datascript.tx_report -> Datascript.tx_op list -> Datascript.tx_report val capture_report : ?creator:Created_by.identity -> Datascript.tx_report -> Datascript.db * string * string val capture : ?creator:Created_by.identity -> Datascript.db -> Datascript.tx_op list -> Datascript.db * string * string -val replay : Datascript.db -> string -> string -> string -> Datascript.db -val encode : (string -> (string, string) result) -> string -> (string, string) result +val pending_tx : Datascript.db -> string -> Dev_sync.Wire.t +val replay : Datascript.db -> string -> string -> Dev_sync.Wire.t -> Datascript.db +val encode : (string -> (string, string) result) -> Dev_sync.Wire.t list -> (string, string) result val apply : (string -> (string, string) result) -> Datascript.conn -> int -> journal -> (applied, string) result diff --git a/shared/src/logseq/core/pending_projection.ml b/shared/src/logseq/core/pending_projection.ml index d874fc07..abf39e85 100644 --- a/shared/src/logseq/core/pending_projection.ml +++ b/shared/src/logseq/core/pending_projection.ml @@ -209,6 +209,16 @@ let title_tx db uuid title = (tag_eids_for_title db title) @ List.concat_map (tag_behavior_tx db uuid) (tag_eids_for_title db title) +let activity_at_least db uuid timestamp = + Option.exists (fun current -> current >= timestamp) + (Graph_read.int_value (one_value db (lookup uuid) "block/updated-at")) + +let with_updated_at db uuid updated_at writes = + match updated_at with + | Some timestamp when not (activity_at_least db uuid timestamp) -> + Ds.Add (lookup uuid, "block/updated-at", Ds.Int64 (Int64.of_int timestamp)) :: writes + | _ -> writes + let uuid_for_eid db eid = match one_value db (Ds.Entity_id eid) "block/uuid" with | Some (Ds.Uuid uuid) -> Some uuid @@ -274,10 +284,14 @@ let insert_tx db (block : Outliner.outliner_block) created_at = ] @ List.concat_map (tag_behavior_tx db block.uuid) (tag_eids_for_title db block.title) -let outliner_mutation_tx db (mutation : Outliner.mutation) = +let outliner_mutation_tx db ?updated_at (mutation : Outliner.mutation) = match mutation with | Outliner.Set_title value -> - title_tx db value.uuid value.title + let writes = title_tx db value.uuid value.title in + if updated_at = None + || one_value db (lookup value.uuid) "block/title" = Some (Ds.String value.title) + then writes + else with_updated_at db value.uuid updated_at writes | Outliner.Insert value -> insert_tx db value.insert_block value.created_at | Outliner.Reparent value -> @@ -295,7 +309,7 @@ let outliner_mutation_tx db (mutation : Outliner.mutation) = | Some eid -> [ Ds.RetractEntity (Ds.Entity_id eid) ] | None -> []) -let compile_outliner db command = +let compile_outliner db ?updated_at command = let ( let* ) = Result.bind in let find_block uuid = outliner_block db uuid in let children uuid = @@ -310,9 +324,7 @@ let compile_outliner db command = in let* mutations = Outliner.plan find_block children command in Ok - (List.concat_map - (fun mutation -> outliner_mutation_tx db mutation) - mutations) + (List.concat_map (outliner_mutation_tx db ?updated_at) mutations) let children db eid = List.of_seq @@ -476,10 +488,6 @@ let resolve_page_references literal_blocks db intent = | _ -> intent in if !created = [] then next else Ops.Atomic (List.rev !created @ [next]) -let activity_at_least db uuid timestamp = - Option.exists (fun current -> current >= timestamp) - (Graph_read.int_value (one_value db (lookup uuid) "block/updated-at")) - let discussion_block_tx ~uuid ~title ~page ~parent ~order ~created_at ~tag extra = entity_tx (Ds.Temp_id ("pending/" ^ uuid)) ([ "block/uuid", Ds.One_value (Ds.Uuid uuid); @@ -582,9 +590,9 @@ let compile_reaction db (write : Collaboration.reaction_write) = Ok (C.own_reactions db ~target:write.target ~actor:write.actor ~emoji:write.emoji |> List.map (fun reaction -> Ds.RetractEntity (Ds.Entity_id reaction))) -let rec compile_with_literals literal_blocks db (intent : Ops.pending_intent) = +let rec compile_with_literals literal_blocks updated_at db (intent : Ops.pending_intent) = let resolved = resolve_page_references literal_blocks db intent in - if resolved <> intent then compile_with_literals literal_blocks db resolved else + if resolved <> intent then compile_with_literals literal_blocks updated_at db resolved else match intent with | Ops.Add_comment write -> compile_comment db write | Ops.Set_reaction write -> compile_reaction db write @@ -637,7 +645,7 @@ let rec compile_with_literals literal_blocks db (intent : Ops.pending_intent) = let ( let* ) = Result.bind in let* _, reversed = List.fold_left (fun result intent -> let* projected, reversed = result in - let* tx = compile_with_literals literal_blocks projected intent in + let* tx = compile_with_literals literal_blocks updated_at projected intent in try Ok (Ds.db_with tx projected, List.rev_append tx reversed) with error -> Error (Printexc.to_string error)) (Ok (db, [])) intents in Ok (List.rev reversed) @@ -658,8 +666,12 @@ let rec compile_with_literals literal_blocks db (intent : Ops.pending_intent) = if current = value.expected_title then let id = Option.get (Ds.entid db "block/uuid" (Ds.Uuid value.uuid)) in Result.map (fun () -> - if is_query_definition db id then [Ds.Add (lookup value.uuid, "block/title", Ds.String value.title)] - else title_tx db value.uuid value.title) (Node_title.validate db id value.title) + let writes = + if is_query_definition db id then [Ds.Add (lookup value.uuid, "block/title", Ds.String value.title)] + else title_tx db value.uuid value.title in + if current = value.title then writes + else with_updated_at db value.uuid updated_at writes) + (Node_title.validate db id value.title) else Error "title changed on the server" | None -> Error "block no longer exists") | Ops.Set_property value -> @@ -689,10 +701,7 @@ let rec compile_with_literals literal_blocks db (intent : Ops.pending_intent) = else let writes = List.concat_map (fun (change : Ops.property_change) -> property_txs db value.uuid change.attr change.value) value.changes in - Ok (match value.updated_at with - | Some timestamp when not (activity_at_least db value.uuid timestamp) -> - Ds.Add (lookup value.uuid, "block/updated-at", Ds.Int64 (Int64.of_int timestamp)) :: writes - | _ -> writes) + Ok (with_updated_at db value.uuid value.updated_at writes) | Ops.Insert_block value -> if Ds.entid db "block/uuid" (Ds.Uuid value.uuid) <> None then Error "inserted block UUID already exists" @@ -810,14 +819,14 @@ let rec compile_with_literals literal_blocks db (intent : Ops.pending_intent) = match moves with | [] -> Ok tx | move :: rest -> - (match compile_with_literals literal_blocks projected (Ops.Move_block move) with + (match compile_with_literals literal_blocks updated_at projected (Ops.Move_block move) with | Ok step -> loop (Ds.db_with step projected) (tx @ step) rest | Error _ as error -> error) in loop db [] value.moves | Ops.Split_block value -> - compile_outliner db + compile_outliner db ?updated_at (Outliner.Split { Outliner.source_uuid = value.uuid; @@ -829,7 +838,7 @@ let rec compile_with_literals literal_blocks db (intent : Ops.pending_intent) = created_at = value.created_at; }) | Ops.Merge_backward value -> - compile_outliner db + compile_outliner db ?updated_at (Outliner.Merge_backward { Outliner.source_uuid = value.uuid; @@ -1117,7 +1126,7 @@ let rec compile_with_literals literal_blocks db (intent : Ops.pending_intent) = Datascript_value.datoms_by_ref db Ds.Aevt attr target |> Seq.map (fun (d : Ds.datom) -> Ds.Retract (Ds.Entity_id d.e, attr, Some d.v)) |> List.of_seq) db.Ds.schema)))) -let compile db intent = +let compile ?updated_at db intent = let literal_blocks = Hashtbl.create 8 in let display_type uuid attr value = if attr = "logseq.property.node/display-type" then @@ -1130,7 +1139,7 @@ let compile db intent = display_type value.uuid change.attr change.value) value.changes | _ -> () in scan intent; - compile_with_literals literal_blocks db intent + compile_with_literals literal_blocks updated_at db intent let block_location_matches db uuid page_uuid parent_uuid order = Ds.entid db "block/uuid" (Ds.Uuid uuid) <> None diff --git a/shared/src/logseq/core/pending_projection.mli b/shared/src/logseq/core/pending_projection.mli index 9eca3a6f..e30a8cee 100644 --- a/shared/src/logseq/core/pending_projection.mli +++ b/shared/src/logseq/core/pending_projection.mli @@ -39,9 +39,9 @@ val entity_tx : val insert_tx : Datascript.db -> Outliner.outliner_block -> int -> Datascript.tx_op list val outliner_mutation_tx : - Datascript.db -> Outliner.mutation -> Datascript.tx_op list + Datascript.db -> ?updated_at:int -> Outliner.mutation -> Datascript.tx_op list val compile_outliner : - Datascript.db -> Outliner.command -> (Datascript.tx_op list, string) result + Datascript.db -> ?updated_at:int -> Outliner.command -> (Datascript.tx_op list, string) result val children : Datascript.db -> int -> int list val subtree : Datascript.db -> int list -> int list val page_entity : Datascript.db -> int -> bool @@ -49,6 +49,7 @@ val would_create_cycle : Datascript.db -> int -> int -> bool val property_tx : string -> string -> Pending_ops.semantic_value option -> Datascript.tx_op val compile : + ?updated_at:int -> Datascript.db -> Pending_ops.pending_intent -> (Datascript.tx_op list, string) result diff --git a/shared/test/logseq/journal_sync_test.ml b/shared/test/logseq/journal_sync_test.ml index 80ea3155..6bae95e3 100644 --- a/shared/test/logseq/journal_sync_test.ml +++ b/shared/test/logseq/journal_sync_test.ml @@ -31,19 +31,30 @@ let message ?before ?(typ = "pull/ok") t rows = ([ "type", `String typ; "t", `Int t; "txs", `List rows ] @ match before with None -> [] | Some t -> [ "t-before", `Int t ])) -let with_graph ?(encrypted = false) f = +let with_graph ?(encrypted = false) ?child_title f = Mobile_graph_test.with_directory (fun dir -> let path = Filename.concat dir "graph.sqlite" in Graph_sqlite.prepare_staging path; let db = Ds.db_with - [ Ds.Add (Ds.Entity_id 1, "block/uuid", Ds.Uuid page); + ([ Ds.Add (Ds.Entity_id 1, "block/uuid", Ds.Uuid page); Ds.Add (Ds.Entity_id 1, "block/title", Ds.String "Page"); Ds.Add (Ds.Entity_id 10, "block/uuid", Ds.Uuid block); Ds.Add (Ds.Entity_id 10, "block/title", Ds.String "Old"); Ds.Add (Ds.Entity_id 10, "block/page", Ds.Ref 1); Ds.Add (Ds.Entity_id 10, "block/parent", Ds.Ref 1); Ds.Add (Ds.Entity_id 10, "block/order", Ds.String "a0") ] + @ match child_title with + | None -> [] + | Some title -> + [ Ds.Add (Ds.Entity_id 1, "block/name", Ds.String "page"); + Ds.Add (Ds.Entity_id 11, "block/uuid", Ds.Uuid child); + Ds.Add (Ds.Entity_id 11, "block/title", Ds.String title); + Ds.Add (Ds.Entity_id 11, "block/page", Ds.Ref 1); + Ds.Add (Ds.Entity_id 11, "block/parent", Ds.Ref 1); + Ds.Add (Ds.Entity_id 11, "block/order", Ds.String "a1"); + Ds.Add (Ds.Entity_id 11, "block/created-at", Ds.Int64 1L); + Ds.Add (Ds.Entity_id 11, "block/updated-at", Ds.Int64 1L) ]) (Ds.empty_db ~schema:Graph_runtime_test.schema ~storage:(Graph_store.storage path) ()) in @@ -78,6 +89,54 @@ let save host id before after = state = Ops.Queued; intent = Ops.Save_title { uuid = block; expected_title = before; title = after } }) +let outliner_edits_keep_creation_time_and_sync_edit_time () = + List.iter (fun (initial_title, edited_title, event) -> + with_graph ~child_title:initial_title (fun dir _ host _ -> + let updated_at expected_title = + let db = Option.get (Mobile.projected_db host) in + check_eq (title db child) (Some expected_title); + let read attr = Graph_read.int_value + (Pending_projection.one_value db (Pending_projection.lookup child) attr) in + check_eq (read "block/created-at") (Some 1); + Option.get (read "block/updated-at") in + check_eq (updated_at initial_title) 1; + let session = Rpc_test.configure_plain_session (Rpc_session.create_session + { Rpc_session.default_options with + load_graph_catalog = Some (fun () -> Some Rpc_test.plain_graph_catalog); + sync_cursor = Some (fun () -> Mobile.sync_cursor host); + graph_db = Some (fun () -> Mobile.projected_db host); + graph_blocks = Some (fun () -> Mobile.blocks host); + graph_sidebar_pages = Some (fun () -> Mobile.sidebar_pages host); + graph_page_blocks = Some (Mobile.blocks_for_page host); + stage_operation = Some (Mobile.stage host); + prepare_operation = Some (Mobile.prepare_sync host); + pending_operations = Some (fun () -> Mobile.pending_operations host) }) in + ignore (Rpc_test.response_result (Rpc_test.dispatch_json session "selectPage" page)); + let tapped = Rpc_test.outliner_block_event session "tapBlock" child in + let member = Yojson.Basic.Util.member in + check_eq (member "uuid" (member "editing" (member "outlinerState" tapped))) (`String child); + ignore (Rpc_test.outliner_event session (Yojson.Basic.to_string (`Assoc + ["type", `String "textChanged"; "uuid", `String child; + "title", `String edited_title; "caretUTF16Offset", `Int (String.length edited_title)]))); + ignore (Rpc_test.outliner_event session (Printf.sprintf {|{"type":"%s"}|} event)); + let edited_at = updated_at edited_title in + check ~msg:event (edited_at > 1); + let edit = List.find (fun (op : Ops.pending_operation) -> + match op.intent with + | Ops.Save_title value -> value.uuid = child + | Ops.Split_block value -> value.uuid = child + | _ -> false) + (Mobile.pending_operations host) in + let _, wire = ok (Mobile.prepare_sync host edit) in + let open Dev_sync.Wire in + let datoms = Dev_sync.Sync_apply.normalize_tx_data_for_rebase (Dev_sync.Transit_codec.of_string wire) in + check ~msg:"pending transaction records the projected edit time" + (List.mem (Array [Keyword "db/add"; Array [Keyword "block/uuid"; Uuid child]; + Keyword "block/updated-at"; Int64 (Int64.of_int edited_at)]) datoms); + ok (Mobile.open_graph host (open_payload dir false)); + check_eq (updated_at edited_title) edited_at)) + [ "", "19:00", "saveEditing"; "19:00", "19:00 22:03", "returnPressed" ] + let journal_applies_canonical_rows_and_stable_refs () = with_graph (fun _ path host opened -> ok (Mobile.apply_sync_event host @@ -114,6 +173,38 @@ let overlay_replays_stored_datoms_and_survives_restart () = check (List.exists (fun (op : Ops.pending_operation) -> op.operation_id = "local") (Mobile.pending_operations host))) +let offline_edit_preserves_newer_remote_activity () = + with_graph ~child_title:"Old" (fun dir _ host _ -> + ok (Mobile.stage host + { Ops.operation_id = "local"; base_t = 42; state = Ops.Queued; + intent = Ops.Save_title { uuid = child; expected_title = "Old"; title = "Mine" } }); + let read db attr = + Pending_projection.one_value db (Pending_projection.lookup child) attr in + let projected () = Option.get (Mobile.projected_db host) in + let edited_at = Option.get (Graph_read.int_value (read (projected ()) "block/updated-at")) in + let remote_at = Int64.of_int (edited_at + 1) in + ok (Mobile.apply_sync_event host + (message 43 [ row 43 [ add (lookup child) "block/order" (V.String "a2"); + add (lookup child) "block/updated-at" (V.Int64 remote_at) ] ])); + let check_projection () = + let db = projected () in + check_eq (title db child) (Some "Mine"); + check_eq (read db "block/order") (Some (Ds.String "a2")); + check_eq (read db "block/updated-at") (Some (Ds.Int64 remote_at)) in + check_projection (); + ok (Mobile.open_graph host (open_payload dir false)); + check_projection (); + let pending = List.find (fun (op : Ops.pending_operation) -> op.operation_id = "local") + (Mobile.pending_operations host) in + let _, wire = ok (Mobile.prepare_sync host pending) in + let open Dev_sync.Wire in + let items = Dev_sync.Sync_apply.normalize_tx_data_for_rebase (Dev_sync.Transit_codec.of_string wire) in + check (List.mem (Array [Keyword "db/add"; Array [Keyword "block/uuid"; Uuid child]; + Keyword "block/title"; String "Mine"]) items); + check (not (List.exists (function + | Array (_ :: _ :: Keyword "block/updated-at" :: _) -> true + | _ -> false) items))) + let own_ack_keeps_server_corrections_and_only_confirms_named_tx () = with_graph (fun _ path host opened -> save host "first" "Old" "Mine"; @@ -261,7 +352,10 @@ let a_late_socket_frame_cannot_write_into_another_graph () = let cases = [ case "canonical journal rows and stable refs" journal_applies_canonical_rows_and_stable_refs; + case "outliner edits preserve creation time and sync edit time" + outliner_edits_keep_creation_time_and_sync_edit_time; case "stored overlay survives remote writes and restart" overlay_replays_stored_datoms_and_survives_restart; + case "offline edit preserves newer remote activity" offline_edit_preserves_newer_remote_activity; case "ACK applies corrections and confirms only named tx" own_ack_keeps_server_corrections_and_only_confirms_named_tx; case "malformed journal is atomic" malformed_journal_does_not_advance_or_partially_commit; case "missing ref does not consume journal" missing_journal_ref_fails_without_consuming_the_row;