Compare commits

..
Author SHA1 Message Date
Dennis Kobert c2845def11 Take rasterize's data input on the materialized leveled form 2026-09-08 20:19:18 +00:00
Dennis Kobert b8bd9499fc Pin the async source materialized input shape 2026-09-08 20:19:18 +00:00
Dennis Kobert e92ced1e4a Cross an async source's materialized input as an owned snapshot 2026-09-08 20:19:18 +00:00
Dennis Kobert e322d8957d Lift the run to owned legacy list bridge into core-types 2026-09-08 20:19:12 +00:00
Dennis Kobert 296185b7fc Register a record-io source whose generic sits on an implementations secondary 2026-09-08 15:23:33 +00:00
Dennis Kobert b321c094d2 Keep the new assert messages inside the format width 2026-09-08 13:29:09 +00:00
Dennis Kobert d4768d606f Justify the unsafe sites in the arena, record and graphic glue 2026-09-08 13:23:52 +00:00
Dennis Kobert 148008c695 Refuse a wasm threads build where the Send and Sync impls assume one thread 2026-09-08 13:15:18 +00:00
Dennis Kobert 2b5845464c Rederive the shared source pointer through an unwinding set_layout 2026-09-08 13:15:13 +00:00
Dennis Kobert 5e388cb38f Assert the deep element glue is registered before the executor evaluates 2026-09-08 13:15:06 +00:00
Dennis Kobert 49daf2895e Make Attribute an unsafe trait stating its re-park and glue coupling 2026-09-08 13:14:59 +00:00
Dennis Kobert 682d3dafbd Bound attribute value types Send and Sync 2026-09-08 13:14:59 +00:00
Dennis Kobert ad03b5b0bf Check a census row against the field before its writer runs 2026-09-08 13:14:33 +00:00
Dennis Kobert 324925aedb Debit the retained hint before the drop glue that may panic 2026-09-08 13:14:18 +00:00
Dennis Kobert e78a987e3e Bind a park forwarding to the destination arena generation 2026-09-08 13:14:12 +00:00
Dennis Kobert 2c8fa44eb4 Mint arena handles only over bytes the bump reserved 2026-09-08 13:14:12 +00:00
Dennis Kobert 6b22316077 Re-park a cross-arena adopt's payloads into the target arena 2026-09-08 13:11:04 +00:00
Dennis Kobert 98cabee4c6 Rebuild stale rasterize subgraphs at document migration 2026-09-08 12:53:02 +00:00
Dennis Kobert e0848abc59 Scan item attribute values for groups the ownership gates miss 2026-09-08 12:22:04 +00:00
Dennis Kobert f237a5ee50 Claim the carrier's frame before the lazy cursor snapshot 2026-09-08 12:22:04 +00:00
Dennis Kobert df99ab3a72 Guard attribute writes against an uninstalled layout offset 2026-09-07 16:12:01 +00:00
Dennis Kobert 0fc4424a09 State the disjointness a plan's copies require 2026-09-07 16:11:56 +00:00
Dennis Kobert e9a3199456 State what contains the laundered arena borrow in the flatten test 2026-09-07 16:11:32 +00:00
Dennis Kobert ef8312806d Serve the probe record the forwarding test finishes 2026-09-07 16:11:32 +00:00
Dennis Kobert 548cbfbf4e Check the claim's layout when replaying an owned record 2026-09-07 16:11:32 +00:00
Dennis Kobert 313c591f70 State from_resident's borrow-window contract at its call sites 2026-09-07 16:11:32 +00:00
Dennis Kobert f07f708ee8 Back the owned-item tests' lanes with word storage 2026-09-07 16:03:10 +00:00
Dennis Kobert 5f73044b6b Back the repark test's element slot with word storage 2026-09-07 16:03:10 +00:00
Dennis Kobert 11aedd8196 Refuse record layouts wider than the frame tier's alignment 2026-09-07 16:03:10 +00:00
Dennis Kobert f4f266b1ba Refuse a lift that never filled its layout's fields 2026-09-07 15:56:28 +00:00
Dennis Kobert 77e4e8c894 Bound and order the lanes a serve run records as filled 2026-09-07 15:51:08 +00:00
Dennis Kobert c231bd0eb8 Check the serve run's lane capacity arithmetic 2026-09-07 15:50:32 +00:00
Dennis Kobert 095e0bb4ff Require content glue for a group's element 2026-09-07 15:39:00 +00:00
Dennis Kobert 369f7db992 Copy records out untyped instead of through a byte slice 2026-09-07 15:38:53 +00:00
Dennis Kobert 79750fb52d Stage attribute default bytes through zeroed storage 2026-09-07 15:38:11 +00:00
Dennis Kobert f7360688f2 Point the construction docs at the registry that exists 2026-09-06 17:08:03 +00:00
Dennis Kobert 00920823aa Rewrite the node-graph README for the record and serving model 2026-09-06 16:58:45 +00:00
Dennis Kobert 0426a01e82 Rename the DynEdge alias to DynSource 2026-09-06 16:27:32 +00:00
Dennis Kobert 02f9cf3e6b Rename generic_record_edge_type to generic_record_source_type 2026-09-06 16:27:25 +00:00
Dennis Kobert 33f7257e47 Rename record_edge_type to record_source_type 2026-09-06 16:27:11 +00:00
Dennis Kobert 2921f44e5c Rename leveled_record_value_edge to leveled_record_value_source 2026-09-06 16:27:01 +00:00
Dennis Kobert 1e91511f93 Rename record_value_edge to record_value_source 2026-09-06 16:26:49 +00:00
Dennis Kobert daf0231c0c Rename the record_edge accessor to record_source 2026-09-06 16:26:33 +00:00
Dennis Kobert 92adc524ca Rename EdgeHandle to SourceHandle 2026-09-06 16:26:03 +00:00
Dennis Kobert 9f0e0ebc96 Clear the remaining clippy warnings on the diff surface 2026-09-06 16:25:17 +00:00
Dennis Kobert a911bcc165 Justify the three clippy lints that must stand 2026-09-06 16:24:53 +00:00
Dennis Kobert 5bedfa4d11 Name the erased repark and replay function types 2026-09-06 16:24:35 +00:00
Dennis Kobert e52af0cee0 Condense the multi-line safety notes to one line 2026-09-06 16:00:05 +00:00
Dennis Kobert fbdba0e545 Drop narration and internal asides from comments 2026-09-06 15:59:41 +00:00
Dennis Kobert 6cdab6b95d Drop docs naming mechanisms that do not exist 2026-09-06 15:58:40 +00:00
Dennis Kobert e92faf763d Correct docs that misstate what the code does 2026-09-06 15:58:01 +00:00
Dennis Kobert 305c36fb25 Reattach docs to the items they describe 2026-09-06 15:57:05 +00:00
Dennis Kobert fc9e69a7a7 Spell the elided Graphic and Artboard lifetimes in return paths 2026-09-06 15:48:45 +00:00
Dennis Kobert c9525d76c4 Give the split graphic modules their abstraction-level docs 2026-09-06 15:45:57 +00:00
Dennis Kobert 451922c217 Reattach the legacy mapping doc to its function 2026-09-06 15:29:03 +00:00
Dennis Kobert 92ea594a2a Split the graphic module into type, paint, walk, glue, and legacy modules 2026-09-06 15:29:03 +00:00
Dennis Kobert 9d3abe385f Sweep the data-flow wire and edge wording to input and source 2026-09-06 15:14:55 +00:00
Dennis Kobert 96521333d6 Rename SharedEdge to SharedSource 2026-09-06 15:13:57 +00:00
Dennis Kobert d80651e85c Rename ElementEdge to ElementInput 2026-09-06 15:13:32 +00:00
Dennis Kobert a16a4c6354 Rename RecordEdgeInput to RecordInput 2026-09-06 15:13:22 +00:00
Dennis Kobert d294d75198 Rename DerivedRecordEdge to DerivedRecordInput 2026-09-06 15:12:54 +00:00
Dennis Kobert 8f7d3936f8 Rename serve_edge to serve_input 2026-09-06 15:12:46 +00:00
Dennis Kobert 6961687172 Split the record module by abstraction level 2026-09-06 14:25:09 +00:00
Dennis Kobert 38d479bdfa Key the paint list park sites so a group-free paint moves 2026-09-05 13:12:17 +00:00
Dennis Kobert 14660bdb64 Key the element park path and its replay to the element type 2026-09-05 13:12:17 +00:00
Dennis Kobert b362452ff2 Guard arena moves by the park's static type instead of its size 2026-09-05 13:12:17 +00:00
Dennis Kobert 30573e6eb6 Condense the narrative comments to their constraints 2026-09-05 13:12:17 +00:00
Dennis Kobert 9ac039074d Scope the paint graphics import to the test that uses it 2026-09-05 13:11:45 +00:00
Dennis Kobert fdde760259 Drop the unread kernel field from the intent IR 2026-09-05 13:11:45 +00:00
Dennis Kobert 1be90ebb4a Delete the orphaned graphic accessor, introspection helper, and fn type macro 2026-09-05 13:11:45 +00:00
Dennis Kobert 8fa250a9f9 Delete the attribute helpers the refactor orphaned 2026-09-05 13:11:45 +00:00
Dennis Kobert 0b70b18338 Delete the unused record batch buffer accessors 2026-09-05 13:11:45 +00:00
Dennis Kobert 40efbc3261 Name the generic-carry predicate for what it now covers 2026-09-05 12:23:34 +00:00
Dennis Kobert 39ce55ab61 Convert rasterize to an async record source with an owned merged-layers write 2026-09-05 12:17:06 +00:00
Dennis Kobert 3e1a9a1acf Let an async source write an owned attribute through its claim 2026-09-05 11:58:02 +00:00
Dennis Kobert ab93e1f071 Add the owned attribute crossing over the deep field glue 2026-09-05 11:52:42 +00:00
Dennis Kobert aa50c42930 Measure the promoted paint list's retained heap 2026-09-02 08:26:26 +00:00
Dennis Kobert c73976f407 Refuse a mistyped park in the arena move 2026-09-02 08:26:26 +00:00
Dennis Kobert cac1c47b86 Cover the promoted paint field's sharing and move laws 2026-09-02 00:10:07 +00:00
Dennis Kobert 1426f6401f Route graphic-list field promotes straight into the persistent region 2026-09-02 00:10:07 +00:00
Dennis Kobert 6b951c1806 Add an opt-in promote half to the deep field glue 2026-09-02 00:09:46 +00:00
Dennis Kobert 1f860aae6a Move group-free graphic and artboard headers at the promote 2026-09-01 22:51:18 +00:00
Dennis Kobert e415714b04 Promote a leaf element by moving its header into the persistent region 2026-09-01 22:51:18 +00:00
Dennis Kobert a6016b2c03 Move a parked payload between arenas instead of cloning its heap 2026-09-01 22:51:18 +00:00
Dennis Kobert c12f8f1115 Add changing-seasons to the gungraun benchmark arguments 2026-09-01 13:18:01 +00:00
Dennis Kobert 4e7d72d4b8 Flush the persistent region on its heap budget 2026-08-31 23:52:44 +00:00
Dennis Kobert 41d42fe794 Delete the now unused frame table 2026-08-31 23:52:44 +00:00
Dennis Kobert 21dfe04bf8 Insert the boundary memo at context nullification 2026-08-31 23:52:34 +00:00
Dennis Kobert 0f26893ec1 Split the memo roles between the span memo and memoize 2026-08-31 23:52:34 +00:00
Dennis Kobert 0cd428f1b1 Share persistent graphic interiors when promoting 2026-08-31 23:52:21 +00:00
Dennis Kobert 39ed962e16 Promote memo levels by provenance 2026-08-31 23:52:21 +00:00
Dennis Kobert 6a5417ed3d Report an arena's occupancy and retained heap 2026-08-31 23:52:21 +00:00
Dennis Kobert 29052a58db Let async source kernels write attributes through their frame claim 2026-08-29 23:00:17 +00:00
Dennis Kobert 84d11b9285 Serve memo hits out of the persistent region 2026-08-29 22:07:27 +00:00
Dennis Kobert 5a6192bbd6 Give the executor a persistent arena flushed between evaluations 2026-08-29 22:07:27 +00:00
Dennis Kobert ca831c00db Promote a materialized batch into a target region 2026-08-29 22:07:27 +00:00
Dennis Kobert fe8ca88752 Name a persistent region on the evaluation scope 2026-08-29 22:07:27 +00:00
Dennis Kobert 8fd2529e27 Flag an arena whose reservation was refused 2026-08-29 22:07:27 +00:00
Dennis Kobert 641fcc88c6 Read declared attributes through one core-types helper 2026-08-29 20:16:17 +00:00
Dennis Kobert 78e35eb6ea Re-derive the shared edge pointer and type-check the paint transmute 2026-08-29 20:16:12 +00:00
Dennis Kobert 3302a3b0b8 Mint attribute reads through a layout-checked field token 2026-08-29 20:16:05 +00:00
Dennis Kobert 41d295f140 Tie a record view to the storage it points into 2026-08-29 20:14:44 +00:00
Dennis Kobert a955d6b458 Run cargo fmt 2026-08-29 18:40:02 +00:00
Dennis Kobert 97bc10e4c3 Pass frame space by argument and delete the record stack 2026-08-29 18:33:23 +00:00
Dennis Kobert 3af6834d3c Flip the Node trait from eval onto the frame claim's serve 2026-08-29 12:26:46 +00:00
Dennis Kobert 277641d27e Delete the plain edge kind 2026-08-29 10:07:10 +00:00
Dennis Kobert f3e945c5d8 Introduce the serve surface: the frame claim's proof-bearing lift on Node 2026-08-28 19:18:54 +00:00
Dennis Kobert aef750153b Claim the node frame once and close every exit through its drop 2026-08-28 19:11:38 +00:00
Dennis Kobert f4d37524c8 Structure record stack rewinds as scope guards and make reserve unsafe 2026-08-28 18:02:50 +00:00
Dennis Kobert e5b910f840 Adopt serving lifetimes and the safe record surfaces in the node crates 2026-08-28 13:30:06 +00:00
Dennis Kobert 25f49e8750 Give the graphic types the serving lifetime 2026-08-28 13:30:06 +00:00
Dennis Kobert 1ef7c9c2c2 Support author-named serving lifetimes in the node macro 2026-08-28 13:30:06 +00:00
Dennis Kobert f34ec257e7 Normalize lifetime arguments out of registry type names 2026-08-28 13:30:05 +00:00
Dennis Kobert 1e5b2c7f62 Serve group items at the evaluation lifetime 2026-08-28 13:30:05 +00:00
Dennis Kobert c6b669fc88 Key the element glue on static type projections 2026-08-28 13:30:05 +00:00
Dennis Kobert d814b610da Migrate test sources and assertions onto the safe record builders 2026-08-27 21:17:31 +00:00
Dennis Kobert 5181c74205 Add the frame builder and captured record reads 2026-08-27 21:17:31 +00:00
Dennis Kobert 4cb711e3f8 Stamp value types on layout fields and include type identity in layout equality 2026-08-27 21:17:31 +00:00
Dennis Kobert e8aea0728a Build native groups at the legacy conversion seams 2026-08-27 20:22:24 +00:00
Dennis Kobert 6f809fda73 Add the run builder and census-driven list adoption 2026-08-27 19:28:41 +00:00
Dennis Kobert ba84e2a968 De-table the graphic leaf variants 2026-08-27 18:55:32 +00:00
Dennis Kobert 72387d17ad Read the vector kernel seams natively 2026-08-27 15:57:10 +00:00
Dennis Kobert 048a4c4b70 Flatten boolean content natively 2026-08-27 15:45:36 +00:00
Dennis Kobert b262195549 Flatten vector rows natively and serve solidify per lane 2026-08-27 15:35:13 +00:00
Dennis Kobert 68a2fb2be3 Render root levels natively and remove the unconstructed stack form 2026-08-27 14:44:19 +00:00
Dennis Kobert 50911a6a25 Recreate introspection data from the monitor's context snapshot 2026-08-27 13:53:25 +00:00
Dennis Kobert 79f3571b02 Store paint content in its native form 2026-08-27 12:33:44 +00:00
Dennis Kobert 34ea9c59fd Deepen graphic-list field values at the persistence seams 2026-08-27 12:05:14 +00:00
Dennis Kobert 92ec2069ad Carry group content across memo seams in an owned form 2026-08-27 11:27:26 +00:00
Dennis Kobert 20e70e7bc9 Exclude executor teardown from the measured bench regions 2026-08-27 10:09:18 +00:00
Dennis Kobert 084f14e973 Resolve paint and transform columns once per lane loop 2026-08-26 23:03:17 +00:00
Dennis Kobert 694d3d34b3 Reduce measurement overhead for run_once benchmark 2026-08-27 00:37:25 +02:00
Dennis Kobert ed457093b1 Store artboard content as a native group 2026-08-26 21:50:36 +00:00
Dennis Kobert 7d44f6ec9e Collect a group element as its typed lowering 2026-08-26 21:50:35 +00:00
Dennis Kobert 54c140e4f3 Walk groups natively with lane paint threaded down 2026-08-26 19:43:32 +00:00
Dennis Kobert 5987c449b2 Serve bounding boxes through the lane source 2026-08-26 19:43:31 +00:00
Dennis Kobert c7605d12a6 Drive every render body from the lane source 2026-08-26 17:47:50 +00:00
Dennis Kobert d9533de9ea Look up paint through the paint markers instead of string keys 2026-08-26 17:47:38 +00:00
Dennis Kobert bc33e14c35 Read gradient columns per lane and drive color rendering from the lane source 2026-08-26 15:59:24 +00:00
Dennis Kobert 2b06d27729 Distinguish an absent column from a defaulted one on the lane source 2026-08-26 15:48:01 +00:00
Dennis Kobert b685ca77f2 Serve record runs through the lane source surface 2026-08-26 15:17:06 +00:00
Dennis Kobert e5b1fad675 Read render attributes through census markers instead of string keys 2026-08-26 14:55:27 +00:00
Dennis Kobert eb11eec5bb Store paint attributes in the paint markers' owned optional form 2026-08-26 14:02:01 +00:00
Dennis Kobert 182c2a1554 Cover the batch path that rebinds a lane-varying eager input 2026-08-25 21:15:12 +00:00
Dennis Kobert 913d7093ea Restore the index declaration on single-lane leveled values 2026-08-25 21:07:52 +00:00
Dennis Kobert 938fc1783a Treat a single-lane leveled value as invariant under the addressed lane 2026-08-25 20:27:39 +00:00
Dennis Kobert d452ac0de1 Hoist a batch input only where the compiler proves it cannot vary per lane 2026-08-25 20:09:12 +00:00
Dennis Kobert 95bbeb6634 Push the flat copy number Repeat on Points declares as its level extent 2026-08-25 17:15:00 +00:00
Dennis Kobert 5176bfd331 Query per-copy extents with the same chain shape the value path builds 2026-08-25 16:36:49 +00:00
Dennis Kobert db761cf8ed Drop a duplicated wasm import 2026-08-25 11:19:22 +00:00
Dennis Kobert 34e03038df Cargo fmt 2026-08-25 11:17:17 +00:00
Dennis Kobert bb3643541d Resolve context features from the registry at compile instead of persisting them 2026-08-25 11:16:56 +00:00
Dennis Kobert ff99f3605c Drop unread index bounds from fold kernels and mark re-addressing nodes ModifyIndex 2026-08-25 11:05:38 +00:00
Dennis Kobert 9cf037e992 Treat Modify bounds as transparent and drop the redundant fold-context validation 2026-08-25 11:04:57 +00:00
Dennis Kobert 888cdf17b0 Compress nullified index chains by dropping trailing zeroed levels 2026-08-25 11:04:57 +00:00
Dennis Kobert 9aef511891 Cargo fmt 2026-08-24 23:15:10 +02:00
Dennis Kobert 0d88e8be9f Inline status cell calls 2026-08-24 23:14:06 +02:00
Dennis Kobert 56d38b3f61 Re-save the demo artwork in its migrated form 2026-08-24 21:06:51 +00:00
Dennis Kobert a6c56c8655 Resolve index levels from the registry instead of persisting them 2026-08-24 20:40:51 +00:00
Dennis Kobert 2c84bb478f Derive pushed index levels per input and pop them when lifting requirements 2026-08-24 17:06:07 +00:00
Dennis Kobert 9cdaf06ca9 Count assign colors lanes without legacy conversion and cache the offsets 2026-08-24 17:06:07 +00:00
Dennis Kobert 027218f16c Declare which index levels a node reads and nullify the rest 2026-08-24 17:06:07 +00:00
Dennis Kobert f1ccb74625 Serve the monitored lane from its own capture materialization 2026-08-24 16:42:28 +00:00
Dennis Kobert cb5fabc6ad Add an env-gated arena allocation trace 2026-08-24 14:31:21 +00:00
Dennis Kobert 2448157af8 Close the memoize frame on a valueless materialization and trace node exits 2026-08-24 14:11:46 +00:00
Dennis Kobert d718cdb225 Keep the monitor's whole-extent capture off the record stack 2026-08-24 12:23:32 +00:00
Dennis Kobert dcc9059041 Give To Graphic a unit row so an unconnected content input renders as nothing 2026-08-24 12:02:46 +00:00
Dennis Kobert d70eae205d Quiet the clippy type-complexity and closure lints on the record kernels 2026-08-24 11:07:14 +00:00
Dennis Kobert ed6922d7eb Read the layer path in its owned form and retarget the introspection tests 2026-08-24 10:26:24 +00:00
Dennis Kobert abb099a1c3 Take brush on record wires and keep its legacy core behind brush_core 2026-08-24 09:27:52 +00:00
Dennis Kobert a4d01bfd11 Route the whole record through switch and drop its fifteen typed rows 2026-08-24 08:51:12 +00:00
Dennis Kobert d38c767312 Gather a chosen subject lane through a Lane output and convert pack_strips 2026-08-24 08:22:25 +00:00
Dennis Kobert aba941e81d Collapse typed levels in To Graphic like the pre-flip list conversion 2026-08-24 01:35:32 +00:00
Dennis Kobert 8c67ad508f Restore pre-flip color parity: rng replay, typed wrap, boolean marker paints 2026-08-24 00:43:44 +00:00
Dennis Kobert 9ca897963f Prune the unused legacy Adjust and Blend list implementations 2026-08-23 20:00:24 +00:00
Dennis Kobert 2575b94e8f Swap the leveled repeat_radial and repeat_on_points in for the eager variants 2026-08-23 19:50:36 +00:00
Dennis Kobert b03e4fb215 Let record nodes take element-consuming lazy inputs and convert map_points 2026-08-23 19:28:27 +00:00
Dennis Kobert c0eb2ee4ff Remove the runtime-named attribute family and its type-erased bridges 2026-08-23 19:05:26 +00:00
Dennis Kobert faa5c9d3db Install the resolved layout in the create_context test 2026-08-23 18:18:13 +00:00
Dennis Kobert bedb0d4159 Turn the byte-list wires into plain shared slices 2026-08-23 17:46:04 +00:00
Dennis Kobert 94b9d279a2 Retarget the palette executor test at the folded record wire 2026-08-23 17:29:43 +00:00
Dennis Kobert 7c4b029d76 Convert the math color and gradient family to element and marker kernels 2026-08-23 17:22:46 +00:00
Dennis Kobert 9ba3c16e79 Convert blur, median_filter, color_overlay, and image_color_palette to record kernels 2026-08-23 17:10:00 +00:00
Dennis Kobert 511b4da9f5 Convert the raster std and adjustments families to element kernels and keep the unit primary's slot 2026-08-23 16:52:43 +00:00
Dennis Kobert 2c15dc838e Convert dehaze, empty_image, extend_image_to_bounds, and image to record kernels 2026-08-23 10:11:34 +00:00
Dennis Kobert 73b2ef1d58 Convert cut_path, separate_subpaths, and path_is_closed to fold kernels 2026-08-23 09:56:09 +00:00
Dennis Kobert 9d2031f7d0 Convert the per-lane vector geometry nodes and the level measures to record kernels 2026-08-23 09:44:25 +00:00
Dennis Kobert 7b609ea781 Parse primitive defaults through record wire types 2026-08-23 08:39:35 +00:00
Dennis Kobert 5e918af371 Restore the sample_polyline test attribute and drop dead scaffolding 2026-08-23 08:31:40 +00:00
Dennis Kobert 6e9cac3b32 Trace record stack frames under an env gate 2026-08-23 08:31:39 +00:00
Dennis Kobert 893cbfe450 Close the frame on interrupt exits and rewind extent value queries 2026-08-23 08:31:39 +00:00
Dennis Kobert e40ee486a9 Claim the node frame on every cache serve and reclaim extracted edges 2026-08-23 08:31:39 +00:00
Dennis Kobert 58182bc2d3 Keep the executor arena at 128 MiB 2026-08-23 00:57:37 +00:00
Dennis Kobert 3fb8b10f80 Cache materialized spans per context and size emitter extents from the subject query 2026-08-23 00:57:37 +00:00
Dennis Kobert 6fe533a875 Cache whole levels in memoize and gate the monitor capture to lane zero 2026-08-23 00:57:37 +00:00
Dennis Kobert feea006fc3 Skip the consuming lane in the index reader 2026-08-23 00:57:37 +00:00
Dennis Kobert 73897111d0 Stop declaring derived index injection as a context feature 2026-08-23 00:57:37 +00:00
Dennis Kobert e76dcb15aa Convert mix and gradient value to element kernels 2026-08-22 22:15:03 +00:00
Dennis Kobert 538959ea90 Convert morph to a fold emitter 2026-08-22 22:15:03 +00:00
Dennis Kobert c33f8ae75b Convert mirror to a fold emitter and bridge levels into the erased list 2026-08-22 22:15:03 +00:00
Dennis Kobert 3126a5b278 Convert copy to points, sample polyline, scatter, spline, jitter, and assign colors 2026-08-22 20:59:37 +00:00
Dennis Kobert 5f6c18893e Grow the executor arena for per-copy paint parks 2026-08-22 20:59:37 +00:00
Dennis Kobert cdc6f11d92 Add an env-gated inferred type dump 2026-08-22 20:59:37 +00:00
Dennis Kobert c4b22c03b9 Size extent-path materialization by the total flat span 2026-08-22 20:59:37 +00:00
Dennis Kobert 6ab9d0360a Convert flatten path and solidify stroke to fold kernels 2026-08-22 19:11:48 +00:00
Dennis Kobert 01da817f61 Grow the executor arena for fold snapshots 2026-08-22 19:11:48 +00:00
Dennis Kobert 040bd71f82 Add an env-gated resolved layout depth dump 2026-08-22 19:11:48 +00:00
Dennis Kobert f2b0f7c533 Defer an empty side's inner extent in extend 2026-08-22 19:11:48 +00:00
Dennis Kobert a2918887f6 Collapse the whole subject wire in materialized folds 2026-08-22 19:11:48 +00:00
Dennis Kobert 7b993c5de6 Place lane paint onto the vector interiors at the legacy boundary 2026-08-22 17:29:51 +00:00
Dennis Kobert 3da7f6cea3 Drop the legacy fill and stroke rows for single-typed paint 2026-08-22 17:29:51 +00:00
Dennis Kobert 7569bdb9cb Convert path modify to a flip kernel over one default lane 2026-08-22 17:29:51 +00:00
Dennis Kobert 4e8a44650e Push the repeat array copies onto a derived level 2026-08-22 17:29:51 +00:00
Dennis Kobert b4346fd47d Convert the generators to element producers 2026-08-22 17:29:51 +00:00
Dennis Kobert e9a18a6437 Emit boolean results as elements with parked attributes 2026-08-22 17:29:51 +00:00
Dennis Kobert 77b0be5c15 Lift shallower sources in the layout union 2026-08-22 16:22:54 +00:00
Dennis Kobert 4bceae26f2 Add the leveled fill rows and the graphic coercion entries 2026-08-22 16:13:01 +00:00
Dennis Kobert c0f50d41d7 Drop the manual extent overrides in favor of the derivation 2026-08-22 15:55:49 +00:00
Dennis Kobert 0b2aa3798a Derive extent forwarding for level-preserving passthroughs 2026-08-22 15:34:22 +00:00
Dennis Kobert 13cd718c90 Drop an unused import 2026-08-22 15:02:01 +00:00
Dennis Kobert 39c7ba39cf Lift the artboard element onto a level and migrate demos for smoke tests 2026-08-22 15:01:27 +00:00
Dennis Kobert 6635e0aeff Convert the artboard constructor to an attribute kernel behind a footprint translate 2026-08-22 14:46:29 +00:00
Dennis Kobert 98dabd7ff5 Materialize the boolean operation's content level 2026-08-22 14:36:42 +00:00
Dennis Kobert a244cc13d0 Convert the blending family to attribute kernels 2026-08-22 14:32:15 +00:00
Dennis Kobert fb71ea426d Bridge legacy seams and convert the transform family 2026-08-22 14:25:31 +00:00
Dennis Kobert 217f32eb88 Type the list-typed value defaults by their element 2026-08-22 12:59:37 +00:00
Dennis Kobert 7fb36123e9 Point the render wrapper at the leveled intermediate 2026-08-22 12:50:47 +00:00
Dennis Kobert 46220ac268 Switch the tagged list values and layer internals onto leveled wires 2026-08-22 12:47:31 +00:00
Dennis Kobert 887dbaca2c Re-home the layer-path stamp and switch the node path to its plain value form 2026-08-22 12:35:48 +00:00
Dennis Kobert 44369cb12b Swap the repeat node to its leveled form in place 2026-08-22 12:29:16 +00:00
Dennis Kobert 56c772de4c Swap the map and index family nodes to their leveled forms in place 2026-08-22 12:27:53 +00:00
Dennis Kobert 93e34d00e5 Swap the graphic structural nodes to their leveled forms in place 2026-08-22 12:24:02 +00:00
Dennis Kobert 46f048b07c Add the leveled render intermediate beside the legacy rows 2026-08-22 12:15:08 +00:00
Dennis Kobert 4b130b4319 Map element-typed wires to their list forms' defaults and widgets 2026-08-22 11:48:27 +00:00
Dennis Kobert da0f70bb5f Stage the flip's document reset markers 2026-08-22 11:48:27 +00:00
Dennis Kobert 5821816228 Add the leveled boundary helpers and the deep group element copy 2026-08-22 11:48:26 +00:00
Dennis Kobert 8eaa541c8c Add the leveled value source and the dormant leveled edge form 2026-08-22 10:52:21 +00:00
Dennis Kobert e4adf16eba Move the paint and merged-layer markers to graphic-types as optional references 2026-08-22 10:23:02 +00:00
Dennis Kobert a8d257e7d6 Move the downstream-typed attribute markers to their value types' crates 2026-08-22 09:34:24 +00:00
Dennis Kobert 49c592013c Declare the core-typed attribute markers and re-export their names 2026-08-22 09:20:17 +00:00
Dennis Kobert 80db9c13c8 Signal past-end for repeat overruns so drains cross structure nodes 2026-08-21 22:17:06 +00:00
Dennis Kobert cf87796072 Probe lower-bound inner levels to their exact span 2026-08-21 22:17:06 +00:00
Dennis Kobert 8859e6b1a0 Add the layer-path stamp carrier 2026-08-21 22:03:31 +00:00
Dennis Kobert 1f23991a72 Add the editor layer path marker 2026-08-21 22:03:31 +00:00
Dennis Kobert 2be252d7b4 Fold a color level into evenly spaced gradient stops 2026-08-21 21:48:21 +00:00
Dennis Kobert 2c1acbdc62 Render groups through the legacy conversion 2026-08-21 20:36:06 +00:00
Dennis Kobert 61e751f278 Convert groups to their legacy list form 2026-08-21 20:36:06 +00:00
Dennis Kobert cdd62ed269 Retarget the wrap and flatten pilots onto group storage 2026-08-21 20:16:19 +00:00
Dennis Kobert f12094ced6 Add in-place group adoption for arena-resident batches 2026-08-21 20:16:19 +00:00
Dennis Kobert b5c4aa4598 Add the group variant to Graphic with typed run walks 2026-08-21 19:34:03 +00:00
Dennis Kobert da8ae2be43 Tag record layouts with their element type 2026-08-21 19:34:02 +00:00
Dennis Kobert 157c011953 Pick hashed element glue in the macro emissions 2026-08-21 18:21:38 +00:00
Dennis Kobert ae6807f8e3 Add content hashing and equality glue to record layouts 2026-08-21 18:21:38 +00:00
Dennis Kobert 17ba74485a Add arena-adopted group storage for nested records 2026-08-21 16:52:23 +00:00
Dennis Kobert 1f2eef5f8f Add the wrap collector beside the production node 2026-08-21 16:52:23 +00:00
Dennis Kobert 1b6513b954 Treat a free side as one lane in the extend split 2026-08-21 16:52:23 +00:00
Dennis Kobert 74fddff589 Add leveled vararg sources beside the production read nodes 2026-08-21 14:38:26 +00:00
Dennis Kobert 7e24f810c6 Register the map family for each production content type 2026-08-21 13:14:49 +00:00
Dennis Kobert 306cf1110f Emit one registry row per ranked implementation 2026-08-21 13:14:49 +00:00
Dennis Kobert b610eede20 Carry ranked element generics as struct parameters 2026-08-21 13:14:49 +00:00
Dennis Kobert 21f671555a Derive lower-bound extents for leveled outputs and drop the map extent fns 2026-08-21 12:37:57 +00:00
Dennis Kobert 951059aa3a Drain lower-bound reducer subjects by guess-and-double 2026-08-21 12:36:41 +00:00
Dennis Kobert e68254eff3 Carry an extent hint on batch returns 2026-08-21 12:32:57 +00:00
Dennis Kobert 61cf619f4b Add the lower-bound extent and the past-end signal 2026-08-21 12:22:09 +00:00
Dennis Kobert 7914a09d4b Carry only the element in the map vararg 2026-08-21 12:19:54 +00:00
Dennis Kobert 95e2cbca15 Test extend associativity and the batched fold across the seam 2026-08-21 09:18:45 +00:00
Dennis Kobert 724bb0fc17 Reject ragged inner extents in the extend concat 2026-08-21 09:18:37 +00:00
Dennis Kobert fb171cd5ac Test the partial fold keeping its subject's outer level 2026-08-19 21:43:14 +00:00
Dennis Kobert cb46be0430 Emit the reducer extent shift and the flat-span materialization 2026-08-19 21:43:14 +00:00
Dennis Kobert 7ffc9b9e3b Add the folded subject to LayoutMeta and derive reducer depth from it 2026-08-19 21:43:14 +00:00
Dennis Kobert 58a65c69e9 Add the map, flat_map, and flatten_levels pilots 2026-08-18 11:02:25 +00:00
Dennis Kobert d1d50ec469 Classify routing sources through IList nesting 2026-08-18 11:02:25 +00:00
Dennis Kobert e25e32ee8a Add the per-copy inner extent accessor 2026-08-18 11:02:25 +00:00
Dennis Kobert d560a39856 Add the flatten pilot over graphic content 2026-08-18 10:06:11 +00:00
Dennis Kobert 00e08359a3 Park droppable elements in the record tail store 2026-08-18 10:06:11 +00:00
Dennis Kobert 116ce622d4 Test batch lane equivalence and single eager bind per batch 2026-08-18 08:53:38 +00:00
Dennis Kobert 082fb5d959 Hoist non-lazy inputs in the default batch implementation 2026-08-18 08:53:38 +00:00
Dennis Kobert 043f28cc23 Add StatusCell snapshot, List copy, and interrupt-to-batch conversion 2026-08-18 08:53:38 +00:00
Dennis Kobert b7413dd22c Add the replaced context derivation for same-level remaps 2026-08-17 14:47:41 +00:00
Dennis Kobert 586737247e Fold nested list levels flat in a single kernel 2026-08-17 14:47:24 +00:00
Dennis Kobert 055b7f0055 Add the rank-model mirror over a materialized level 2026-08-17 14:47:24 +00:00
Dennis Kobert 4a042bade2 Key materialization on declared list nesting and carriers on non-materialized subjects 2026-08-17 14:46:48 +00:00
Dennis Kobert 3aa018a15c Add the rank-model read-by-index family: omit, index elements, extract element 2026-08-17 11:59:40 +00:00
Dennis Kobert 8508dc6c9d Add the rank-model extend concatenating two sources at the top level 2026-08-17 11:42:52 +00:00
Dennis Kobert fbba0cd037 Gate the gpu converter imports the sweep wrongly removed 2026-08-17 10:56:45 +00:00
Dennis Kobert ae7c51a964 Drop stale imports left behind by the record-wire port 2026-08-17 10:28:29 +00:00
Dennis Kobert 0c49026c9a Error on out-of-range copy addressing instead of wrapping in the repeat family 2026-08-17 10:28:28 +00:00
Dennis Kobert bc29166d4c Add the rank-model repeat on points flattening every points row 2026-08-17 09:26:59 +00:00
Dennis Kobert 0f3e3f7337 Materialize ranked non-subject inputs whole and expose them to extent overrides 2026-08-17 09:26:59 +00:00
Dennis Kobert a03db0ac6c Decompose the flat index over the content extent in structure creators 2026-08-17 08:09:27 +00:00
Dennis Kobert 932ed8653e Add the rank-model repeat radial rotating each copy around the center 2026-08-16 18:17:30 +00:00
Dennis Kobert 5ab3f067fe Add the rank-model repeat array over a lazy transform-reading carrier 2026-08-16 17:47:25 +00:00
Dennis Kobert 3df028cb18 Wire record-io plain values as record edges in the registry, extracted at construction 2026-08-16 17:47:25 +00:00
Dennis Kobert e423dd96de Support lazy record carriers so a creator can read and rewrite attrs per copy 2026-08-16 17:13:19 +00:00
Dennis Kobert bef58bf395 Give the generic repeat its production shape with reverse in the index mapping 2026-08-16 17:13:19 +00:00
Dennis Kobert 131abf5883 Give extent overrides a typed input surface instead of the raw node form 2026-08-16 15:55:17 +00:00
Dennis Kobert 3859bd713e Install element layouts on the runtime test graphs 2026-08-16 11:29:20 +00:00
Dennis Kobert ac40f1838f Store record batches in caller-owned frame buffers instead of aliased stack pointers 2026-08-16 11:29:20 +00:00
Dennis Kobert 9055a5f3d5 Drop the stale layout unwraps in the math wire tests 2026-08-16 11:28:33 +00:00
Dennis Kobert d32caeab52 Add a generic lazy repeat that evaluates its content at each copy index 2026-08-16 11:28:11 +00:00
Dennis Kobert 15f4aa8f98 Strip IList nesting from kernel returns at parse time 2026-08-16 11:27:13 +00:00
Dennis Kobert 99ce2ea565 Require a node registry to compile so the layout pass always runs 2026-08-15 14:49:25 +00:00
Dennis Kobert 87200f3c2a Gate a flipped shader node's layout metadata out of the GPU build 2026-08-15 14:49:19 +00:00
Dennis Kobert 214632c5ec Reserve the record stack before direct edge evals in executor tests 2026-08-15 12:27:39 +00:00
Dennis Kobert 64fb4eda61 Fold the record-stack peak in the layout pass, not the executor 2026-08-15 12:20:52 +00:00
Dennis Kobert f9e30c4c77 Install record layouts from the pass via set_layout 2026-08-15 11:20:01 +00:00
Dennis Kobert bfa48439c8 Resolve coercion nodes and dynamic values in the layout pass 2026-08-15 08:48:29 +00:00
Dennis Kobert a717403db8 Diagnose a materializing node's missing InjectIndex and Copy bounds 2026-08-14 21:31:14 +00:00
Dennis Kobert fdf13f91cb Materialize a reducer's ranked input into a List and fold it 2026-08-14 21:19:20 +00:00
Dennis Kobert 65e0969721 Recognize a reducer's IList input level in build 2026-08-14 10:13:53 +00:00
Dennis Kobert 8f265e7660 Report a creator's pushed-level extent from its count 2026-08-14 09:56:31 +00:00
Dennis Kobert 98e6b97072 Reshape the extent trait to a written extent_at and a derived composite 2026-08-14 09:10:04 +00:00
Dennis Kobert a3e9074955 Scatter a creator's per-copy attribute from the copy index 2026-08-14 08:24:44 +00:00
Dennis Kobert 04afada5b3 Lower a creator's IList return to a level-pushing record 2026-08-14 08:22:29 +00:00
Dennis Kobert 3e183fbd28 Read a creator's IList return level in build 2026-08-14 08:11:59 +00:00
Dennis Kobert 849d6a17be Delete the Class taxonomy in favor of the intent IR 2026-08-13 23:46:07 +00:00
Dennis Kobert 20ba069fe0 Derive record-io construction wiring from the intent IR 2026-08-13 23:26:22 +00:00
Dennis Kobert c82093f153 Derive codegen node-kind predicates from the intent IR 2026-08-13 23:09:48 +00:00
Dennis Kobert 010785d8db Derive single-row registry entries from the intent IR 2026-08-13 22:08:04 +00:00
Dennis Kobert 69774d445c Derive the eval tail from the intent IR 2026-08-13 21:08:41 +00:00
Dennis Kobert b42c632474 Derive input bindings from the intent IR 2026-08-13 19:32:25 +00:00
Dennis Kobert f195e363a5 Emit layout metadata from the intent IR 2026-08-13 16:11:58 +00:00
Dennis Kobert 40f99152ce Bridge-verify build against the resolved class 2026-08-13 15:35:07 +00:00
Dennis Kobert 3b1170b148 Derive inputs, output, and monomorphizations in build 2026-08-13 15:18:35 +00:00
Dennis Kobert 3a20091d3a Derive the node-level intent axes in build 2026-08-13 14:19:49 +00:00
Dennis Kobert e5206c3b50 Add the node intent IR types 2026-08-13 14:00:15 +00:00
Dennis Kobert fbc736e1cc Verify computed layouts match construction at node construction 2026-08-13 10:25:00 +00:00
Dennis Kobert d7da2ba9e7 Add the resolve_types and compute_layouts compiler passes 2026-08-13 10:24:59 +00:00
Dennis Kobert a5784c8f0b Port the create_context render test onto record wires 2026-08-12 13:11:48 +00:00
Dennis Kobert 83fbaca6f2 Unify the layout metadata model and collapse the single-row entry emitters 2026-08-12 13:11:48 +00:00
Dennis Kobert b6f73b0691 Emit declarative LayoutMeta from the node macro into registry entries 2026-08-11 20:08:45 +00:00
Dennis Kobert 557f8020bb Add the leveled extent_at/depth trait surface and the push_level context helper 2026-08-11 20:08:45 +00:00
Dennis Kobert fb94d99807 Port the stale math-nodes and raster-nodes tests onto record wires 2026-08-11 09:54:48 +00:00
Dennis Kobert 264601c5f7 Return records from eval_batch through a RecordBatch view 2026-08-11 09:26:36 +00:00
Dennis Kobert 5db7e1816a Make Node::layout non-optional, defaulting to a shared empty layout 2026-08-11 09:20:02 +00:00
Dennis Kobert 5b02edfd9a Split the node macro codegen into classify, entries, and metadata modules 2026-08-10 16:15:31 +00:00
Dennis Kobert 7c0a4073e9 Select the eval tail form by class and dialect through an explicit Tail step 2026-08-10 15:57:58 +00:00
Dennis Kobert 275100eab0 Model the eval body as an EvalStep sequence with a structural stack discipline 2026-08-10 15:34:12 +00:00
Dennis Kobert 42cd2a4303 Resolve the dialect and input-role axes as node-model sum types 2026-08-10 15:21:59 +00:00
Dennis Kobert e4f81fc947 Drive the node macro from a single analyze pass, NodePlan, and shared NodeFields 2026-08-10 13:33:58 +00:00
Dennis Kobert 492cf18cb0 Flip the passthrough node onto record wires by dropping its dead lifetime 2026-08-10 13:33:58 +00:00
Dennis Kobert 05630bab6e Port the repeat node tests onto record-wire lazy inputs 2026-08-10 10:41:40 +00:00
Dennis Kobert a465948ad4 Always-spill records, retiring inline-16 and reclaiming read-out record frames 2026-08-10 10:29:22 +00:00
Dennis Kobert 63cf0151e2 Change stack return to standart sret semantics 2026-08-08 07:33:33 +00:00
Dennis Kobert 9c7a633d5b Adopt tuple attribute io and the carrier lowering, deleting the bridge adapters for record-only wires 2026-08-06 18:48:16 +00:00
Dennis Kobert 166241b0e8 Flip nested-generic nodes onto record wires by unifying row types against field types 2026-08-06 13:36:46 +00:00
Dennis Kobert ea49f3c2fc Delete the Ref wire type and its lend edge surface 2026-08-06 12:24:50 +00:00
Dennis Kobert 100f81c307 Retire the lend machinery and flip the clone node onto record wires 2026-08-06 11:57:18 +00:00
Dennis Kobert 886ff03ef2 Construct value nodes as native record sources 2026-08-06 10:24:44 +00:00
Dennis Kobert 7a1d1f3238 Define the frame memo through the record-opaque class over same-frame byte copies 2026-08-06 09:57:21 +00:00
Dennis Kobert 612afb7ebb Capture the input context snapshot on the monitor io record 2026-08-06 09:37:48 +00:00
Dennis Kobert daf3f25d21 Define the monitor through the record-opaque class and move introspection to element reads 2026-08-06 09:07:57 +00:00
Dennis Kobert a2de2a9c09 Add the record-opaque kernel class to the node macro and define memoize through it 2026-08-06 08:28:52 +00:00
Dennis Kobert 98be2b8c79 Carry erased element and re-park glue on layouts and collapse memoize to a generic record row 2026-08-06 08:01:19 +00:00
Dennis Kobert 83fda4f08c Update the core-types runtime tests to record wires 2026-08-06 06:46:28 +00:00
Dennis Kobert 20c6ba19d3 Flip async source nodes onto record wires by lifting their slot values 2026-08-05 23:54:42 +00:00
Dennis Kobert 7eeb7d84cd Flip poll kernels and derived-context lazy nodes onto record wires and land record roots at the host rim 2026-08-05 23:42:24 +00:00
Dennis Kobert 7ddc66adbe Flip lazy-input nodes onto record wires through the element lazy input 2026-08-05 23:12:43 +00:00
Dennis Kobert c20a243fc2 Flip lend-parameter nodes onto record wires and keep the clone adapter plain 2026-08-05 22:57:51 +00:00
Dennis Kobert 3eecc31bfd Flip generic value nodes onto record wires through phantom struct parameters 2026-08-05 22:39:25 +00:00
Dennis Kobert 7099f056dc Flip concrete value nodes onto record wires with bridge rows for every value type 2026-08-05 22:18:50 +00:00
Dennis Kobert 9680d34abf Carry record elements by the drop-glue rule and unify the lift and extract adapters 2026-08-05 22:17:50 +00:00
Dennis Kobert 592b2fbe32 Turn context modification into a generic record routing node and park droppable elements as arena references 2026-08-05 19:25:17 +00:00
Dennis Kobert 60f80682c5 Collapse duplicate proto nodes when assigning stable ids 2026-08-05 19:25:17 +00:00
Dennis Kobert 9fc4fcc7a0 Inline records of at most 16 bytes into the two-word RecordValue with layout-resolved storage 2026-08-05 17:23:09 +00:00
Dennis Kobert 7915800d73 Add per-field erased-read glue, the record monitor with introspection capture, and rename record constructors to new 2026-08-05 15:22:20 +00:00
Dennis Kobert c91be74a55 Add the Record wire type, record registry rows, lift and extract adapters, and executor stack reservation 2026-08-05 12:24:20 +00:00
Dennis Kobert abe2a565d1 Drop the list driver, make attribute values Copy over arena references, and land record-tier offset io on a per-thread record stack 2026-08-05 09:47:03 +00:00
Dennis Kobert 6154e4d219 Add the attribute census, node macro attribute io over list wires, and the rank-0 record tier 2026-08-04 22:05:02 +00:00
Dennis Kobert 62b7ccf40c Support bare reference parameters and lending outputs in the node macro and make the clone node the clone-out adapter 2026-08-03 18:29:16 +00:00
Dennis Kobert 9b45af854a Emit Ref wire types for lending rows and splice lend/clone_out adapters in the type checker 2026-08-03 16:33:27 +00:00
Dennis Kobert 562e6602eb Poll source tasks once at spawn and land inline completions in the first eval 2026-08-03 10:21:46 +00:00
Dennis Kobert 8fb18012cf Remove unuse allow dead code 2026-08-02 19:35:43 +02:00
Dennis Kobert 2b3161773f Propagate tokio runtime creation failure in graphene-cli 2026-08-02 19:29:33 +02:00
Dennis Kobert 167d733f02 Wire the async source runtimes into the hosts 2026-08-02 19:24:51 +02:00
Dennis Kobert ee499be31f Add test coverage for the repeat nodes 2026-08-02 16:18:07 +00:00
Dennis Kobert d385f3c69b Fix warnings 2026-08-02 15:06:11 +00:00
Dennis Kobert e372f78b7e Address pr review 2026-08-02 14:31:13 +00:00
Dennis Kobert 8686b2c891 Export the async-source flag from the macro and dispatch superseded type deltas in tests 2026-08-02 14:09:27 +00:00
Dennis Kobert e3aa32bc83 Fix wireing of async sources 2026-08-02 14:02:53 +02:00
Dennis Kobert 77d439ec35 Silence the dead-code warnings for groundwork the host wiring will use 2026-08-01 00:59:26 +02:00
Dennis Kobert c30054579f Adapt the cutover to the reviewed core-types API 2026-07-31 23:39:39 +02:00
Dennis Kobert 81a319430b Cut over to the graphene execution model 2026-07-31 23:19:42 +02:00
Dennis Kobert 1fb6fcb447 Remove the unused CtxSnapshot scope reconstruction 2026-07-31 22:55:53 +02:00
Dennis Kobert 32d244e700 Make the sources fields private and normalize them on every mutation 2026-07-31 22:00:22 +02:00
Dennis Kobert 0877f9d50e Park the arena during drop glue, guard filled batches, and normalize deserialized sources 2026-07-31 20:09:46 +02:00
Dennis Kobert 14c1dd0397 Guard the shared generation counter in tests and reject oversized batch ranges 2026-07-31 19:30:59 +02:00
Dennis Kobert daf7b3e7b9 Make arena generation exhaustion fallible with an unsafe counter rewind 2026-07-31 19:08:09 +02:00
Dennis Kobert bdf53070f2 Forward serialize through node wrappers and free abandoned frame table reservations 2026-07-31 18:12:53 +02:00
Dennis Kobert 0d0ec96709 Draw arena generations from a global counter so foreign handles never upgrade 2026-07-31 17:48:09 +02:00
Dennis Kobert 6feaf4ec9d Drop arena entries in reverse allocation order and require Send + Sync payloads 2026-07-31 17:21:11 +02:00
Dennis Kobert 5541769dc5 Fix frame table key aliasing and arena handle offset truncation 2026-07-31 16:46:20 +02:00
Dennis Kobert 1fccb112cb Add the core execution types, the borrowed context, and the seeded u64 fx hasher 2026-07-31 13:11:36 +00:00
Timon eb50be844b Remove now obsolete disable-registration special case from node macro (#4375) 2026-07-25 13:54:46 +00:00
Dennis Kobert 0f0f62c2e9 Enforce unwind safety on all public executor entry points (#4356) 2026-07-24 09:34:40 +00:00
Timon f5b1fee85f Fix node insertion crash caused by mismatched DefinitionIdentifier serialization (#4353) 2026-07-22 09:38:07 +00:00
Timon 6f8c4b2adb Desktop: Stop compiling the editor into the wasm wrapper (#4348)
* Make wasm wrapper not depend on editor on native

* Introduce pkg-native

* Fix tests

* Fix fmt

* Correct span and make cargo fmt work inside editor_commands block

* Review

* Fix lint
2026-07-18 10:33:38 +00:00
632 changed files with 58004 additions and 79794 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/6687dc6d3d8552948458d00d35e2bee3a40ab66b.tar.gz
7663b4a35f377a5d3363430a725a1d5f634fbdc56adca5e43167786b8fe1b253
https://github.com/Keavon/graphite-branded-assets/archive/0d004aa61e6b48d316e8e5db6d59ccc4788f192d.tar.gz
772d64518be43c99977ba56f69e574531c56e83d2df2f42ab066f77f74b0dd1f
+4 -20
View File
@@ -2,25 +2,11 @@
"image": "mcr.microsoft.com/devcontainers/base:debian",
"features": {
"ghcr.io/devcontainers/features/rust:1": {
"profile": "default",
"targets": "wasm32-unknown-unknown"
"profile": "default"
},
"ghcr.io/devcontainers/features/node:1": {
// NOTICE: keep in sync with `.nvmrc`
"version": "24"
}
},
// NOTICE: keep these tool versions in sync with `.github/workflows/build.yml`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
"containerEnv": {
"WASM_BINDGEN_CLI_VERSION": "0.2.121",
"CARGO_ABOUT_VERSION": "0.9.2",
"BINARYEN_VERSION": "130",
"CARGO_BINSTALL_VERSION": "1.23.0"
},
"onCreateCommand": {
"Install cargo-about and wasm-bindgen-cli": "curl -sSfL https://github.com/cargo-bins/cargo-binstall/releases/download/v$CARGO_BINSTALL_VERSION/cargo-binstall-$(uname -m)-unknown-linux-musl.tgz | tar xz -C $CARGO_HOME/bin && BINSTALL_DISABLE_TELEMETRY=true cargo binstall --no-confirm cargo-about@$CARGO_ABOUT_VERSION wasm-bindgen-cli@$WASM_BINDGEN_CLI_VERSION",
"Install Binaryen wasm-opt": "curl -sSfL https://github.com/WebAssembly/binaryen/releases/download/version_$BINARYEN_VERSION/binaryen-version_$BINARYEN_VERSION-$(uname -m)-linux.tar.gz | tar xz -C $CARGO_HOME/bin --strip-components=2 binaryen-version_$BINARYEN_VERSION/bin/wasm-opt"
"ghcr.io/devcontainers/features/node:1": {}
},
"onCreateCommand": "cargo install cargo-about && cargo install -f [email protected]",
"customizations": {
"vscode": {
// NOTE: Keep this in sync with `.vscode/extensions.json`
@@ -30,16 +16,14 @@
"tamasfe.even-better-toml",
// Web
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"svelte.svelte-vscode",
"vitaliymaz.vscode-svg-previewer",
// Code quality
"wayou.vscode-todo-highlight",
"streetsidesoftware.code-spell-checker",
// Git
// Helpful
"mhutchie.git-graph",
"qezhu.gitlink",
// Helpful
"wmaurer.change-case"
]
}
-34
View File
@@ -1,34 +0,0 @@
# Keavon Chambers (@Keavon [email protected])
# Dennis Kobert (@TrueDoctor [email protected])
/document/format/ @TrueDoctor
/node-graph/graph-craft/ @TrueDoctor
/node-graph/preprocessor/ @TrueDoctor
/node-graph/node-macro/ @TrueDoctor
/node-graph/interpreted-executor/ @TrueDoctor
/node-graph/graphene-cli/ @TrueDoctor
# Timon Schelling (@timon-schelling [email protected])
/.nix/ @timon-schelling
/flake.nix @timon-schelling
/flake.lock @timon-schelling
/desktop/ @timon-schelling
/editor/src/messages/future/ @timon-schelling
/editor/src/messages/resource_storage/ @timon-schelling
/editor/src/messages/network/ @timon-schelling
/editor/src/messages/app_window/ @timon-schelling
/editor/src/messages/clipboard/ @timon-schelling
/editor/src/messages/viewport/ @timon-schelling
/libraries/wgpu-sync/ @timon-schelling
/node-graph/libraries/canvas-utils/ @timon-schelling
/tools/cargo-run/ @timon-schelling
/tools/third-party-licenses/ @timon-schelling
+10 -24
View File
@@ -58,7 +58,6 @@ jobs:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
SCCACHE_DIR: /var/lib/github-actions/.cache
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
steps:
@@ -303,11 +302,9 @@ jobs:
pull-requests: write
env:
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
CARGO_ABOUT_VERSION: "0.9.0"
steps:
- name: 📥 Clone repository
@@ -344,9 +341,7 @@ jobs:
frontend/package-lock.json
- name: 📦 Install Cargo-binstall
uses: cargo-bins/cargo-binstall@v1.23.0
with:
version: ${{ env.CARGO_BINSTALL_VERSION }}
uses: cargo-bins/cargo-binstall@main
- name: 🚧 Install native dependencies
shell: pwsh
@@ -502,11 +497,9 @@ jobs:
pull-requests: write
env:
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.121"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
CARGO_ABOUT_VERSION: "0.9.0"
steps:
- name: 📥 Clone repository
@@ -542,11 +535,6 @@ jobs:
package-lock.json
frontend/package-lock.json
- name: 📦 Install Cargo-binstall
uses: cargo-bins/[email protected]
with:
version: ${{ env.CARGO_BINSTALL_VERSION }}
- name: 🚧 Install native dependencies
env:
GITHUB_TOKEN: ${{ github.token }}
@@ -556,7 +544,8 @@ jobs:
brew install \
pkg-config \
openssl@3 \
llvm
llvm \
cargo-binstall
echo "OPENSSL_DIR=$(brew --prefix openssl@3)" >> $GITHUB_ENV
echo "PKG_CONFIG_PATH=$(brew --prefix openssl@3)/lib/pkgconfig" >> $GITHUB_ENV
@@ -661,20 +650,17 @@ jobs:
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper.app"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (GPU).app"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Graphite Helper (Renderer).app"
find "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries" -name "*.dylib" -exec codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" {} \;
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libcef_sandbox.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libEGL.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libGLESv2.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH/Contents/Frameworks/Chromium Embedded Framework.framework/Libraries/libvk_swiftshader.dylib"
codesign --force --options runtime --entitlements "$ENTITLEMENTS" --sign "$CERTIFICATE" "$APP_PATH" --deep
codesign --verify --deep --strict --verbose=4 "$APP_PATH"
ditto -c -k --keepParent "$APP_PATH" "$ZIP_PATH"
SUBMISSION_ID=$(xcrun notarytool submit "$ZIP_PATH" --wait --output-format json --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD" | tee /dev/stderr | jq -r '.id')
STATUS=$(xcrun notarytool info "$SUBMISSION_ID" --output-format json --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD" | jq -r '.status')
if [ "$STATUS" != "Accepted" ]; then
echo "Notarization failed with status: $STATUS"
xcrun notarytool log "$SUBMISSION_ID" --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD"
exit 1
fi
xcrun notarytool submit "$ZIP_PATH" --wait --apple-id "$APPLE_EMAIL" --team-id "$APPLE_TEAM_ID" --password "$APPLE_PASSWORD"
rm "$ZIP_PATH"
xcrun stapler staple -v "$APP_PATH"
-1
View File
@@ -13,4 +13,3 @@ flamegraph.svg
.direnv
.DS_Store
.nvim.lua
/.devcontainer/devcontainer-lock.json
+12 -14
View File
@@ -1,10 +1,10 @@
{ pkgs, ... }:
let
version = "151.3.24+g2384915+chromium-151.0.7922.174";
version = "149.0.5+g6770623+chromium-149.0.7827.197";
hashes = {
aarch64-linux = "sha256-R5ZbnDallYvdbW/bP+M2DzjRfWWRTvY2q63hSIHNxZs=";
x86_64-linux = "sha256-21PEP9rOi37krw8AUSARbWlzqp2Ot3AsBhe635voaE4=";
aarch64-linux = "sha256-cBAvcvs1rAg5EKJkCt81RZYupCWpUNIC/nLt3PJow7Q=";
x86_64-linux = "sha256-OPGMBJmvvLiLdBDniBQwx7LmTGGI59AcesJdILSeqcs=";
};
selectSystem =
@@ -12,19 +12,17 @@ let
attrs.${pkgs.stdenv.hostPlatform.system}
or (throw "Unsupported system ${pkgs.stdenv.hostPlatform.system}");
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
selectSystem {
aarch64-linux = "linuxarm64";
x86_64-linux = "linux64";
}
}_minimal.tar.bz2";
src = pkgs.fetchurl {
inherit url;
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
selectSystem {
aarch64-linux = "linuxarm64";
x86_64-linux = "linux64";
}
}_minimal.tar.bz2";
hash = selectSystem hashes;
};
in
pkgs.cef-binary.overrideAttrs {
pkgs.cef-binary.overrideAttrs (finalAttrs: {
version = builtins.head (builtins.split "\\+" version);
inherit src;
postInstall = ''
@@ -40,9 +38,9 @@ pkgs.cef-binary.overrideAttrs {
echo '${
builtins.toJSON {
type = "minimal";
name = builtins.baseNameOf url;
name = builtins.baseNameOf finalAttrs.src.url;
sha1 = "";
}
}' > $out/archive.json
'';
}
})
-1
View File
@@ -6,7 +6,6 @@
"tamasfe.even-better-toml",
// Web
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"svelte.svelte-vscode",
"vitaliymaz.vscode-svg-previewer",
// Code quality
Generated
+470 -2099
View File
File diff suppressed because it is too large. Load diff
+11 -27
View File
@@ -11,13 +11,10 @@ members = [
"document/format",
"document/graph-storage",
"document/container",
"document/peer-transport",
"document/live",
"editor",
"frontend/wrapper",
"libraries/dyn-any",
"libraries/math-parser",
"libraries/ipsum",
"libraries/wgpu-sync",
"node-graph/libraries/graphene-hash",
"node-graph/libraries/*",
@@ -43,7 +40,6 @@ default-members = [
"frontend/wrapper",
"libraries/dyn-any",
"libraries/math-parser",
"libraries/ipsum",
"node-graph/graph-craft",
"node-graph/interpreted-executor",
"node-graph/node-macro",
@@ -60,7 +56,7 @@ edition = "2024"
authors = ["Graphite Authors <[email protected]>"]
homepage = "https://graphite.art"
repository = "https://github.com/GraphiteEditor/Graphite"
license = "MIT OR Apache-2.0"
license = "Apache-2.0"
version = "0.0.0"
readme = "README.md"
publish = false
@@ -84,7 +80,6 @@ no-std-types = { path = "node-graph/libraries/no-std-types" }
raster-types = { path = "node-graph/libraries/raster-types" }
vector-types = { path = "node-graph/libraries/vector-types" }
graphic-types = { path = "node-graph/libraries/graphic-types" }
brush-types = { path = "node-graph/libraries/brush-types" }
rendering = { path = "node-graph/libraries/rendering" }
brush-nodes = { path = "node-graph/nodes/brush" }
blending-nodes = { path = "node-graph/nodes/blending" }
@@ -100,8 +95,6 @@ graph-craft = { path = "node-graph/graph-craft" }
document-format = { path = "document/format" }
document-graph-storage = { path = "document/graph-storage", default-features = false }
document-container = { path = "document/container" }
peer-transport = { path = "document/peer-transport" }
document-live = { path = "document/live" }
raster-nodes = { path = "node-graph/nodes/raster" }
graphene-std = { path = "node-graph/nodes/gstd" }
interpreted-executor = { path = "node-graph/interpreted-executor" }
@@ -111,7 +104,6 @@ wgpu-sync = { path = "libraries/wgpu-sync" }
graphite-proc-macros = { path = "proc-macros" }
graphite-editor = { path = "editor" }
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
ipsum = { path = "libraries/ipsum" }
# Workspace dependencies
rustc-hash = "2.0"
@@ -147,7 +139,7 @@ wgpu = { version = "29.0", features = [
"strict_asserts",
] }
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned across CI workflows, devcontainer, Nix, and the `cargo-run` tool. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen-futures = "0.4"
js-sys = "=0.3.98"
web-sys = { version = "=0.3.98", features = [
@@ -168,17 +160,16 @@ web-sys = { version = "=0.3.98", features = [
"HtmlImageElement",
"ImageBitmapRenderingContext",
] }
winit = "0.31.0-beta.2"
winit = { git = "https://github.com/rust-windowing/winit.git" }
keyboard-types = "0.8"
url = "2.5"
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
# Linebender ecosystem (BEGIN)
kurbo = { version = "0.13", features = ["serde"] }
vello = "0.10"
vello_encoding = "0.10"
vello = "0.9"
vello_encoding = "0.9"
resvg = "0.47"
usvg = "0.47"
simplecss = "0.2"
parley = { version = "0.9", default-features = false, features = ["std"] }
skrifa = "0.42"
polycool = "0.4"
@@ -199,13 +190,6 @@ image = { version = "0.25", default-features = false, features = [
"jpeg",
"bmp",
"gif",
"webp",
"tiff",
"ico",
"tga",
"hdr",
"exr",
"serde",
] }
pretty_assertions = "1.4"
fern = { version = "0.7", features = ["colored"] }
@@ -225,7 +209,6 @@ syn = { version = "2.0", default-features = false, features = [
"proc-macro",
] }
lyon_geom = "1.0"
delaunator = "1.0"
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
tinyvec = { version = "1", features = ["std"] }
@@ -234,8 +217,8 @@ gungraun = { version = "0.18" }
ndarray = "0.16"
strum = { version = "0.27", features = ["derive"] }
dirs = "6.0"
cef = "151"
cef-dll-sys = "151"
cef = "149"
cef-dll-sys = "149"
include_dir = "0.7"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing = "0.1"
@@ -274,7 +257,8 @@ lto = "thin"
debug = true
[patch.crates-io]
winit = { git = "https://github.com/timon-schelling/winit", branch = "graphite" }
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
dpi = { git = "https://github.com/rust-windowing/winit.git" }
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
-19
View File
@@ -1,19 +0,0 @@
Copyright (c) Graphite contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
View File
File renamed without changes.
+1 -3
View File
@@ -80,6 +80,4 @@ Graphite is 100% community built and funded. Please become a part of keeping the
Are you a graphics programmer or Rust developer? Graphite aims to be one of the most approachable projects for putting your engineering skills to use in the world of open source. See [instructions here](https://graphite.art/volunteer/guide/) for setting up the project and getting started.
## License
Graphite's source code is dual-licensed under your choice of either the [MIT license](LICENSE-MIT) or the [Apache License 2.0](LICENSE-APACHE), at your option, unless otherwise noted within the repository. By submitting code for inclusion in the project, you agree to license your contributions under both licenses, and that you have the authority to do so.
*By submitting code for inclusion in the project, you are agreeing to license your changes under the Apache 2.0 license, and that you have the authority to do so. Some directories may have other licenses, like dual-licensed MIT/Apache 2.0, and code submissions to those directories mean you agree to the applicable license(s).*
+2 -1
View File
@@ -18,11 +18,12 @@ accepted = [
"NCSA", # Keep this list in sync with those in `/deny.toml`
"bzip2-1.0.6", # Keep this list in sync with those in `/deny.toml`
"OFL-1.1", # Keep this list in sync with those in `/deny.toml`
"Unlicense", # Keep this list in sync with those in `/deny.toml`
]
workarounds = ["ring"]
ignore-build-dependencies = true
ignore-dev-dependencies = true
# Clearly Defined's API would occasionally (every few months) return errors for at least a full day (maybe some weird rate limiting?), but we can just disable to perform local checking (see #1653)
no-clearly-defined = true
# https://raw.githubusercontent.com/briansmith/webpki/main/LICENSE
# is the ISC license but test code within the repo is BSD-3-Clause, but is not compiled into the crate when we use it
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.9822506,"green":0.2050787Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"impleLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"I64":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"I64":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_vaLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5],"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[4388711862172196665,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":"","sources":[]}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"ValueLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Node":{"node_id":6,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[2,{"inputs":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":null},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0]]},"regions":{"add":[],"remove":[],"segLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Gradient":{"position":[0.0,1.0],"midpoint":[0.5,0.5],"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}]}},"exposed":false}},{"Value":{"tagged_value":{"GradientType":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"GradientSpreadMethod":"Pad"},"exposed":false}},{"Value":{"tagged_value":{"OptionalDAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implemeLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ToGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WrapGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"INDEX","inject":"","sources":[]}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"INDEX","inject":"","sources":[]}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":"","sources":[]}}],[76,{"inputs":[{"Node":{"node_id":77,"output_index":0}},{"Node":{"node_id":16164610528699022118,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodesLine truncated
-1
View File
@@ -82,7 +82,6 @@ allow = [
"NCSA", # Keep this list in sync with those in `/about.toml`
"bzip2-1.0.6", # Keep this list in sync with those in `/about.toml`
"OFL-1.1", # Keep this list in sync with those in `/about.toml`
"Unlicense", # Keep this list in sync with those in `/about.toml`
]
# The confidence threshold for detecting a license from license text.
# The higher the value, the more closely the license text must be to the
+7 -7
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop"
version = "0.1.0"
description = "Graphite Desktop"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
[[bin]]
name = "graphite"
@@ -44,12 +44,12 @@ rfd = { workspace = true }
open = { workspace = true }
lzma-rust2 = { workspace = true }
serde = { workspace = true }
url = { workspace = true }
rand = { workspace = true, features = ["thread_rng"] }
clap = { workspace = true, features = ["derive"] }
interprocess = "2.4.2"
fd-lock = "4.0.4"
ctrlc = "3.5.1"
window_clipboard = "0.5"
# Windows-specific dependencies
[target.'cfg(target_os = "windows")'.dependencies]
+6 -6
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop-bundle"
version = "0.0.0"
description = "Graphite Desktop Bundle"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
[dependencies]
cef-dll-sys = { workspace = true }
+6 -6
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop-embedded-resources"
version = "0.1.0"
description = "Graphite Desktop Embedded Resources"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
[dependencies]
include_dir = { workspace = true }
+6 -6
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop-platform-linux"
version = "0.0.0"
description = "Graphite Desktop Platform Linux"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
[[bin]]
name = "graphite"
+6 -6
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop-platform-mac"
version = "0.0.0"
description = "Graphite Desktop Platform Mac"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
[features]
main = ["dep:graphite-desktop"]
+6 -6
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop-platform-win"
version = "0.0.0"
description = "Graphite Desktop Platform Windows"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
[[bin]]
name = "graphite"
+95 -133
View File
@@ -9,22 +9,19 @@ use std::sync::mpsc::{Receiver, SyncSender};
use std::thread;
use std::time::{Duration, Instant};
use winit::application::ApplicationHandler;
use winit::data_transfer::{DataTransferSendBuilder, TypeHint};
use winit::dpi::PhysicalSize;
use winit::event::{ElementState, MouseButton, StartCause, WindowEvent};
use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand;
use winit::event_loop::{ActiveEventLoop, AsyncRequestSerial, ControlFlow, DndAction, EventLoop};
use winit::dpi::{PhysicalPosition, PhysicalSize};
use winit::event::{ButtonSource, ElementState, MouseButton, StartCause, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::WindowId;
use crate::dirs;
use crate::event::{AppEvent, AppEventScheduler};
use crate::input::InputState;
use crate::persist;
use crate::preferences;
use crate::render::{RenderError, RenderState};
use crate::ui::{InputEvent, UiCommand, UiInstance};
use crate::ui::{UiCommand, UiInstance};
use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
pub(crate) struct App {
@@ -36,9 +33,8 @@ pub(crate) struct App {
window_maximized: bool,
window_fullscreen: bool,
window_pending_drag: bool,
pending_dnd_fetch: Option<AsyncRequestSerial>,
pending_clipboard_fetch: Option<AsyncRequestSerial>,
input_state: InputState,
pointer_position: PhysicalPosition<f64>,
pointer_lock_position: Option<PhysicalPosition<f64>>,
ui_scale: f64,
app_event_receiver: Receiver<AppEvent>,
app_event_scheduler: AppEventScheduler,
@@ -101,6 +97,11 @@ impl App {
});
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
let completion_render_sender = start_render_sender.clone();
DesktopWrapper::set_completion_notifier(move || {
let _ = completion_render_sender.try_send(());
});
Self {
render_state: None,
wgpu_context,
@@ -110,9 +111,8 @@ impl App {
window_maximized: false,
window_fullscreen: false,
window_pending_drag: false,
pending_dnd_fetch: None,
pending_clipboard_fetch: None,
input_state: InputState::new(),
pointer_position: Default::default(),
pointer_lock_position: Default::default(),
ui_scale: 1.,
app_event_receiver,
app_event_scheduler,
@@ -130,8 +130,8 @@ impl App {
}
}
pub(crate) fn run(mut self, mut event_loop: EventLoop) -> ExitReason {
event_loop.run_app_on_demand(&mut self).unwrap();
pub(crate) fn run(mut self, event_loop: EventLoop) -> ExitReason {
event_loop.run_app(&mut self).unwrap();
self.exit_reason
}
@@ -205,15 +205,15 @@ impl App {
};
self.send_or_queue_web_message(bytes);
}
DesktopFrontendMessage::OpenFileDialog { title, options, action } => {
DesktopFrontendMessage::OpenFileDialog { title, filters, multiple, context } => {
let app_event_scheduler = self.app_event_scheduler.clone();
let _ = thread::spawn(move || {
let mut dialog = AsyncFileDialog::new().set_title(title);
for filter in options.filters {
for filter in filters {
dialog = dialog.add_filter(filter.name, &filter.extensions);
}
let handles = if options.multiple {
let handles = if multiple {
futures::executor::block_on(dialog.pick_files()).unwrap_or_default()
} else {
futures::executor::block_on(dialog.pick_file()).into_iter().collect()
@@ -223,8 +223,7 @@ impl App {
let path = handle.path().to_path_buf();
match fs::read(&path) {
Ok(content) => {
let action = action.clone();
let message = DesktopWrapperMessage::IngestFile { path, content, action };
let message = DesktopWrapperMessage::FileDialogResult { path, content, context };
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
Err(e) => tracing::error!("Failed to read file {}: {}", path.display(), e),
@@ -270,8 +269,6 @@ impl App {
});
}
DesktopFrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height } => {
self.input_state.set_viewport_info(x, y, width, height, self.window_scale);
if let Some(render_state) = &mut self.render_state
&& let Some(window) = &self.window
{
@@ -286,9 +283,6 @@ impl App {
render_state.set_viewport_scale([viewport_scale_x as f32, viewport_scale_y as f32]);
}
}
DesktopFrontendMessage::WindowUpdateDirectInput { enabled } => {
self.input_state.set_direct_input(enabled);
}
DesktopFrontendMessage::UpdateUIScale { scale } => {
self.ui_scale = scale;
self.resize();
@@ -341,13 +335,19 @@ impl App {
}
}
DesktopFrontendMessage::ClipboardRead => {
self.app_event_scheduler.schedule(AppEvent::ClipboardRead);
if let Some(window) = &self.window {
let content = window.clipboard_read();
let message = DesktopWrapperMessage::ClipboardReadResult { content };
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
}
DesktopFrontendMessage::ClipboardWrite { content } => {
self.app_event_scheduler.schedule(AppEvent::ClipboardWrite { content });
if let Some(window) = &mut self.window {
window.clipboard_write(content);
}
}
DesktopFrontendMessage::PointerLock => {
self.input_state.lock_pointer();
self.pointer_lock_position = Some(self.pointer_position);
if let Some(window) = &self.window {
window.start_pointer_lock();
}
@@ -467,32 +467,6 @@ impl App {
self.ui_frame_received = true;
}
}
AppEvent::ClipboardRead => {
let result = event_loop.clipboard().and_then(|id| {
let Some(id) = id else { return Ok(None) };
let data_transfer = event_loop.data_transfer(id)?;
if !data_transfer.has_type(&TypeHint::Plaintext) {
return Ok(None);
}
event_loop.fetch_data_transfer(id, &TypeHint::Plaintext).map(Some)
});
match result {
Ok(Some(serial)) => self.pending_clipboard_fetch = Some(serial),
Ok(None) => self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::ClipboardReadResult { content: None }),
Err(e) => {
tracing::error!("Failed to read from clipboard: {e}");
self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::ClipboardReadResult { content: None });
}
}
}
AppEvent::ClipboardWrite { content } => {
let send_data = DataTransferSendBuilder::new(content)
.with_type(TypeHint::Plaintext, |content: &String, _| Some(content.clone()))
.build();
if let Err(e) = event_loop.set_clipboard(send_data) {
tracing::error!("Failed to write to clipboard: {e}");
}
}
AppEvent::CursorChange(cursor) => {
if let Some(window) = &mut self.window {
window.set_cursor(event_loop, cursor);
@@ -521,11 +495,7 @@ impl App {
for path in paths {
tracing::info!("Opening file: {}", path.display());
if let Ok(content) = fs::read(&path) {
let message = DesktopWrapperMessage::IngestFile {
path,
content,
action: IngestAction::Open,
};
let message = DesktopWrapperMessage::OpenFile { path, content };
app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
} else {
tracing::error!("Failed to read file: {}", path.display());
@@ -568,28 +538,28 @@ impl ApplicationHandler for App {
}
}
fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
fn window_event(&mut self, _event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
// Handle pointer lock release
if let WindowEvent::PointerButton {
state: ElementState::Released,
button,
..
} = &event && button.clone().mouse_button() == Some(MouseButton::Left)
&& let Some(pointer_lock_position) = self.input_state.unlock_pointer()
if let Some(pointer_lock_position) = self.pointer_lock_position
&& let WindowEvent::PointerButton {
state: ElementState::Released,
button: ButtonSource::Mouse(MouseButton::Left),
..
} = event
{
self.pointer_lock_position = None;
if let Some(window) = &self.window {
window.end_pointer_lock();
}
self.ui.send(UiCommand::Input(
InputEvent::pointer().position(pointer_lock_position).moved().modifiers(self.input_state.modifiers()).build(),
));
self.ui.send(UiCommand::Input(WindowEvent::PointerMoved {
device_id: None,
position: pointer_lock_position,
primary: true,
source: winit::event::PointerSource::Mouse,
}));
}
self.input_state.process(
&event,
|message| self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Input(message))),
|input| self.ui.send(UiCommand::Input(input)),
);
self.ui.send(UiCommand::Input(event.clone()));
match event {
WindowEvent::CloseRequested => {
@@ -631,73 +601,65 @@ impl ApplicationHandler for App {
self.exit(Some(ExitReason::UiAccelerationFailure));
}
}
WindowEvent::DragEntered { id, .. } => {
let accepts = event_loop.data_transfer(id).is_ok_and(|data_transfer| data_transfer.has_type(&TypeHint::UriList));
let actions: &[DndAction] = if accepts { &[DndAction::Copy] } else { &[] };
if let Err(e) = event_loop.set_valid_dnd_actions(id, actions) {
tracing::error!("Failed to set valid drag and drop actions: {e}");
WindowEvent::DragDropped { paths, .. } => {
for path in paths {
match fs::read(&path) {
Ok(content) => {
let message = DesktopWrapperMessage::ImportFile { path, content };
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
Err(e) => {
tracing::error!("Failed to read dropped file {}: {}", path.display(), e);
return;
}
};
}
}
WindowEvent::DragDropped { id, .. } => match event_loop.fetch_data_transfer(id, &TypeHint::UriList) {
Ok(serial) => self.pending_dnd_fetch = Some(serial),
Err(e) => tracing::error!("Failed to fetch dropped data: {e}"),
},
WindowEvent::DataTransferReceived { serial, ref value, .. } if self.pending_clipboard_fetch == Some(serial) => match value.try_as_string() {
Ok(content) => {
self.pending_clipboard_fetch = None;
let message = DesktopWrapperMessage::ClipboardReadResult { content: Some(content) };
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
Err(e) => {
self.pending_clipboard_fetch = None;
tracing::error!("Failed to read from clipboard: {e}");
let message = DesktopWrapperMessage::ClipboardReadResult { content: None };
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
},
WindowEvent::DataTransferReceived { serial, ref value, .. } if self.pending_dnd_fetch == Some(serial) => match value.try_as_uris() {
Ok(uris) => {
self.pending_dnd_fetch = None;
let paths = uris.iter().filter_map(|uri| url::Url::parse(uri).ok()?.to_file_path().ok());
for path in paths {
match fs::read(&path) {
Ok(content) => {
let message = DesktopWrapperMessage::IngestFile {
path,
content,
action: IngestAction::Import,
};
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
Err(e) => {
tracing::error!("Failed to read dropped file {}: {}", path.display(), e);
return;
}
};
}
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
Err(e) => {
self.pending_dnd_fetch = None;
tracing::error!("Failed to read dropped data: {e}");
}
},
WindowEvent::PointerMoved { .. } | WindowEvent::PointerLeft { position: Some(_), .. } | WindowEvent::PointerEntered { .. }
if !self.input_state.pointer_locked() && self.window_pending_drag =>
// Forward and Back buttons are not supported by CEF and thus need to be directly forwarded the editor
WindowEvent::PointerButton {
button: ButtonSource::Mouse(button),
state: ElementState::Pressed,
..
} => {
let mouse_keys = match button {
MouseButton::Back => Some(MouseKeys::BACK),
MouseButton::Forward => Some(MouseKeys::FORWARD),
_ => None,
};
if let Some(mouse_keys) = mouse_keys {
let message = DesktopWrapperMessage::Input(InputMessage::PointerDown {
editor_mouse_state: MouseState { mouse_keys, ..Default::default() },
modifier_keys: Default::default(),
});
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
let message = DesktopWrapperMessage::Input(InputMessage::PointerUp {
editor_mouse_state: Default::default(),
modifier_keys: Default::default(),
});
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
}
WindowEvent::PointerMoved { position, .. } | WindowEvent::PointerLeft { position: Some(position), .. } | WindowEvent::PointerEntered { position, .. }
if self.pointer_lock_position.is_none() =>
{
self.window_pending_drag = false;
if let Some(window) = &self.window {
window.start_drag();
self.pointer_position = position;
if self.window_pending_drag {
self.window_pending_drag = false;
if let Some(window) = &self.window {
window.start_drag();
}
}
}
WindowEvent::PointerButton {
button,
button: ButtonSource::Mouse(MouseButton::Left),
state: ElementState::Released,
..
} if button.clone().mouse_button() == Some(MouseButton::Left) => {
} => {
self.window_pending_drag = false;
}
@@ -706,7 +668,7 @@ impl ApplicationHandler for App {
}
fn device_event(&mut self, _event_loop: &dyn ActiveEventLoop, _device_id: Option<winit::event::DeviceId>, event: winit::event::DeviceEvent) {
if self.input_state.pointer_locked()
if self.pointer_lock_position.is_some()
&& let winit::event::DeviceEvent::PointerMotion { delta: (x, y) } = event
{
let message = DesktopWrapperMessage::PointerLockMove { x, y };
+4 -4
View File
@@ -20,10 +20,10 @@ pub(crate) fn clear_dir(path: &PathBuf) {
if let Err(e) = fs::remove_dir_all(&entry_path) {
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
}
} else if entry_path.is_file()
&& let Err(e) = fs::remove_file(&entry_path)
{
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
} else if entry_path.is_file() {
if let Err(e) = fs::remove_file(&entry_path) {
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
}
}
}
}
-4
View File
@@ -8,10 +8,6 @@ pub(crate) enum AppEvent {
WebCommunicationInitialized,
DesktopWrapperMessage(DesktopWrapperMessage),
NodeGraphExecutionResult(NodeGraphExecutionResult),
ClipboardRead,
ClipboardWrite {
content: String,
},
Exit,
UiCrashed,
OpenFiles(Vec<std::path::PathBuf>),
-455
View File
@@ -1,455 +0,0 @@
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use winit::dpi::PhysicalPosition;
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, PointerSource, TabletToolData, TabletToolKind, WindowEvent};
use winit::keyboard::ModifiersState;
use crate::ui::{InputEvent, MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
use crate::wrapper::messages::{EditorPointerState, InputMessage, ModifierKeys, MouseKeys, ScrollDelta};
// Marks input event as observe-only, meaning it should not result in any input messages being send by the frontend.
// And should instead be ignored by frontend input processing and only be used to update the UI state (hover, cursor).
// TODO(Timon): Remove and find a less hacky solution
trait ObserveOnlyExt {
fn observe_only(self) -> Self;
}
impl ObserveOnlyExt for crate::ui::InputEventBuilder {
fn observe_only(self) -> Self {
self.num_lock(true)
}
}
pub(crate) struct InputState {
start: Instant,
viewport_info: Option<ViewportInfo>,
direct_input: bool,
modifiers: ModifiersState,
pointer_position: PhysicalPosition<f64>,
pointer_state: PointerState,
click_tracker: ClickTracker,
shake_tracker: ShakeTracker,
}
impl InputState {
pub(crate) fn new() -> Self {
Self {
start: Instant::now(),
viewport_info: None,
direct_input: false,
modifiers: ModifiersState::default(),
pointer_position: PhysicalPosition::default(),
pointer_state: PointerState::Hover { route: Route::Ui },
click_tracker: ClickTracker::default(),
shake_tracker: ShakeTracker::default(),
}
}
pub(crate) fn set_viewport_info(&mut self, x: f64, y: f64, width: f64, height: f64, scale: f64) {
self.viewport_info = Some(ViewportInfo { x, y, width, height, scale });
}
pub(crate) fn set_direct_input(&mut self, enabled: bool) {
self.direct_input = enabled;
}
pub(crate) fn lock_pointer(&mut self) {
self.pointer_state = match self.pointer_state {
PointerState::Hover { route } => PointerState::Locked {
route,
keys: MouseKeys::empty(),
position: self.pointer_position,
},
PointerState::Stroke { route, keys } | PointerState::Locked { route, keys, .. } => PointerState::Locked {
route,
keys,
position: self.pointer_position,
},
};
}
pub(crate) fn unlock_pointer(&mut self) -> Option<PhysicalPosition<f64>> {
let PointerState::Locked {
route: resume,
keys,
position: restore,
} = self.pointer_state
else {
return None;
};
self.pointer_position = restore;
self.pointer_state = match keys.is_empty() {
true => PointerState::Hover { route: Route::Ui },
false => PointerState::Stroke { route: resume, keys },
};
Some(restore)
}
pub(crate) fn pointer_locked(&self) -> bool {
matches!(self.pointer_state, PointerState::Locked { .. })
}
pub(crate) fn modifiers(&self) -> ModifiersState {
self.modifiers
}
pub(crate) fn process(&mut self, event: &WindowEvent, mut editor_callback: impl FnMut(InputMessage), mut ui_callback: impl FnMut(InputEvent)) {
match event {
WindowEvent::PointerMoved { position, source, .. } => {
self.pointer_position = *position;
let route = match self.pointer_state {
PointerState::Hover { .. } => {
let next = self.route(*position);
self.pointer_state = PointerState::Hover { route: next };
next
}
PointerState::Stroke { route, .. } => route,
PointerState::Locked { keys, route: resume, .. } => match keys.is_empty() {
true => Route::Ui,
false => resume,
},
};
match route {
Route::Ui => ui_callback(InputEvent::pointer().position(*position).moved().modifiers(self.modifiers).build()),
Route::Editor => {
if !self.pointer_locked() {
ui_callback(InputEvent::pointer().position(*position).moved().modifiers(self.modifiers).observe_only().build());
}
let editor_mouse_state = match source {
PointerSource::TabletTool { kind, data } => self.tablet_pointer_state(kind, data),
_ => self.pointer_state(),
};
let modifier_keys = self.modifier_keys();
if self.shake_tracker.detect(*position, self.start.elapsed()) {
editor_callback(InputMessage::PointerShake { editor_mouse_state, modifier_keys });
}
editor_callback(InputMessage::PointerMove { editor_mouse_state, modifier_keys });
}
}
}
WindowEvent::PointerEntered { position, .. } => {
self.pointer_position = *position;
ui_callback(InputEvent::pointer().position(*position).entered().modifiers(self.modifiers).build())
}
WindowEvent::PointerLeft { position: Some(position), .. } => {
self.pointer_position = *position;
ui_callback(InputEvent::pointer().position(*position).exited().modifiers(self.modifiers).build())
}
WindowEvent::PointerLeft { position: None, .. } => ui_callback(InputEvent::pointer().exited().modifiers(self.modifiers).build()),
WindowEvent::PointerButton { state, button, position, .. } => {
self.pointer_position = *position;
let mouse_button = button.clone().mouse_button();
let keys = match mouse_button {
Some(MouseButton::Left) => MouseKeys::LEFT,
Some(MouseButton::Right) => MouseKeys::RIGHT,
Some(MouseButton::Middle) => MouseKeys::MIDDLE,
Some(MouseButton::Back) => MouseKeys::BACK,
Some(MouseButton::Forward) => MouseKeys::FORWARD,
_ => MouseKeys::NONE,
};
let (pointer, route) = match self.pointer_state {
PointerState::Hover { route } => match (state.is_pressed(), keys.is_empty()) {
(true, false) => {
let route = self.route(*position);
(PointerState::Stroke { route, keys }, route)
}
(true, true) => (PointerState::Hover { route }, self.route(*position)),
(false, _) => (PointerState::Hover { route }, route),
},
PointerState::Stroke { route, keys: mut held } => {
match state.is_pressed() {
true => held.insert(keys),
false => held.remove(keys),
}
match held.is_empty() {
true => (PointerState::Hover { route }, route),
false => (PointerState::Stroke { route, keys: held }, route),
}
}
PointerState::Locked { route, keys: mut held, position } => {
let resume = if state.is_pressed() && held.is_empty() { Route::Ui } else { route };
match state.is_pressed() {
true => held.insert(keys),
false => held.remove(keys),
}
(PointerState::Locked { route: resume, keys: held, position }, Route::Ui)
}
};
self.pointer_state = pointer;
let count = mouse_button.map_or(1, |button| self.click_tracker.input(*position, button, *state));
let back_or_forward = matches!(mouse_button, Some(MouseButton::Back | MouseButton::Forward));
let pointer = InputEvent::pointer().position(*position);
let input = match state {
ElementState::Pressed => pointer.pressed(button.clone(), count),
ElementState::Released => pointer.released(button.clone(), count),
}
.modifiers(self.modifiers);
if self.pointer_locked() || keys.is_empty() || !(back_or_forward || route == Route::Editor) {
ui_callback(input.build());
return;
}
if route == Route::Editor {
ui_callback(input.observe_only().build());
}
let editor_mouse_state = match button {
ButtonSource::TabletTool { kind, data, .. } => self.tablet_pointer_state(kind, data),
_ => self.pointer_state(),
};
let modifier_keys = self.modifier_keys();
match state {
ElementState::Pressed => editor_callback(InputMessage::PointerDown { editor_mouse_state, modifier_keys }),
ElementState::Released if count % 2 == 0 => {
editor_callback(InputMessage::PointerUp { editor_mouse_state, modifier_keys });
editor_callback(InputMessage::DoubleClick {
editor_mouse_state: EditorPointerState {
mouse_keys: keys,
..editor_mouse_state
},
modifier_keys,
});
}
ElementState::Released => editor_callback(InputMessage::PointerUp { editor_mouse_state, modifier_keys }),
}
}
WindowEvent::MouseWheel { delta, .. } => {
if self.pointer_locked() || self.ui_captures(self.pointer_position) {
let input = match delta {
MouseScrollDelta::LineDelta(x, y) => InputEvent::pointer().scrolled_lines(f64::from(*x), f64::from(*y)),
MouseScrollDelta::PixelDelta(position) => InputEvent::pointer().scrolled_pixels(position.x, position.y),
_ => return,
};
ui_callback(input.modifiers(self.modifiers).build());
return;
}
let (x, y) = match delta {
MouseScrollDelta::LineDelta(x, y) => (f64::from(*x) * SCROLL_LINE_WIDTH, f64::from(*y) * SCROLL_LINE_HEIGHT),
MouseScrollDelta::PixelDelta(position) => (position.x, position.y),
_ => return,
};
let scroll_delta = ScrollDelta::new(-x * SCROLL_SPEED_X, -y * SCROLL_SPEED_Y, 0.);
editor_callback(InputMessage::WheelScroll {
editor_mouse_state: EditorPointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys(),
});
}
WindowEvent::PinchGesture { delta, .. } => {
if self.pointer_locked() || self.ui_captures(self.pointer_position) || !delta.is_normal() {
ui_callback(InputEvent::pointer().zoomed(*delta).modifiers(self.modifiers).build());
return;
}
// TODO: This is a temporary solution to handle pinch gestures, we should handle pinch gestures editor-side instead.
let scroll_delta = ScrollDelta::new(0., -delta * PINCH_ZOOM_SPEED, 0.);
editor_callback(InputMessage::WheelScroll {
editor_mouse_state: EditorPointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys() | ModifierKeys::CONTROL,
});
}
WindowEvent::ModifiersChanged(modifiers) => {
self.modifiers = modifiers.state();
}
WindowEvent::KeyboardInput { event, .. } => ui_callback(InputEvent::key(event).modifiers(self.modifiers).build()),
_ => {}
}
}
fn scale(&self) -> f64 {
self.viewport_info.as_ref().map_or(1., |info| info.scale)
}
fn ui_captures(&self, position: PhysicalPosition<f64>) -> bool {
!self.direct_input || !self.viewport_info.as_ref().is_some_and(|info| info.contains(position))
}
fn route(&self, position: PhysicalPosition<f64>) -> Route {
if self.ui_captures(position) { Route::Ui } else { Route::Editor }
}
fn pointer_keys(&self) -> MouseKeys {
match self.pointer_state {
PointerState::Hover { .. } => MouseKeys::empty(),
PointerState::Stroke { keys, .. } | PointerState::Locked { keys, .. } => keys,
}
}
fn pointer_state(&self) -> EditorPointerState {
EditorPointerState {
editor_position: (self.pointer_position.x / self.scale(), self.pointer_position.y / self.scale()).into(),
mouse_keys: self.pointer_keys(),
time: Some(self.start.elapsed().as_secs_f64() * 1000.),
..Default::default()
}
}
fn tablet_pointer_state(&self, kind: &TabletToolKind, data: &TabletToolData) -> EditorPointerState {
EditorPointerState {
pressure: data.force.map(|force| force.normalized(None)),
tilt: data.clone().tilt().map(|tilt| (f64::from(tilt.x), f64::from(tilt.y)).into()),
twist: data.twist.map(f64::from),
wheel: data.tangential_force.map(f64::from),
eraser: matches!(kind, TabletToolKind::Eraser),
..self.pointer_state()
}
}
fn modifier_keys(&self) -> ModifierKeys {
let mut keys = ModifierKeys::empty();
keys.set(ModifierKeys::SHIFT, self.modifiers.shift_key());
keys.set(ModifierKeys::CONTROL, self.modifiers.control_key());
keys.set(ModifierKeys::ALT, self.modifiers.alt_key());
keys.set(ModifierKeys::META_OR_COMMAND, self.modifiers.meta_key());
keys
}
}
#[derive(Clone, Copy)]
enum PointerState {
Hover { route: Route },
Stroke { route: Route, keys: MouseKeys },
Locked { route: Route, keys: MouseKeys, position: PhysicalPosition<f64> },
}
#[derive(Clone, Copy, PartialEq)]
enum Route {
Ui,
Editor,
}
struct ViewportInfo {
x: f64,
y: f64,
width: f64,
height: f64,
scale: f64,
}
impl ViewportInfo {
fn contains(&self, position: PhysicalPosition<f64>) -> bool {
position.x >= self.x && position.y >= self.y && position.x <= self.x + self.width && position.y <= self.y + self.height
}
}
#[derive(Default)]
struct ClickTracker {
left: ClickChains,
right: ClickChains,
middle: ClickChains,
back: ClickChains,
forward: ClickChains,
}
impl ClickTracker {
fn input(&mut self, position: PhysicalPosition<f64>, button: MouseButton, state: ElementState) -> u32 {
let position = (position.x as i32, position.y as i32);
let clicks = match button {
MouseButton::Left => &mut self.left,
MouseButton::Right => &mut self.right,
MouseButton::Middle => &mut self.middle,
MouseButton::Back => &mut self.back,
MouseButton::Forward => &mut self.forward,
_ => return 1,
};
let chain = match state {
ElementState::Pressed => &mut clicks.down,
ElementState::Released => &mut clicks.up,
};
let now = Instant::now();
let count = match chain {
Some(previous) => {
let within_time = now.saturating_duration_since(previous.time) <= MULTICLICK_TIMEOUT;
let dx = position.0.abs_diff(previous.position.0) as usize;
let dy = position.1.abs_diff(previous.position.1) as usize;
let within_distance = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
if within_time && within_distance { previous.count.saturating_add(1) } else { 1 }
}
None => 1,
};
*chain = Some(Click { time: now, position, count });
count
}
}
#[derive(Default)]
struct ClickChains {
down: Option<Click>,
up: Option<Click>,
}
struct Click {
time: Instant,
position: (i32, i32),
count: u32,
}
#[derive(Default)]
struct ShakeTracker {
samples: VecDeque<(PhysicalPosition<f64>, Duration)>,
last: Option<Duration>,
}
// Keep heuristic and constants in sync with `detectShake` in `frontend/src/utility-functions/input.ts`.
impl ShakeTracker {
const SENSITIVITY_DIRECTION_CHANGES: usize = 3;
const SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO: f64 = 0.1;
const DETECTION_WINDOW: Duration = Duration::from_millis(500);
const DEBOUNCE: Duration = Duration::from_millis(1000);
fn detect(&mut self, position: PhysicalPosition<f64>, now: Duration) -> bool {
self.samples.push_back((position, now));
while self.samples.front().is_some_and(|&(_, time)| now.saturating_sub(time) > Self::DETECTION_WINDOW) {
self.samples.pop_front();
}
if self.samples.len() <= 3 || self.last.is_some_and(|time| now.saturating_sub(time) <= Self::DEBOUNCE) {
return false;
}
let mut total_distance_squared = 0.;
for i in 1..self.samples.len() {
let (p1, _) = self.samples[i - 1];
let (p2, _) = self.samples[i];
total_distance_squared += (p2.x - p1.x).powi(2) + (p2.y - p1.y).powi(2);
}
let mut direction_changes = 0;
let mut average = PhysicalPosition::new(0., 0.);
let interior_count = self.samples.len() - 2;
for i in 0..interior_count {
let (p1, _) = self.samples[i];
let (p2, _) = self.samples[i + 1];
let (p3, _) = self.samples[i + 2];
let vector1 = (p2.x - p1.x, p2.y - p1.y);
let vector2 = (p3.x - p2.x, p3.y - p2.y);
if vector1.0 * vector2.0 + vector1.1 * vector2.1 < 0. {
direction_changes += 1;
}
average.x += p2.x;
average.y += p2.y;
}
average.x /= interior_count as f64;
average.y /= interior_count as f64;
let (last, _) = self.samples[self.samples.len() - 1];
let displacement_squared = (last.x - average.x).powi(2) + (last.y - average.y).powi(2);
if Self::SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO * total_distance_squared >= displacement_squared && direction_changes >= Self::SENSITIVITY_DIRECTION_CHANGES {
self.last = Some(now);
self.samples.clear();
return true;
}
false
}
}
-1
View File
@@ -17,7 +17,6 @@ mod cli;
mod dirs;
mod event;
mod gpu_context;
mod input;
mod persist;
mod preferences;
mod render;
+4 -5
View File
@@ -71,11 +71,10 @@ fn garbage_collect_document_files(state: &PersistedState) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file()
&& !valid_paths.contains(&path)
&& let Err(e) = std::fs::remove_file(&path)
{
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
if path.is_file() && !valid_paths.contains(&path) {
if let Err(e) = std::fs::remove_file(&path) {
tracing::error!("Failed to remove orphaned document file {path:?}: {e}");
}
}
}
}
+5 -4
View File
@@ -52,12 +52,13 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
return srgb_to_linear(immediates.background_color);
}
let ui_sample = textureSample(t_ui, s_diffuse, ui_coordinate);
if (ui_sample.a >= 0.999) {
return srgb_to_linear(ui_sample);
let ui_linear = srgb_to_linear(textureSample(t_ui, s_diffuse, ui_coordinate));
if (ui_linear.a >= 0.999) {
return ui_linear;
}
let ui_srgb = unpremultiply(ui_sample);
// UI texture is premultiplied, we need to unpremultiply before blending
let ui_srgb = linear_to_srgb(unpremultiply(ui_linear));
let viewport_coordinate = (in.tex_coords - immediates.viewport_offset) * immediates.viewport_scale;
if (viewport_coordinate.x < 0.0 || viewport_coordinate.x > 1.0 ||
+9 -9
View File
@@ -1,7 +1,7 @@
use wgpu::PresentMode;
use crate::window::Window;
use crate::wrapper::{Texture, WgpuContext, WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
use crate::wrapper::{WgpuContext, WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
#[derive(derivative::Derivative)]
#[derivative(Debug)]
@@ -10,14 +10,14 @@ pub(crate) struct RenderState {
executor: WgpuExecutor,
config: wgpu::SurfaceConfiguration,
render_pipeline: wgpu::RenderPipeline,
transparent_texture: Texture,
transparent_texture: std::sync::Arc<wgpu::Texture>,
sampler: wgpu::Sampler,
desired_width: u32,
desired_height: u32,
viewport_scale: [f32; 2],
viewport_offset: [f32; 2],
viewport_texture: Option<Texture>,
overlays_texture: Option<Texture>,
viewport_texture: Option<std::sync::Arc<wgpu::Texture>>,
overlays_texture: Option<std::sync::Arc<wgpu::Texture>>,
ui_texture: Option<wgpu::Texture>,
bind_group: Option<wgpu::BindGroup>,
#[derivative(Debug = "ignore")]
@@ -46,8 +46,8 @@ impl RenderState {
surface.configure(&context.device, &config);
let transparent_texture = Texture::from(context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("transparent_fallback"),
let transparent_texture = std::sync::Arc::new(context.device.create_texture(&wgpu::TextureDescriptor {
label: Some("Transparent Texture"),
size: wgpu::Extent3d {
width: 1,
height: 1,
@@ -193,7 +193,7 @@ impl RenderState {
self.surface_outdated = true;
}
pub(crate) fn bind_viewport_texture(&mut self, viewport_texture: Texture) {
pub(crate) fn bind_viewport_texture(&mut self, viewport_texture: std::sync::Arc<wgpu::Texture>) {
self.viewport_texture = Some(viewport_texture);
self.update_bindgroup();
}
@@ -228,10 +228,10 @@ impl RenderState {
return;
};
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None);
match result {
Ok(texture) => {
self.overlays_texture = Some(texture);
self.overlays_texture = Some(texture.into());
}
Err(e) => {
self.overlays_texture = None;
+33
View File
@@ -43,6 +43,13 @@ pub(crate) struct Window {
#[allow(dead_code)]
native_handle: native::NativeWindowImpl,
custom_cursors: HashMap<CustomCursorSource, CustomCursor>,
clipboard: Option<window_clipboard::Clipboard>,
}
impl Drop for Window {
fn drop(&mut self) {
// Clipboard must be dropped before `winit_window`
drop(self.clipboard.take());
}
}
impl Window {
@@ -63,10 +70,12 @@ impl Window {
let winit_window = event_loop.create_window(attributes).unwrap();
let native_handle = native::NativeWindowImpl::new(winit_window.as_ref(), app_event_scheduler);
let clipboard = unsafe { window_clipboard::Clipboard::connect(&winit_window) }.ok();
Self {
winit_window: winit_window.into(),
native_handle,
custom_cursors: HashMap::new(),
clipboard,
}
}
@@ -199,4 +208,28 @@ impl Window {
pub(crate) fn update_menu(&self, entries: Vec<MenuItem>) {
self.native_handle.update_menu(entries);
}
pub(crate) fn clipboard_read(&self) -> Option<String> {
let Some(clipboard) = &self.clipboard else {
tracing::error!("Clipboard not available");
return None;
};
match clipboard.read() {
Ok(data) => Some(data),
Err(e) => {
tracing::error!("Failed to read from clipboard: {e}");
None
}
}
}
pub(crate) fn clipboard_write(&mut self, data: String) {
let Some(clipboard) = &mut self.clipboard else {
tracing::error!("Clipboard not available");
return;
};
if let Err(e) = clipboard.write(data) {
tracing::error!("Failed to write to clipboard: {e}")
}
}
}
-8
View File
@@ -344,14 +344,6 @@ unsafe fn position_helper(main: HWND, helper: HWND) {
let h = (r.bottom - r.top) + RESIZE_BAND_THICKNESS * 2;
let _ = unsafe { SetWindowPos(helper, Some(main), x, y, w, h, SWP_NOACTIVATE | SWP_NOSENDCHANGING) };
let outer = unsafe { CreateRectRgn(0, 0, w, h) };
let inner = unsafe { CreateRectRgn(RESIZE_BAND_THICKNESS, RESIZE_BAND_THICKNESS, w - RESIZE_BAND_THICKNESS, h - RESIZE_BAND_THICKNESS) };
let _ = unsafe { CombineRgn(Some(outer), Some(outer), Some(inner), RGN_DIFF) };
let _ = unsafe { DeleteObject(inner.into()) };
if unsafe { SetWindowRgn(helper, Some(outer), false) } == 0 {
let _ = unsafe { DeleteObject(outer.into()) };
}
}
unsafe fn calculate_hit(helper: HWND, lparam: LPARAM) -> u32 {
+1 -3
View File
@@ -2,11 +2,9 @@
name = "graphite-desktop-ui"
description = "Renders the Graphite editor frontend UI into wgpu textures"
version.workspace = true
license.workspace = true
authors.workspace = true
license.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[features]
default = []
+18 -18
View File
@@ -1,23 +1,5 @@
use std::time::Duration;
pub const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
pub const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
pub const SCROLL_LINE_HEIGHT: f64 = 40.;
pub const SCROLL_LINE_WIDTH: f64 = 40.;
#[cfg(target_os = "linux")]
pub const SCROLL_SPEED_X: f64 = 3.;
#[cfg(target_os = "linux")]
pub const SCROLL_SPEED_Y: f64 = 3.;
#[cfg(not(target_os = "linux"))]
pub const SCROLL_SPEED_X: f64 = 1.;
#[cfg(not(target_os = "linux"))]
pub const SCROLL_SPEED_Y: f64 = 1.;
pub const PINCH_ZOOM_SPEED: f64 = 300.;
pub(crate) const RESOURCE_SCHEME: &str = "resources";
pub(crate) const RESOURCE_DOMAIN: &str = "resources";
@@ -35,3 +17,21 @@ pub(crate) const HOST_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
#[cfg(target_os = "macos")]
pub(crate) const IPC_BOOTSTRAP_PREFIX: &str = "art.graphite.Graphite.ipc.";
pub(crate) const SCROLL_LINE_HEIGHT: usize = 40;
pub(crate) const SCROLL_LINE_WIDTH: usize = 40;
#[cfg(target_os = "linux")]
pub(crate) const SCROLL_SPEED_X: f32 = 3.;
#[cfg(target_os = "linux")]
pub(crate) const SCROLL_SPEED_Y: f32 = 3.;
#[cfg(not(target_os = "linux"))]
pub(crate) const SCROLL_SPEED_X: f32 = 1.;
#[cfg(not(target_os = "linux"))]
pub(crate) const SCROLL_SPEED_Y: f32 = 1.;
pub(crate) const PINCH_ZOOM_SPEED: f64 = 300.;
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
pub(crate) const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
+6 -4
View File
@@ -223,7 +223,6 @@ fn create_browser(delegate: BrowserDelegate, frames: FrameStreamer, view_info_se
.map(|browser| BrowserContext {
delegate,
browser,
input: input::InputState::default(),
view_info_sender,
_instance_dir: instance_dir,
})
@@ -253,8 +252,12 @@ pub(crate) enum InitError {
pub(crate) struct CefContextHandle;
impl CefContextHandle {
pub(crate) fn process_input(&self, event: InputEvent) {
with_context(move |context| input::process(&mut context.input, &context.browser, &event));
pub(crate) fn apply_input(&self, events: Vec<InputEvent>) {
with_context(move |context| {
for event in &events {
input::apply(&context.browser, event);
}
});
}
pub(crate) fn update_view_info(&self, update: ViewInfoUpdate) {
@@ -273,7 +276,6 @@ impl CefContextHandle {
struct BrowserContext {
delegate: BrowserDelegate,
browser: Browser,
input: input::InputState,
view_info_sender: Sender<ViewInfoUpdate>,
_instance_dir: TempDir,
}
+207 -191
View File
@@ -1,235 +1,251 @@
pub(crate) mod event;
pub(crate) use event::InputEvent;
use cef::sys::{cef_key_event_type_t, cef_mouse_button_type_t};
use cef::{Browser, ImplBrowser, ImplBrowserHost, KeyEvent, MouseEvent};
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, WindowEvent};
mod keymap;
use keymap::{ToCharRepresentation, ToNativeKeycode, ToVKBits};
use cef::sys::{cef_event_flags_t, cef_key_event_type_t, cef_mouse_button_type_t};
use cef::{Browser, ImplBrowser, ImplBrowserHost, KeyEvent, MouseEvent};
use winit::dpi::PhysicalPosition;
use winit::keyboard::{Key, KeyLocation, NamedKey};
mod state;
pub(crate) use state::{CefModifiers, InputState};
use super::consts::{PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
use event::{InputEventKind, KeyAction, Modifiers, MouseButton, PointerAction};
#[derive(Default)]
pub(crate) struct InputState {
position: PhysicalPosition<f64>,
buttons: ButtonStates,
/// A window input translated into the plain data CEF consumes — no winit types, so it can
/// be applied to a browser living in another process.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) enum InputEvent {
MouseMove { data: MouseData, leave: bool },
MouseClick { data: MouseData, button: MouseButtonKind, up: bool, click_count: i32 },
MouseWheel { data: MouseData, delta_x: i32, delta_y: i32 },
Key(KeyData),
}
impl InputState {
fn pointer_move(&mut self, position: PhysicalPosition<f64>) -> bool {
let moved = (position.x as i32, position.y as i32) != (self.position.x as i32, self.position.y as i32);
self.position = position;
moved
}
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct MouseData {
pub(crate) x: i32,
pub(crate) y: i32,
pub(crate) modifiers: u32,
}
pub(crate) fn process(state: &mut InputState, browser: &Browser, event: &InputEvent) {
let Some(host) = browser.host() else { return };
match &event.kind {
InputEventKind::Pointer { position, action } => {
let position = position.unwrap_or(state.position);
match *action {
PointerAction::Move => {
if !state.pointer_move(position) {
return;
}
let flags = event_flags(&event.modifiers, &state.buttons);
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 0);
}
PointerAction::Enter => {
state.pointer_move(position);
let flags = event_flags(&event.modifiers, &state.buttons);
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 0);
}
PointerAction::Exit => {
state.pointer_move(position);
let flags = event_flags(&event.modifiers, &state.buttons);
host.send_mouse_move_event(Some(&mouse_event(position, flags)), 1);
}
PointerAction::Press { button, count } | PointerAction::Release { button, count } => {
state.pointer_move(position);
let cef_button = match button {
MouseButton::Left => cef_mouse_button_type_t::MBT_LEFT,
MouseButton::Right => cef_mouse_button_type_t::MBT_RIGHT,
MouseButton::Middle => cef_mouse_button_type_t::MBT_MIDDLE,
MouseButton::Unknown => return,
};
let up = matches!(action, PointerAction::Release { .. });
state.buttons.update(button, !up);
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum MouseButtonKind {
Left,
Right,
Middle,
}
// CEF only understands single, double and triple clicks; further clicks alternate between double and triple.
let count = match count {
0 | 1 => 1,
count if count % 2 == 0 => 2,
_ => 3,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum KeyEventKind {
RawKeyDown,
KeyUp,
Char,
}
let flags = event_flags(&event.modifiers, &state.buttons);
host.send_mouse_click_event(Some(&mouse_event(position, flags)), cef::MouseButtonType::from(cef_button), up as i32, count);
}
PointerAction::ScrollLines { x, y } => {
let flags = event_flags(&event.modifiers, &state.buttons);
let delta_x = (x * SCROLL_LINE_WIDTH * SCROLL_SPEED_X) as i32;
let delta_y = (y * SCROLL_LINE_HEIGHT * SCROLL_SPEED_Y) as i32;
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), delta_x, delta_y);
}
PointerAction::ScrollPixels { x, y } => {
let flags = event_flags(&event.modifiers, &state.buttons) | PRECISION_SCROLLING_DELTA;
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), (x * SCROLL_SPEED_X) as i32, (y * SCROLL_SPEED_Y) as i32);
}
PointerAction::Zoom(delta) => {
if !delta.is_normal() {
return;
}
let flags = CONTROL_DOWN | PRECISION_SCROLLING_DELTA;
host.send_mouse_wheel_event(Some(&mouse_event(position, flags)), 0, (delta * PINCH_ZOOM_SPEED).round() as i32);
}
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct KeyData {
pub(crate) kind: KeyEventKind,
pub(crate) modifiers: u32,
pub(crate) windows_key_code: i32,
pub(crate) native_key_code: i32,
pub(crate) character: u16,
pub(crate) unmodified_character: u16,
}
/// Turns a winit event into zero or more [`InputEvent`]s, updating the tracked input state
/// (cursor position, click counting, modifiers) along the way.
pub(crate) fn translate(input_state: &mut InputState, event: &WindowEvent) -> Vec<InputEvent> {
match event {
WindowEvent::PointerMoved { position, .. } => {
if !input_state.cursor_move(position) {
return Vec::new();
}
vec![InputEvent::MouseMove {
data: input_state.mouse_data(),
leave: false,
}]
}
InputEventKind::Key {
key,
key_without_modifiers,
physical_key,
location,
text,
action,
} => {
let mut flags = event_flags(&event.modifiers, &state.buttons);
WindowEvent::PointerEntered { position, .. } => {
let _ = input_state.cursor_move(position);
vec![InputEvent::MouseMove {
data: input_state.mouse_data(),
leave: false,
}]
}
WindowEvent::PointerLeft { position, .. } => {
if let Some(position) = position {
let _ = input_state.cursor_move(position);
}
vec![InputEvent::MouseMove {
data: input_state.mouse_data(),
leave: true,
}]
}
WindowEvent::PointerButton { state, button, position, .. } => {
let mouse_button = match button {
ButtonSource::Mouse(mouse_button) => mouse_button,
_ => {
return Vec::new(); // TODO: Handle touch input
}
};
let own_flag = match key {
Key::Named(NamedKey::Shift) => SHIFT_DOWN,
Key::Named(NamedKey::Control) => CONTROL_DOWN,
Key::Named(NamedKey::Alt) => ALT_DOWN,
Key::Named(NamedKey::AltGraph) => ALTGR_DOWN,
Key::Named(NamedKey::Meta) => COMMAND_DOWN,
let _ = input_state.cursor_move(position);
let click_count = input_state.mouse_input(mouse_button, state).into();
let up = matches!(state, ElementState::Released);
let button = match mouse_button {
MouseButton::Left => MouseButtonKind::Left,
MouseButton::Right => MouseButtonKind::Right,
MouseButton::Middle => MouseButtonKind::Middle,
_ => return Vec::new(),
};
vec![InputEvent::MouseClick {
data: input_state.mouse_data(),
button,
up,
click_count,
}]
}
WindowEvent::MouseWheel { delta, phase: _, device_id: _, .. } => {
let (mut delta_x, mut delta_y) = match delta {
MouseScrollDelta::LineDelta(x, y) => (x * SCROLL_LINE_WIDTH as f32, y * SCROLL_LINE_HEIGHT as f32),
MouseScrollDelta::PixelDelta(physical_position) => (physical_position.x as f32, physical_position.y as f32),
};
delta_x *= SCROLL_SPEED_X;
delta_y *= SCROLL_SPEED_Y;
vec![InputEvent::MouseWheel {
data: input_state.mouse_data(),
delta_x: delta_x as i32,
delta_y: delta_y as i32,
}]
}
WindowEvent::ModifiersChanged(modifiers) => {
input_state.modifiers_changed(&modifiers.state());
Vec::new()
}
WindowEvent::KeyboardInput { device_id: _, event, is_synthetic: _ } => {
input_state.modifiers_apply_key_event(&event.logical_key, &event.state);
let mut kind = match (event.state, &event.logical_key) {
(ElementState::Pressed, winit::keyboard::Key::Character(_)) => KeyEventKind::Char,
(ElementState::Pressed, _) => KeyEventKind::RawKeyDown,
(ElementState::Released, _) => KeyEventKind::KeyUp,
};
let modifiers = input_state.cef_modifiers(&event.location, event.repeat).into();
let windows_key_code = match &event.logical_key {
winit::keyboard::Key::Named(named) => named.to_vk_bits(),
winit::keyboard::Key::Character(char) => char.chars().next().unwrap_or_default().to_vk_bits(),
_ => 0,
};
match action {
KeyAction::Press | KeyAction::Repeat => flags |= own_flag,
KeyAction::Release => flags &= !own_flag,
}
flags |= match location {
KeyLocation::Left => IS_LEFT,
KeyLocation::Right => IS_RIGHT,
KeyLocation::Numpad => IS_KEY_PAD,
KeyLocation::Standard => 0,
};
if *action == KeyAction::Repeat {
flags |= IS_REPEAT;
}
let native_key_code = event.physical_key.to_native_keycode();
let windows_key_code = match key {
Key::Named(named) => named.to_vk_bits(),
Key::Character(char) => char.chars().next().unwrap_or_default().to_vk_bits(),
_ => 0,
};
let native_key_code = physical_key.to_native_keycode();
let char_representation = key.to_char_representation();
let char_representation = event.logical_key.to_char_representation();
#[allow(unused_mut)]
let mut character = char_representation as u16;
let unmodified_character = key_without_modifiers.to_char_representation() as u16;
if event.state == ElementState::Pressed && character != 0 {
kind = KeyEventKind::Char;
}
let unmodified_character = event.key_without_modifiers.to_char_representation() as u16;
#[cfg(target_os = "macos")] // See https://www.magpcss.org/ceforum/viewtopic.php?start=10&t=11650
if character == 0 && unmodified_character == 0 && text.is_some() {
if character == 0 && unmodified_character == 0 && event.text_with_all_modifiers.is_some() {
character = 1;
}
#[cfg(not(target_os = "macos"))]
let _ = text;
let key_event = |kind: cef_key_event_type_t, windows_key_code: i32| KeyEvent {
type_: kind.into(),
modifiers: flags,
let key = KeyData {
kind,
modifiers,
windows_key_code,
native_key_code,
character,
unmodified_character,
..Default::default()
};
match action {
KeyAction::Press | KeyAction::Repeat if char_representation != '\0' => {
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_RAWKEYDOWN, windows_key_code)));
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_CHAR, char_representation as i32)));
}
KeyAction::Press | KeyAction::Repeat => {
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_RAWKEYDOWN, windows_key_code)));
}
KeyAction::Release => {
host.send_key_event(Some(&key_event(cef_key_event_type_t::KEYEVENT_KEYUP, windows_key_code)));
}
if kind == KeyEventKind::Char {
// CEF expects a raw key-down before the character event it produces.
vec![
InputEvent::Key(KeyData {
kind: KeyEventKind::RawKeyDown,
..key
}),
InputEvent::Key(KeyData {
windows_key_code: char_representation as i32,
..key
}),
]
} else {
vec![InputEvent::Key(key)]
}
}
WindowEvent::PinchGesture { delta, .. } => {
if !delta.is_normal() {
return Vec::new();
}
let data = MouseData {
modifiers: CefModifiers::PINCH_MODIFIERS.into(),
..input_state.mouse_data()
};
vec![InputEvent::MouseWheel {
data,
delta_x: 0,
delta_y: (delta * PINCH_ZOOM_SPEED).round() as i32,
}]
}
_ => Vec::new(),
}
}
#[derive(Default)]
struct ButtonStates {
left: bool,
right: bool,
middle: bool,
}
impl ButtonStates {
fn update(&mut self, button: MouseButton, held: bool) {
match button {
MouseButton::Left => self.left = held,
MouseButton::Right => self.right = held,
MouseButton::Middle => self.middle = held,
MouseButton::Unknown => {}
/// Sends a translated [`InputEvent`] to the browser. Must run on the thread owning the browser.
pub(crate) fn apply(browser: &Browser, event: &InputEvent) {
let Some(host) = browser.host() else { return };
match event {
InputEvent::MouseMove { data, leave } => {
host.send_mouse_move_event(Some(&data.into()), *leave as i32);
}
InputEvent::MouseClick { data, button, up, click_count } => {
let cef_button = cef::MouseButtonType::from(match button {
MouseButtonKind::Left => cef_mouse_button_type_t::MBT_LEFT,
MouseButtonKind::Right => cef_mouse_button_type_t::MBT_RIGHT,
MouseButtonKind::Middle => cef_mouse_button_type_t::MBT_MIDDLE,
});
host.send_mouse_click_event(Some(&data.into()), cef_button, *up as i32, *click_count);
}
InputEvent::MouseWheel { data, delta_x, delta_y } => {
host.send_mouse_wheel_event(Some(&data.into()), *delta_x, *delta_y);
}
InputEvent::Key(key) => {
let key_event = KeyEvent {
type_: match key.kind {
KeyEventKind::RawKeyDown => cef_key_event_type_t::KEYEVENT_RAWKEYDOWN,
KeyEventKind::KeyUp => cef_key_event_type_t::KEYEVENT_KEYUP,
KeyEventKind::Char => cef_key_event_type_t::KEYEVENT_CHAR,
}
.into(),
modifiers: key.modifiers,
windows_key_code: key.windows_key_code,
native_key_code: key.native_key_code,
character: key.character,
unmodified_character: key.unmodified_character,
..Default::default()
};
host.send_key_event(Some(&key_event));
}
}
}
fn mouse_event(position: PhysicalPosition<f64>, flags: u32) -> MouseEvent {
MouseEvent {
x: position.x as i32,
y: position.y as i32,
modifiers: flags,
impl From<&MouseData> for MouseEvent {
fn from(data: &MouseData) -> Self {
MouseEvent {
x: data.x,
y: data.y,
modifiers: data.modifiers,
}
}
}
fn event_flags(modifiers: &Modifiers, buttons: &ButtonStates) -> u32 {
let bit = |condition: bool, flag: u32| if condition { flag } else { 0 };
bit(modifiers.shift, SHIFT_DOWN)
| bit(modifiers.control, CONTROL_DOWN)
| bit(modifiers.alt, ALT_DOWN)
| bit(modifiers.alt_graph, ALTGR_DOWN)
| bit(modifiers.meta, COMMAND_DOWN)
| bit(modifiers.caps_lock, CAPS_LOCK_ON)
| bit(modifiers.num_lock, NUM_LOCK_ON)
| bit(buttons.left, LEFT_MOUSE_BUTTON)
| bit(buttons.right, RIGHT_MOUSE_BUTTON)
| bit(buttons.middle, MIDDLE_MOUSE_BUTTON)
}
const fn flag(flag: cef_event_flags_t) -> u32 {
#[cfg(not(target_os = "windows"))]
{
flag.0
}
#[cfg(target_os = "windows")]
{
flag.0 as u32
}
}
const SHIFT_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_SHIFT_DOWN);
const CONTROL_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_CONTROL_DOWN);
const ALT_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_ALT_DOWN);
const ALTGR_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_ALTGR_DOWN);
const COMMAND_DOWN: u32 = flag(cef_event_flags_t::EVENTFLAG_COMMAND_DOWN);
const CAPS_LOCK_ON: u32 = flag(cef_event_flags_t::EVENTFLAG_CAPS_LOCK_ON);
const NUM_LOCK_ON: u32 = flag(cef_event_flags_t::EVENTFLAG_NUM_LOCK_ON);
const LEFT_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON);
const MIDDLE_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_MIDDLE_MOUSE_BUTTON);
const RIGHT_MOUSE_BUTTON: u32 = flag(cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON);
const IS_LEFT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_LEFT);
const IS_RIGHT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_RIGHT);
const IS_KEY_PAD: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_KEY_PAD);
const IS_REPEAT: u32 = flag(cef_event_flags_t::EVENTFLAG_IS_REPEAT);
const PRECISION_SCROLLING_DELTA: u32 = flag(cef_event_flags_t::EVENTFLAG_PRECISION_SCROLLING_DELTA);
-245
View File
@@ -1,245 +0,0 @@
use winit::dpi::PhysicalPosition;
use winit::event::{ElementState, KeyEvent};
use winit::keyboard::{Key, KeyLocation, ModifiersState, PhysicalKey, SmolStr};
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct InputEvent {
pub(crate) kind: InputEventKind,
pub(crate) modifiers: Modifiers,
}
impl InputEvent {
pub fn pointer() -> PointerInputEventBuilder {
PointerInputEventBuilder { position: UnknownPosition }
}
pub fn key(event: &KeyEvent) -> InputEventBuilder {
let action = match (event.state, event.repeat) {
(ElementState::Pressed, false) => KeyAction::Press,
(ElementState::Pressed, true) => KeyAction::Repeat,
(ElementState::Released, _) => KeyAction::Release,
};
InputEventBuilder::new(InputEventKind::Key {
key: event.logical_key.clone(),
key_without_modifiers: event.key_without_modifiers.clone(),
physical_key: event.physical_key,
location: event.location,
text: event.text_with_all_modifiers.clone(),
action,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum MouseButton {
Left,
Right,
Middle,
Unknown,
}
impl From<winit::event::MouseButton> for MouseButton {
fn from(button: winit::event::MouseButton) -> Self {
match button {
winit::event::MouseButton::Left => Self::Left,
winit::event::MouseButton::Right => Self::Right,
winit::event::MouseButton::Middle => Self::Middle,
_ => Self::Unknown,
}
}
}
impl From<winit::event::ButtonSource> for MouseButton {
fn from(button: winit::event::ButtonSource) -> Self {
button.mouse_button().map_or(Self::Unknown, Self::from)
}
}
#[must_use]
#[derive(Clone, Debug)]
pub struct PointerInputEventBuilder<P = UnknownPosition> {
position: P,
}
impl PointerInputEventBuilder<UnknownPosition> {
pub fn position(self, position: PhysicalPosition<f64>) -> PointerInputEventBuilder<PhysicalPosition<f64>> {
PointerInputEventBuilder { position }
}
}
impl PointerInputEventBuilder<PhysicalPosition<f64>> {
pub fn moved(self) -> InputEventBuilder {
self.finish(PointerAction::Move)
}
pub fn entered(self) -> InputEventBuilder {
self.finish(PointerAction::Enter)
}
}
impl<P: PointerPosition> PointerInputEventBuilder<P> {
pub fn exited(self) -> InputEventBuilder {
self.finish(PointerAction::Exit)
}
pub fn pressed(self, button: impl Into<MouseButton>, count: u32) -> InputEventBuilder {
self.finish(PointerAction::Press { button: button.into(), count })
}
pub fn released(self, button: impl Into<MouseButton>, count: u32) -> InputEventBuilder {
self.finish(PointerAction::Release { button: button.into(), count })
}
pub fn scrolled_lines(self, x: f64, y: f64) -> InputEventBuilder {
self.finish(PointerAction::ScrollLines { x, y })
}
pub fn scrolled_pixels(self, x: f64, y: f64) -> InputEventBuilder {
self.finish(PointerAction::ScrollPixels { x, y })
}
pub fn zoomed(self, delta: f64) -> InputEventBuilder {
self.finish(PointerAction::Zoom(delta))
}
fn finish(self, action: PointerAction) -> InputEventBuilder {
InputEventBuilder::new(InputEventKind::Pointer {
position: self.position.position(),
action,
})
}
}
#[must_use]
#[derive(Clone, Debug)]
pub struct InputEventBuilder {
kind: InputEventKind,
modifiers: Modifiers,
}
impl InputEventBuilder {
fn new(kind: InputEventKind) -> Self {
Self {
kind,
modifiers: Modifiers::default(),
}
}
pub fn shift(mut self, on: bool) -> Self {
self.modifiers.shift = on;
self
}
pub fn control(mut self, on: bool) -> Self {
self.modifiers.control = on;
self
}
pub fn alt(mut self, on: bool) -> Self {
self.modifiers.alt = on;
self
}
pub fn alt_graph(mut self, on: bool) -> Self {
self.modifiers.alt_graph = on;
self
}
pub fn meta(mut self, on: bool) -> Self {
self.modifiers.meta = on;
self
}
pub fn caps_lock(mut self, on: bool) -> Self {
self.modifiers.caps_lock = on;
self
}
pub fn num_lock(mut self, on: bool) -> Self {
self.modifiers.num_lock = on;
self
}
pub fn modifiers(mut self, modifiers: ModifiersState) -> Self {
self.modifiers.shift = modifiers.shift_key();
self.modifiers.control = modifiers.control_key();
self.modifiers.alt = modifiers.alt_key();
self.modifiers.meta = modifiers.meta_key();
self
}
pub fn build(self) -> InputEvent {
InputEvent {
kind: self.kind,
modifiers: self.modifiers,
}
}
}
#[expect(private_bounds)]
pub trait PointerPosition: OptionalPosition {}
impl PointerPosition for UnknownPosition {}
impl PointerPosition for PhysicalPosition<f64> {}
#[derive(Clone, Copy, Debug)]
pub struct UnknownPosition;
trait OptionalPosition {
fn position(self) -> Option<PhysicalPosition<f64>>;
}
impl OptionalPosition for UnknownPosition {
fn position(self) -> Option<PhysicalPosition<f64>> {
None
}
}
impl OptionalPosition for PhysicalPosition<f64> {
fn position(self) -> Option<PhysicalPosition<f64>> {
Some(self)
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) enum InputEventKind {
Pointer {
position: Option<PhysicalPosition<f64>>,
action: PointerAction,
},
Key {
key: Key,
key_without_modifiers: Key,
physical_key: PhysicalKey,
location: KeyLocation,
text: Option<SmolStr>,
action: KeyAction,
},
}
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) enum PointerAction {
Move,
Enter,
Exit,
Press { button: MouseButton, count: u32 },
Release { button: MouseButton, count: u32 },
ScrollLines { x: f64, y: f64 },
ScrollPixels { x: f64, y: f64 },
Zoom(f64),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(crate) enum KeyAction {
Press,
Repeat,
Release,
}
#[derive(Clone, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
pub(crate) struct Modifiers {
pub(crate) shift: bool,
pub(crate) control: bool,
pub(crate) alt: bool,
pub(crate) alt_graph: bool,
pub(crate) meta: bool,
pub(crate) caps_lock: bool,
pub(crate) num_lock: bool,
}
+256
View File
@@ -0,0 +1,256 @@
use cef::sys::cef_event_flags_t;
use std::time::Instant;
use winit::dpi::PhysicalPosition;
use winit::event::{ElementState, MouseButton};
use winit::keyboard::{Key, KeyLocation, ModifiersState, NamedKey};
use super::MouseData;
use crate::consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT};
#[derive(Default)]
pub(crate) struct InputState {
modifiers: ModifiersState,
mouse_position: MousePosition,
mouse_state: MouseState,
mouse_click_tracker: ClickTracker,
}
impl InputState {
pub(crate) fn modifiers_changed(&mut self, modifiers: &ModifiersState) {
self.modifiers = *modifiers;
}
pub(crate) fn modifiers_apply_key_event(&mut self, key: &Key, state: &ElementState) {
let bits = match key {
Key::Named(NamedKey::Shift) => ModifiersState::SHIFT,
Key::Named(NamedKey::Control) => ModifiersState::CONTROL,
Key::Named(NamedKey::Alt) => ModifiersState::ALT,
Key::Named(NamedKey::Meta) => ModifiersState::META,
_ => return,
};
let is_pressed = matches!(state, ElementState::Pressed);
self.modifiers.set(bits, is_pressed);
}
pub(crate) fn cursor_move(&mut self, position: &PhysicalPosition<f64>) -> bool {
let new = position.into();
if self.mouse_position == new {
return false;
}
self.mouse_position = new;
true
}
pub(crate) fn mouse_input(&mut self, button: &MouseButton, state: &ElementState) -> ClickCount {
self.mouse_state.update(button, state);
self.mouse_click_tracker.input(button, state, self.mouse_position)
}
pub(crate) fn cef_modifiers(&self, location: &KeyLocation, is_repeat: bool) -> CefModifiers {
CefModifiers::new(self, location, is_repeat)
}
pub(crate) fn cef_mouse_modifiers(&self) -> CefModifiers {
self.cef_modifiers(&KeyLocation::Standard, false)
}
pub(crate) fn mouse_data(&self) -> MouseData {
MouseData {
x: self.mouse_position.x,
y: self.mouse_position.y,
modifiers: self.cef_mouse_modifiers().into(),
}
}
}
#[derive(Default, Clone, Copy, Eq, PartialEq)]
pub(crate) struct MousePosition {
x: i32,
y: i32,
}
impl From<&PhysicalPosition<f64>> for MousePosition {
fn from(position: &PhysicalPosition<f64>) -> Self {
Self {
x: position.x as i32,
y: position.y as i32,
}
}
}
#[derive(Default, Clone)]
pub(crate) struct MouseState {
left: bool,
right: bool,
middle: bool,
}
impl MouseState {
pub(crate) fn update(&mut self, button: &MouseButton, state: &ElementState) {
match state {
ElementState::Pressed => match button {
MouseButton::Left => self.left = true,
MouseButton::Right => self.right = true,
MouseButton::Middle => self.middle = true,
_ => {}
},
ElementState::Released => match button {
MouseButton::Left => self.left = false,
MouseButton::Right => self.right = false,
MouseButton::Middle => self.middle = false,
_ => {}
},
}
}
}
#[derive(Default)]
struct ClickTracker {
left: Option<ClickRecord>,
middle: Option<ClickRecord>,
right: Option<ClickRecord>,
}
impl ClickTracker {
fn input(&mut self, button: &MouseButton, state: &ElementState, position: MousePosition) -> ClickCount {
let record = match button {
MouseButton::Left => &mut self.left,
MouseButton::Right => &mut self.right,
MouseButton::Middle => &mut self.middle,
_ => return ClickCount::Single,
};
let Some(record) = record else {
*record = Some(ClickRecord {
down_position: position,
up_position: position,
..Default::default()
});
return ClickCount::Single;
};
let now = Instant::now();
let within_time = now.saturating_duration_since(record.time) <= MULTICLICK_TIMEOUT;
let (prev_count, prev_position) = match state {
ElementState::Pressed => (record.down_count, record.down_position),
ElementState::Released => (record.up_count, record.up_position),
};
let dx = position.x.abs_diff(prev_position.x) as usize;
let dy = position.y.abs_diff(prev_position.y) as usize;
let within_dist = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
let count = match (prev_count, within_time, within_dist) {
(ClickCount::Single, true, true) => ClickCount::Double,
(ClickCount::Double, true, true) => ClickCount::Triple,
(ClickCount::Triple, true, true) => ClickCount::Double,
_ => ClickCount::Single,
};
record.time = now;
match state {
ElementState::Pressed => {
record.down_position = position;
record.down_count = count;
}
ElementState::Released => {
record.up_position = position;
record.up_count = count;
}
}
count
}
}
#[derive(Clone, Copy, PartialEq, Default)]
pub(crate) enum ClickCount {
#[default]
Single,
Double,
Triple,
}
impl From<ClickCount> for i32 {
fn from(count: ClickCount) -> i32 {
match count {
ClickCount::Single => 1,
ClickCount::Double => 2,
ClickCount::Triple => 3,
}
}
}
#[derive(Clone, Copy)]
struct ClickRecord {
time: Instant,
down_position: MousePosition,
up_position: MousePosition,
down_count: ClickCount,
up_count: ClickCount,
}
impl Default for ClickRecord {
fn default() -> Self {
Self {
time: Instant::now(),
down_position: Default::default(),
up_position: Default::default(),
down_count: Default::default(),
up_count: Default::default(),
}
}
}
pub(crate) struct CefModifiers(cef_event_flags_t);
impl CefModifiers {
fn new(input_state: &InputState, location: &KeyLocation, is_repeat: bool) -> Self {
let mut inner = cef_event_flags_t::EVENTFLAG_NONE;
if input_state.modifiers.shift_key() {
inner |= cef_event_flags_t::EVENTFLAG_SHIFT_DOWN;
}
if input_state.modifiers.control_key() {
inner |= cef_event_flags_t::EVENTFLAG_CONTROL_DOWN;
}
if input_state.modifiers.alt_key() {
inner |= cef_event_flags_t::EVENTFLAG_ALT_DOWN;
}
if input_state.modifiers.meta_key() {
inner |= cef_event_flags_t::EVENTFLAG_COMMAND_DOWN;
}
if input_state.mouse_state.left {
inner |= cef_event_flags_t::EVENTFLAG_LEFT_MOUSE_BUTTON;
}
if input_state.mouse_state.right {
inner |= cef_event_flags_t::EVENTFLAG_RIGHT_MOUSE_BUTTON;
}
if input_state.mouse_state.middle {
inner |= cef_event_flags_t::EVENTFLAG_MIDDLE_MOUSE_BUTTON;
}
if is_repeat {
inner |= cef_event_flags_t::EVENTFLAG_IS_REPEAT;
}
inner |= match location {
KeyLocation::Left => cef_event_flags_t::EVENTFLAG_IS_LEFT,
KeyLocation::Right => cef_event_flags_t::EVENTFLAG_IS_RIGHT,
KeyLocation::Numpad => cef_event_flags_t::EVENTFLAG_IS_KEY_PAD,
KeyLocation::Standard => cef_event_flags_t::EVENTFLAG_NONE,
};
Self(inner)
}
pub(super) const PINCH_MODIFIERS: Self = Self(cef_event_flags_t(
cef_event_flags_t::EVENTFLAG_CONTROL_DOWN.0 | cef_event_flags_t::EVENTFLAG_PRECISION_SCROLLING_DELTA.0,
));
}
impl From<CefModifiers> for u32 {
fn from(val: CefModifiers) -> Self {
#[cfg(not(target_os = "windows"))]
return val.0.0;
#[cfg(target_os = "windows")]
return val.0.0 as u32;
}
}
+15 -5
View File
@@ -22,9 +22,6 @@ mod resources;
mod utility;
mod view;
pub use consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
pub use input::event::{InputEvent, InputEventBuilder, MouseButton, PointerInputEventBuilder, PointerPosition, UnknownPosition};
pub struct UiContext<S: Stage = Started> {
inner: S::ContextData,
}
@@ -70,6 +67,7 @@ impl UiContext<Started> {
Ok(UiInstance {
inner: Arc::new(UiInstanceInner {
host: self.inner.clone(),
input: Mutex::new(input::InputState::default()),
events: Mutex::new(events),
queue,
shutdown_complete: Mutex::new(shutdown_complete),
@@ -143,6 +141,7 @@ pub struct UiInstance {
pub(crate) struct UiInstanceInner {
host: Arc<HostHandle>,
input: Mutex<input::InputState>,
events: Mutex<Receiver<UiEvent>>,
queue: events::EventQueue,
shutdown_complete: Mutex<Receiver<()>>,
@@ -153,7 +152,18 @@ impl UiInstance {
pub fn send(&self, command: UiCommand) {
let shared = &self.inner;
match command {
UiCommand::Input(event) => shared.host.send(HostControlMessage::Input(event)),
UiCommand::Input(event) => {
let events = {
let Ok(mut input) = shared.input.lock() else {
tracing::error!("Failed to lock the input state");
return;
};
input::translate(&mut input, &event)
};
if !events.is_empty() {
shared.host.send(HostControlMessage::Input(events));
}
}
UiCommand::Resized { width, height } => shared.host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Size { width, height })),
UiCommand::ScaleChanged(scale) => shared.host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Scale(scale))),
UiCommand::Refresh => shared.host.send(HostControlMessage::RefreshViewInfo),
@@ -210,7 +220,7 @@ impl Drop for UiInstanceInner {
#[derive(Debug)]
pub enum UiCommand {
Input(InputEvent),
Input(winit::event::WindowEvent),
Resized { width: u32, height: u32 },
ScaleChanged(f64),
Refresh,
+1 -1
View File
@@ -99,7 +99,7 @@ enum ControlOutcome {
fn control_loop(receiver: &IpcReceiver<HostControlMessage>, context: &CefContextHandle, sequence: &SequenceState) -> ControlOutcome {
loop {
match receiver.recv() {
Ok(HostControlMessage::Input(event)) => context.process_input(event),
Ok(HostControlMessage::Input(events)) => context.apply_input(events),
Ok(HostControlMessage::UpdateViewInfo(update)) => context.update_view_info(update),
Ok(HostControlMessage::RefreshViewInfo) => context.refresh_view_info(),
Ok(HostControlMessage::SendWebMessage(message)) => context.send_web_message(message),
+1 -1
View File
@@ -8,7 +8,7 @@ use crate::view::ViewInfoUpdate;
#[derive(Serialize, Deserialize)]
pub(crate) enum HostControlMessage {
Input(InputEvent),
Input(Vec<InputEvent>),
UpdateViewInfo(ViewInfoUpdate),
RefreshViewInfo,
SendWebMessage(Vec<u8>),
+6 -6
View File
@@ -1,12 +1,12 @@
[package]
name = "graphite-desktop-wrapper"
version = "0.1.0"
description = "Graphite Desktop Wrapper"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
authors = ["Graphite Authors <[email protected]>"]
license = "Apache-2.0"
repository = ""
edition = "2024"
rust-version = "1.87"
[features]
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
@@ -2,7 +2,7 @@ use graphite_editor::messages::clipboard::utility_types::ClipboardContentRaw;
use graphite_editor::messages::prelude::*;
use super::DesktopWrapperMessageDispatcher;
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage, SaveFileDialogContext};
use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessage, OpenFileDialogContext, SaveFileDialogContext};
pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: DesktopWrapperMessage) {
match message {
@@ -15,14 +15,14 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
DesktopWrapperMessage::Input(message) => {
dispatcher.queue_editor_message(EditorMessage::InputPreprocessor(message));
}
DesktopWrapperMessage::IngestFile { path, content, action } => {
dispatcher.queue_editor_message(IngestMessage::Ingest {
data: content,
action,
mime_type: String::new(),
path: Some(path),
});
}
DesktopWrapperMessage::FileDialogResult { path, content, context } => match context {
OpenFileDialogContext::Open => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::OpenFile { path, content });
}
OpenFileDialogContext::Import => {
dispatcher.queue_desktop_wrapper_message(DesktopWrapperMessage::ImportFile { path, content });
}
},
DesktopWrapperMessage::SaveFileDialogResult { path, context } => match context {
SaveFileDialogContext::Document { document_id, content } => {
dispatcher.respond(DesktopFrontendMessage::WriteFile { path: path.clone(), content });
@@ -35,6 +35,14 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
}
},
DesktopWrapperMessage::OpenFile { path, content } => {
let message = PortfolioMessage::OpenFile { path, content };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::ImportFile { path, content } => {
let message = PortfolioMessage::ImportFile { path, content };
dispatcher.queue_editor_message(message);
}
DesktopWrapperMessage::PollNodeGraphEvaluation => dispatcher.poll_node_graph_evaluation(),
DesktopWrapperMessage::UpdateMaximized { maximized } => {
let message = FrontendMessage::UpdateMaximized { maximized };
@@ -3,23 +3,27 @@ use graphite_editor::messages::layout::utility_types::layout_widget::LayoutTarge
use graphite_editor::messages::prelude::FrontendMessage;
use super::DesktopWrapperMessageDispatcher;
use super::messages::{DesktopFrontendMessage, IngestAction, SaveFileDialogContext};
use super::messages::{DesktopFrontendMessage, FileFilter, OpenFileDialogContext, SaveFileDialogContext};
pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: FrontendMessage) -> Option<FrontendMessage> {
match message {
FrontendMessage::RenderOverlays { context } => {
dispatcher.respond(DesktopFrontendMessage::UpdateOverlays(context.take_scene()));
}
FrontendMessage::TriggerBrowse { options, action } => {
let title = match action {
IngestAction::Open => "Open Document",
IngestAction::Import => "Import File",
_ => "Select File",
};
FrontendMessage::TriggerOpen => {
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: title.to_string(),
options,
action,
title: "Open Document".to_string(),
filters: vec![],
multiple: true,
context: OpenFileDialogContext::Open,
});
}
FrontendMessage::TriggerImport => {
dispatcher.respond(DesktopFrontendMessage::OpenFileDialog {
title: "Import File".to_string(),
filters: vec![],
multiple: false,
context: OpenFileDialogContext::Import,
});
}
FrontendMessage::TriggerSaveDocument {
@@ -27,29 +31,32 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
name,
path,
folder,
filters,
content,
} => {
let content = content.into_vec();
if let Some(path) = path {
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
} else {
let extension = std::path::Path::new(&name).extension().and_then(|extension| extension.to_str()).unwrap_or("*").to_string();
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
title: "Save Document".to_string(),
default_filename: name,
default_folder: folder,
filters,
filters: vec![FileFilter {
name: "Graphite Document".to_string(),
extensions: vec![extension],
}],
context: SaveFileDialogContext::Document { document_id, content },
});
}
}
FrontendMessage::TriggerSaveFile { name, folder, filters, content } => {
FrontendMessage::TriggerSaveFile { name, folder, content } => {
let content = content.into_vec();
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
title: "Save File".to_string(),
default_filename: name,
default_folder: folder,
filters,
filters: Vec::new(),
context: SaveFileDialogContext::File { content },
});
}
@@ -115,19 +122,9 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
FrontendMessage::TriggerClipboardWrite { content } => {
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite { content });
}
// The desktop app has no web origin to build the link from, so it points at the hosted editor; the token
// alone is offered separately.
FrontendMessage::TriggerSessionLinkCopy { token } => {
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite {
content: format!("https://editor.graphite.rs/?session={token}"),
});
}
FrontendMessage::WindowPointerLock => {
dispatcher.respond(DesktopFrontendMessage::PointerLock);
}
FrontendMessage::WindowUpdateDirectInput { enabled } => {
dispatcher.respond(DesktopFrontendMessage::WindowUpdateDirectInput { enabled });
}
FrontendMessage::WindowClose => {
dispatcher.respond(DesktopFrontendMessage::WindowClose);
}
+6 -3
View File
@@ -10,7 +10,6 @@ use std::sync::Arc;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
pub use wgpu_executor::Texture;
pub use wgpu_executor::WgpuBackends;
pub use wgpu_executor::WgpuContext;
pub use wgpu_executor::WgpuContextBuilder;
@@ -53,17 +52,21 @@ impl DesktopWrapper {
executor.execute()
}
pub fn set_completion_notifier(notifier: impl Fn() + Send + Sync + 'static) {
graphite_editor::node_graph_executor::set_completion_notifier(Arc::new(notifier));
}
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
let result = graphite_editor::node_graph_executor::run_node_graph().await;
match result {
(true, texture) => NodeGraphExecutionResult::HasRun(texture),
(true, texture) => NodeGraphExecutionResult::HasRun(texture.map(Into::into)),
(false, _) => NodeGraphExecutionResult::NotRun,
}
}
}
pub enum NodeGraphExecutionResult {
HasRun(Option<Texture>),
HasRun(Option<std::sync::Arc<wgpu::Texture>>),
NotRun,
}
+4 -4
View File
@@ -44,10 +44,10 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
pub(super) fn poll_node_graph_evaluation(&mut self) {
let mut responses = VecDeque::new();
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
&& e != "No active document"
{
tracing::error!("Error polling node graph: {}", e);
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses) {
if e != "No active document" {
tracing::error!("Error poling node graph: {}", e);
}
}
while let Some(message) = responses.pop_front() {
self.queue_editor_message(message);
+20 -10
View File
@@ -3,10 +3,9 @@ use std::path::PathBuf;
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, FileDialogOptions, FileFilter, PersistedState};
pub use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
pub use graphite_editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys, ScrollDelta};
pub use graphite_editor::messages::portfolio::ingest::utility_types::IngestAction;
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, PersistedState};
pub use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
pub use graphite_editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState as MouseState, EditorPosition as Position, MouseKeys};
pub use graphite_editor::messages::prelude::DocumentId;
pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMessage;
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
@@ -16,8 +15,9 @@ pub enum DesktopFrontendMessage {
OpenLaunchDocuments,
OpenFileDialog {
title: String,
options: FileDialogOptions,
action: IngestAction,
filters: Vec<FileFilter>,
multiple: bool,
context: OpenFileDialogContext,
},
SaveFileDialog {
title: String,
@@ -40,9 +40,6 @@ pub enum DesktopFrontendMessage {
UpdateUIScale {
scale: f64,
},
WindowUpdateDirectInput {
enabled: bool,
},
UpdateOverlays(vello::Scene),
PersistenceWriteDocument {
id: DocumentId,
@@ -87,8 +84,10 @@ pub enum DesktopWrapperMessage {
FromWeb(Box<EditorMessage>),
Wake,
Input(InputMessage),
IngestFile { path: PathBuf, content: Vec<u8>, action: IngestAction },
FileDialogResult { path: PathBuf, content: Vec<u8>, context: OpenFileDialogContext },
SaveFileDialogResult { path: PathBuf, context: SaveFileDialogContext },
OpenFile { path: PathBuf, content: Vec<u8> },
ImportFile { path: PathBuf, content: Vec<u8> },
PollNodeGraphEvaluation,
UpdateMaximized { maximized: bool },
UpdateFullscreen { fullscreen: bool },
@@ -101,6 +100,17 @@ pub enum DesktopWrapperMessage {
LoadThirdPartyLicenses { text: String },
}
pub struct FileFilter {
pub name: String,
pub extensions: Vec<String>,
}
#[derive(Clone, Copy)]
pub enum OpenFileDialogContext {
Open,
Import,
}
pub enum SaveFileDialogContext {
Document { document_id: DocumentId, content: Vec<u8> },
File { content: Vec<u8> },
+1 -1
View File
@@ -3,7 +3,7 @@ pub(crate) mod menu {
use base64::engine::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, LabeledKeyOrMouseMotion, LabeledShortcut};
use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, LabeledKeyOrMouseMotion, LabeledShortcut};
use graphite_editor::messages::input_mapper::utility_types::misc::ActionShortcut;
use graphite_editor::messages::layout::LayoutMessage;
use graphite_editor::messages::tool::tool_messages::tool_prelude::{Layout, LayoutGroup, LayoutTarget, MenuListEntry, Widget, WidgetId, WidgetRow};
+1 -3
View File
@@ -1,12 +1,10 @@
[package]
name = "document-container"
description = "Container abstraction for the on-disk side of the .gdd document format"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[features]
default = []
+2 -7
View File
@@ -1,12 +1,10 @@
[package]
name = "document-format"
description = "Typed handle for the .gdd document format, sitting over document-graph-storage and document-container"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[features]
# Runtime bridge: the editor <-> storage conversion methods (stage/commit from a `NodeNetwork`,
@@ -17,14 +15,11 @@ conversion = ["document-graph-storage/conversion", "dep:graph-craft", "dep:core-
# gates that format's `ExportFormat` arm and sink. The folder/memory codec-free core needs neither.
zip = ["document-container/zip"]
xz = ["document-container/xz"]
# Live collaboration: `Gdd` hosts or joins a `peer_transport` session and mirrors hot ops and retired history to peers.
network = ["dep:peer-transport"]
default = ["conversion", "zip", "xz", "network"]
default = ["conversion", "zip", "xz"]
[dependencies]
document-container = { workspace = true }
document-graph-storage = { workspace = true, default-features = false }
peer-transport = { workspace = true, optional = true }
graph-craft = { workspace = true, optional = true }
graphene-resource = { workspace = true }
core-types = { workspace = true, optional = true }
-4
View File
@@ -47,8 +47,4 @@ pub enum Error {
/// An export marked a resource for embedding but its bytes were absent from the byte store.
#[error("embedded resource {0} missing from the byte store")]
MissingResource(ResourceHash),
/// A packet for the collaboration session failed to encode.
#[cfg(feature = "network")]
#[error("network error: {0}")]
Network(#[from] peer_transport::PacketError),
}
+1 -12
View File
@@ -11,7 +11,7 @@ use graphene_resource::{LoadResource, Resource, ResourceHash};
use crate::error::Error;
use crate::layout::Layout;
use crate::session_state::SessionState;
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
use crate::{Gdd, MANIFEST_CODEC, io};
/// Export wrapping. Payloads keep the working copy's recorded per-payload codecs (see
/// [`crate::manifest::PayloadCodecs`]); export does not re-encode.
@@ -146,25 +146,14 @@ impl<L: Layout> Gdd<L> {
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
let session_state = SessionState {
peer_id: self.session.peer(),
user_id: self.session.user(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
// An export is a copy taken out of the room; it does not reconnect on its own.
shared: false,
next_hot_sequence: self.session.next_hot_sequence(),
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
sink.write_entry(&io::path_for(self.layout.session_basename(), codecs.session), &codecs.session.write_single(&session_state)?)?;
if !self.metadata.is_empty() {
let mut facts = Vec::new();
for fact in self.metadata.facts() {
METADATA_CODEC.append(&mut facts, &fact)?;
}
sink.write_entry(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &facts)?;
}
let working_copy_hashes: std::collections::HashSet<ResourceHash> = self.resource_hashes().await?.into_iter().collect();
-5
View File
@@ -12,8 +12,6 @@ pub trait Layout {
fn registry_basename(&self) -> &str;
fn history_basename(&self) -> &str;
fn hot_log_basename(&self) -> &str;
/// What people state about the history beside it: users and their names, later labels and tags.
fn metadata_basename(&self) -> &str;
fn resources_dir(&self) -> &str;
fn resource_path(&self, hash: &ResourceHash) -> String;
/// The embedded legacy `.graphite` document, stored verbatim during the dual-write soak so the
@@ -41,9 +39,6 @@ impl Layout for GddV1Layout {
fn hot_log_basename(&self) -> &str {
"hot-log"
}
fn metadata_basename(&self) -> &str {
"metadata"
}
fn resources_dir(&self) -> &str {
"resources"
}
+27 -129
View File
@@ -17,10 +17,10 @@ use document_container::backends::folder::FolderBackend;
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
#[cfg(feature = "conversion")]
use document_graph_storage::{CommitError, NodeMetadataSource};
use document_graph_storage::{Delta, HistoryMetadata, HotOp, MetadataFact, PeerId, Registry, Session, UserId};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::{ResourceHash, ResourceStorage};
use graphene_resource::ResourceHash;
pub mod codec;
pub mod error;
@@ -28,8 +28,6 @@ pub mod export;
pub mod io;
pub mod layout;
pub mod manifest;
#[cfg(feature = "network")]
pub mod network;
pub mod persist;
pub mod resource;
pub mod session_state;
@@ -57,8 +55,6 @@ pub const MANIFEST_CODEC: Codec = Codec::Json;
/// users who want a diffable on-disk representation. Recorded in the manifest at create time and
/// read back on open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
/// The metadata file is a log of facts appended one per line and folded on read, so nothing is ever rewritten.
pub const METADATA_CODEC: Codec = Codec::JsonLines;
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::MessagePack;
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::MessagePackFrames;
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
@@ -72,8 +68,8 @@ pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
/// read.
/// `Clone` shares the working-copy container (`Arc<AnyContainer>`) so a cloned handle reads and writes
/// the *same* on-disk/OPFS working copy — including any writes still queued on the OPFS backend. The
/// `Session` is cloned (a snapshot copy); the container is shared. A live collaboration session is
/// not carried over, so a clone is a read-only copy for asynchronous writes.
/// `Session` is cloned (a snapshot copy); the container is shared.
#[derive(Clone)]
pub struct Gdd<L: Layout = GddV1Layout> {
pub(crate) session: Session,
pub(crate) working: Arc<AnyContainer>,
@@ -82,77 +78,12 @@ pub struct Gdd<L: Layout = GddV1Layout> {
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
/// and synchronous.
pub(crate) manifest: Manifest,
/// What people state about the history: its users and their names, later labels and tags. Kept beside
/// the history in its own file, merged last-writer-wins with every copy met, never folded and never undone.
pub(crate) metadata: HistoryMetadata,
/// The wall clock as the editor last reported it, in milliseconds since the Unix epoch, so retirements can
/// record when they happened. `None` for a copy nothing ticks, the CLI or a test.
pub(crate) wall_clock_ms: Option<f64>,
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
pub(crate) view_settings: std::collections::BTreeMap<String, serde_json::Value>,
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
/// Where this document's resource bytes live. `None` means the working copy's own content-addressed
/// store, which is what a standalone handle uses. The editor points this at its application-wide
/// cache, the single store resources are kept in there.
pub(crate) byte_store: Option<Arc<dyn ResourceStorage>>,
#[cfg(feature = "network")]
pub(crate) network: Option<peer_transport::Replica>,
#[cfg(feature = "network")]
pub(crate) pending_persist: PendingPersist,
/// What peers changed since the editor last took it, so it can bring its runtime mirror into line
/// with the registry without rebuilding it.
#[cfg(feature = "network")]
pub(crate) remote_changes: network::RemoteChanges,
/// When each closed transaction was first seen here, by its marker, so the retirement policy can age
/// it. Not persisted: after a reopen everything pending is old enough.
pub(crate) transactions_seen: std::collections::HashMap<document_graph_storage::HotOpId, f64>,
/// When this peer last staged an op, so an open transaction the editor never closed can be closed
/// once it has gone quiet.
pub(crate) own_last_staged_ms: Option<f64>,
/// Whether an op of this peer's own was staged since the last policy tick.
pub(crate) own_staged_since_tick: bool,
/// Whether the document is meant to be in its room: set by sharing, cleared by disconnecting, and
/// persisted so a reopened document reconnects on its own.
pub(crate) shared: bool,
}
/// Whole-file rewrites the sync path defers to the end of a poll, so one batch of remote packets costs
/// one rewrite of each file rather than one per packet.
#[cfg(feature = "network")]
#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct PendingPersist {
pub(crate) history: bool,
pub(crate) hot_log: bool,
pub(crate) snapshot: bool,
}
impl<L: Layout + Clone> Clone for Gdd<L> {
fn clone(&self) -> Self {
Self {
session: self.session.clone(),
working: self.working.clone(),
layout: self.layout.clone(),
manifest: self.manifest.clone(),
view_settings: self.view_settings.clone(),
metadata: self.metadata.clone(),
wall_clock_ms: self.wall_clock_ms,
network_view_settings: self.network_view_settings.clone(),
byte_store: self.byte_store.clone(),
shared: self.shared,
#[cfg(feature = "network")]
network: None,
#[cfg(feature = "network")]
pending_persist: PendingPersist::default(),
#[cfg(feature = "network")]
remote_changes: network::RemoteChanges::default(),
transactions_seen: Default::default(),
own_last_staged_ms: None,
own_staged_since_tick: false,
}
}
}
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
@@ -170,10 +101,10 @@ impl<L: Layout + Default> Gdd<L> {
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
pub async fn create(path: &Path, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub async fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let working = AnyContainer::Folder(FolderBackend::create(path)?);
let layout = L::default();
Self::create_in(working, layout, peer, user, document_uuid, editor_version, stdlib_version).await
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version).await
}
}
@@ -204,40 +135,29 @@ impl<L: Layout> Gdd<L> {
true => io::read_single(&working, layout.session_basename(), codecs.session).await?,
false => SessionState::default(),
};
let metadata = match io::exists(&working, layout.metadata_basename(), METADATA_CODEC).await {
true => HistoryMetadata::fold(io::iter::<MetadataFact>(&working, layout.metadata_basename(), METADATA_CODEC).await?),
false => HistoryMetadata::default(),
};
let has_registry = io::exists(&working, layout.registry_basename(), codecs.registry).await;
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
let peer = session_state.peer_id;
// A copy written before identities were stored has no user; the peer stands for itself until one is set.
let user = match session_state.user_id {
UserId(0) => UserId(peer.0),
user => user,
};
let mut session = match (has_registry, has_history) {
(true, true) => {
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
let history = load_history(&working, &layout, codecs.history).await?;
Session::load(peer, user, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
}
(true, false) => {
// Registry-only export: synthesize a history that reproduces this state.
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
Session::bootstrap_from_registry(peer, user, registry)?
Session::bootstrap_from_registry(peer, registry)?
}
(false, _) => Session::replay_from_history(peer, user, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
(false, _) => Session::replay_from_history(peer, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
};
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
if let Some(rev) = session_state.last_broadcast_rev {
session.publish_up_to(rev);
}
// Every arm must continue this peer's authored-op count too.
session.restore_hot_sequence(session_state.next_hot_sequence);
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
@@ -248,36 +168,19 @@ impl<L: Layout> Gdd<L> {
manifest,
view_settings: session_state.view_settings,
network_view_settings: session_state.network_view_settings,
shared: session_state.shared,
metadata,
wall_clock_ms: None,
byte_store: None,
#[cfg(feature = "network")]
network: None,
#[cfg(feature = "network")]
pending_persist: PendingPersist::default(),
#[cfg(feature = "network")]
remote_changes: network::RemoteChanges::default(),
transactions_seen: Default::default(),
own_last_staged_ms: None,
own_staged_since_tick: false,
})
}
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
/// the manifest and writes each payload with its recorded codec.
pub async fn create_in(working: AnyContainer, layout: L, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
pub async fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
let codecs = manifest.codecs;
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
let session_state = SessionState {
peer_id: peer,
user_id: user,
..Default::default()
};
let session_state = SessionState { peer_id: peer, ..Default::default() };
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
let session = Session::with_identity(peer, user);
let session = Session::with_peer(peer);
io::write_single(&working, layout.registry_basename(), codecs.registry, session.registry())?;
Ok(Self {
@@ -287,19 +190,6 @@ impl<L: Layout> Gdd<L> {
manifest,
view_settings: std::collections::BTreeMap::new(),
network_view_settings: std::collections::BTreeMap::new(),
metadata: HistoryMetadata::default(),
wall_clock_ms: None,
byte_store: None,
shared: false,
#[cfg(feature = "network")]
network: None,
#[cfg(feature = "network")]
pending_persist: PendingPersist::default(),
#[cfg(feature = "network")]
remote_changes: network::RemoteChanges::default(),
transactions_seen: Default::default(),
own_last_staged_ms: None,
own_staged_since_tick: false,
})
}
}
@@ -402,16 +292,24 @@ impl<L: Layout> Gdd<L> {
(working, self.layout)
}
/// Resolve every proto-node declaration referenced by the registry or its history into a
/// [`document_graph_storage::Declarations`] map, loading each `ProtoNode`'s bytes from `byte_store`
/// (the global cache in the editor, the working-copy container for standalone). Covers history so
/// the map can serve any undo/redo target. Cold-path (mount / open); async because resource loads are.
/// Resolve the proto-node declarations referenced by the registry into a [`document_graph_storage::Declarations`]
/// map, loading each `ProtoNode`'s bytes from `byte_store` (the global cache in the editor, the
/// working-copy container for standalone). Only resources referenced by `Implementation::ProtoNode`
/// are visited, so image/font resources are skipped. Cold-path (open / `to_runtime`); async
/// because resource loads are.
#[cfg(feature = "conversion")]
pub async fn declarations(&self, byte_store: &dyn LoadResource) -> document_graph_storage::Declarations {
use document_graph_storage::Implementation;
let registry = self.session.registry();
let mut declarations = document_graph_storage::Declarations::new();
for (id, hash) in self.session.all_declaration_resources() {
let Some(hash) = hash else {
for node in registry.node_instances.values() {
let Implementation::ProtoNode(id) = node.implementation() else { continue };
if declarations.contains_key(id) {
continue;
}
let Some(hash) = registry.resources.get(id).and_then(|entry| entry.hash) else {
log::error!("Declaration resource {id} has no resolved hash; cannot load ProtoNode");
continue;
};
@@ -421,7 +319,7 @@ impl<L: Layout> Gdd<L> {
};
match document_graph_storage::decode_declaration(resource.as_ref()) {
Ok(proto) => {
declarations.insert(id, proto);
declarations.insert(*id, proto);
}
Err(error) => log::error!("Failed to deserialize ProtoNode for {id}: {error}"),
}
-372
View File
@@ -1,372 +0,0 @@
//! Live collaboration on the [`Gdd`] handle. `share` / `join` attach a [`Replica`]; the persist path
//! then broadcasts staged hot ops and (as host) retired deltas, and `poll_peers` applies what peers
//! send through the [`SyncTarget`] impl below, which persists inbound state the same way local
//! edits are.
use std::collections::HashSet;
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, RegistryDelta, ResourceHash, RetiredHotOps, Rev, Session, Touched, UserId};
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, Transport};
use crate::error::Error;
use crate::layout::Layout;
use crate::{Gdd, PendingPersist};
/// What peers changed in the working registry since the editor last asked. The editor keeps a runtime
/// mirror of the registry and brings just the touched entities back into line, unless the registry was
/// rederived wholesale, when the touched set no longer bounds what changed.
#[derive(Clone, Debug, Default)]
pub struct RemoteChanges {
pub touched: Touched,
/// The working registry was replaced wholesale by a full sync, so the mirror has to be rebuilt from it.
pub rebuilt: bool,
}
impl RemoteChanges {
pub fn is_empty(&self) -> bool {
self.touched.is_empty() && !self.rebuilt
}
pub fn extend(&mut self, other: RemoteChanges) {
self.touched.extend(other.touched);
self.rebuilt |= other.rebuilt;
}
}
impl<L: Layout> Gdd<L> {
/// Takes what peers changed since the last call. Empty when nothing did.
pub fn take_remote_changes(&mut self) -> RemoteChanges {
std::mem::take(&mut self.remote_changes)
}
}
impl<L: Layout> Gdd<L> {
pub fn share(&mut self, transport: impl Transport + 'static, user: UserId) {
self.network = Some(Replica::host(transport, self.session.peer(), user));
}
/// Connect to the room every copy of this document shares, host or guest as the room calls for, and
/// remember that the document is shared so a reopen reconnects on its own.
pub fn connect(&mut self, transport: impl Transport + 'static, user: UserId) -> Result<(), Error> {
self.network = Some(Replica::connect(transport, self.session.peer(), user));
self.shared = true;
self.persist_session_state()
}
/// Whether the document is meant to be in its room; see [`connect`](Self::connect).
pub fn is_shared(&self) -> bool {
self.shared
}
/// For a connection still undecided after the grace period: take the host role if no host is there. See
/// [`Replica::decide_role`].
pub fn decide_role(&mut self) -> Option<Role> {
self.network.as_mut().and_then(Replica::decide_role)
}
pub fn join(&mut self, transport: impl Transport + 'static, user: UserId) {
self.network = Some(Replica::guest(transport, self.session.peer(), user));
}
/// Leaves the room. A host retires every closed transaction first, so what peers finished is in
/// history before the retirer goes away.
pub fn leave(&mut self) {
self.shared = false;
if let Err(error) = self.persist_session_state() {
log::error!("Persisting the session state before leaving failed: {error}");
}
self.disconnect();
}
/// Drops the connection but keeps the document shared, for a transport that went down: a reopen
/// reconnects on its own, and the Session panel offers to reconnect now.
pub fn disconnect(&mut self) {
let closed = self.session.closed_transactions();
if let Err(error) = self.retire_transactions(&closed) {
log::error!("Retiring before leaving failed: {error}");
}
if let Some(mut replica) = self.network.take() {
replica.leave();
}
}
pub fn role(&self) -> Option<Role> {
self.network.as_ref().map(Replica::role)
}
pub fn is_synced(&self) -> bool {
self.network.as_ref().is_none_or(Replica::is_synced)
}
/// Announce this peer's display name to the room; a no-op when it has not changed or nobody is connected.
pub fn set_name(&mut self, name: &str) -> Result<(), Error> {
if let Some(replica) = &mut self.network {
replica.set_name(name)?;
}
Ok(())
}
/// Send this peer's pointer position, `None` when it left the viewport.
pub fn send_cursor(&mut self, position: Option<peer_transport::CursorPosition>) -> Result<(), Error> {
if let Some(replica) = &mut self.network {
replica.send_cursor(position)?;
}
Ok(())
}
/// The other peers in the room; empty when the document is not connected.
pub fn peers(&self) -> Vec<peer_transport::RemotePeer> {
self.network.as_ref().map(|replica| replica.peers().cloned().collect()).unwrap_or_default()
}
/// Record that the runtime was rebuilt from the registry, so the next staged diff is taken against it.
pub fn mark_runtime_current(&mut self) {
self.session.mark_runtime_current();
}
pub fn poll_peers(&mut self) -> Vec<Event> {
let Some(mut replica) = self.network.take() else { return Vec::new() };
let events = replica.poll(self);
self.network = Some(replica);
events
}
/// Answer an [`Event::ResourceRequested`].
pub fn send_resource(&mut self, to: peer_transport::TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), Error> {
if let Some(replica) = &mut self.network {
replica.send_resource(to, hash, bytes)?;
}
Ok(())
}
}
impl<L: Layout> SyncTarget for Gdd<L> {
fn peer(&self) -> PeerId {
self.session.peer()
}
fn document_id(&self) -> Option<u64> {
Some(self.manifest.document_id)
}
fn adopt_document_id(&mut self, document_id: u64) -> Result<(), TargetError> {
self.update_manifest(|manifest| manifest.document_id = document_id)?;
Ok(())
}
fn head(&self) -> Option<Rev> {
self.session.head_rev()
}
fn retired_registry(&self) -> Registry {
self.session.retired_registry().clone()
}
fn hot_log(&self) -> Vec<HotOp> {
self.session.hot_log().to_vec()
}
fn known_revs(&self) -> Vec<Rev> {
self.session.known_revs()
}
fn contains_rev(&self, rev: Rev) -> bool {
self.session.delta(rev).is_some()
}
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta> {
<Session as SyncTarget>::deltas_unknown_to(&self.session, known)
}
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
self.session.load(registry, history, head)?;
self.remote_changes.rebuilt = true;
self.pending_persist = PendingPersist {
history: true,
hot_log: true,
snapshot: true,
};
Ok(())
}
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
// An op naming an entity that has not arrived here yet is handed back for a later retry, so only
// what actually applied reaches the hot frame log.
let mut deferred = Vec::new();
for hot_op in ops {
// Recorded whether or not it applies: a failed apply can still have resurrected what it references.
self.remote_changes.touched.record(&hot_op.op);
if self.session.replay_hot_op(hot_op.clone()).is_err() {
deferred.push(hot_op);
continue;
}
self.append_hot_frame(&hot_op)?;
}
Ok(deferred)
}
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId], head: Option<Rev>) -> Result<(), TargetError> {
let incoming: HashSet<Rev> = deltas.iter().map(|delta| delta.id).collect();
let length_before = self.session.history_len();
for delta in &deltas {
self.remote_changes.touched.record(&delta.kind);
}
SyncTarget::merge_remote(&mut self.session, deltas, retires, head)?;
// Whatever a peer sent is shared by definition, so it sits behind the published frontier too: a
// guest must no more silently rewind the host's history than the host may rewind its own.
if let Some(head) = self.session.head_rev() {
self.session.publish_up_to(head);
}
// A batch that extended canonical history at the end, with any merge delta joining it there, extends
// the file the same way. One that sorted earlier deltas after it rewrites the file.
let tail: Vec<Rev> = self.session.history().skip(length_before).map(|delta| delta.id).collect();
let appended = tail
.iter()
.all(|&rev| incoming.contains(&rev) || self.session.delta(rev).is_some_and(|delta| matches!(delta.kind, RegistryDelta::Merge { .. })));
match appended {
true => self.append_history_deltas(&tail)?,
false => self.pending_persist.history = true,
}
self.pending_persist.hot_log |= !retires.is_empty();
self.pending_persist.snapshot = true;
Ok(())
}
fn merge_divergent(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<Vec<Delta>, TargetError> {
let length_before = self.session.history_len();
for delta in &deltas {
self.remote_changes.touched.record(&delta.kind);
}
let absorbed = SyncTarget::merge_divergent(&mut self.session, deltas, retires)?;
if let Some(head) = self.session.head_rev() {
self.session.publish_up_to(head);
}
// The absorbed deltas and the merge joining them are the batch; a sort that moved earlier deltas
// after them rewrites the file.
let absorbed_ids: HashSet<Rev> = absorbed.iter().map(|delta| delta.id).collect();
let tail: Vec<Rev> = self.session.history().skip(length_before).map(|delta| delta.id).collect();
match tail.iter().all(|rev| absorbed_ids.contains(rev)) {
true => self.append_history_deltas(&tail)?,
false => self.pending_persist.history = true,
}
self.pending_persist.hot_log |= !retires.is_empty();
self.pending_persist.snapshot = true;
Ok(absorbed)
}
fn retired_marks(&self) -> RetiredHotOps {
SyncTarget::retired_marks(&self.session)
}
fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError> {
SyncTarget::absorb_retired_marks(&mut self.session, remote)?;
self.pending_persist.hot_log = true;
Ok(())
}
fn retracted_marks(&self) -> RetiredHotOps {
SyncTarget::retracted_marks(&self.session)
}
fn absorb_retracted_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError> {
let touched = self.session.absorb_retracted_marks(remote);
if !touched.is_empty() {
self.remote_changes.touched.extend(touched);
self.pending_persist.hot_log = true;
self.pending_persist.snapshot = true;
}
Ok(())
}
fn metadata(&self) -> HistoryMetadata {
self.metadata.clone()
}
fn absorb_metadata(&mut self, remote: &HistoryMetadata) -> Result<bool, TargetError> {
let landed = self.metadata.merge(remote);
if landed.is_empty() {
return Ok(false);
}
self.append_facts(&landed)?;
Ok(true)
}
fn retract_hot_ops(&mut self, ops: &[HotOpId]) -> Result<(), TargetError> {
let touched = self.session.retract_hot_ops(ops);
self.remote_changes.touched.extend(touched);
self.pending_persist.hot_log = true;
self.pending_persist.snapshot = true;
Ok(())
}
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
let (moved, touched) = self.session.drop_interaction(rev)?;
self.remote_changes.touched.extend(touched);
self.pending_persist.history = true;
self.pending_persist.hot_log = true;
self.pending_persist.snapshot = true;
Ok(moved)
}
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError> {
let revs = self.session.restore_interaction(rev)?;
let deltas: Vec<Delta> = revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
for delta in &deltas {
self.remote_changes.touched.record(&delta.kind);
}
if let Some(&last) = revs.last() {
self.session.publish_up_to(last);
}
self.pending_persist.history = true;
self.pending_persist.snapshot = true;
Ok(deltas)
}
fn apply_head_move(&mut self, moved: &HeadMove) -> Result<(), TargetError> {
let touched = self.session.apply_head_move(moved)?;
self.remote_changes.touched.extend(touched);
if let Some(head) = self.session.head_rev() {
self.session.publish_up_to(head);
}
self.pending_persist.history = true;
self.pending_persist.hot_log = true;
self.pending_persist.snapshot = true;
Ok(())
}
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
let (moved, touched) = self.session.move_head_to(rev)?;
self.remote_changes.touched.extend(touched);
self.pending_persist.snapshot = true;
Ok(moved)
}
fn flush(&mut self) -> Result<(), TargetError> {
let pending = std::mem::take(&mut self.pending_persist);
if pending.history {
self.rewrite_history()?;
}
if pending.hot_log {
self.rewrite_hot_log()?;
}
if pending.snapshot {
self.persist_registry_snapshot()?;
self.persist_session_state()?;
}
Ok(())
}
fn missing_resources(&self) -> HashSet<ResourceHash> {
self.unstored_resources().into_iter().collect()
}
fn store_resource(&mut self, _hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
self.hold_resource(bytes)?;
Ok(())
}
}
+55 -403
View File
@@ -6,7 +6,7 @@
use document_container::AsyncContainer;
#[cfg(feature = "conversion")]
use document_graph_storage::NodeMetadataSource;
use document_graph_storage::{Delta, HistoryMetadata, HotOp, MetadataFact, RegistryDelta, Rev, TimeStamp, UserId, WallStamp};
use document_graph_storage::{HotOp, Rev, TimeStamp};
#[cfg(feature = "conversion")]
use graphene_resource::ResourceStorage;
@@ -14,7 +14,7 @@ use crate::error::Error;
use crate::layout::Layout;
use crate::manifest::Manifest;
use crate::session_state::SessionState;
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
use crate::{Gdd, MANIFEST_CODEC, io};
impl<L: Layout> Gdd<L> {
/// Move the undo cursor back one commit (silent-zone reflog undo) and persist the new cursor. Returns
@@ -36,16 +36,6 @@ impl<L: Layout> Gdd<L> {
}
/// Edit the cached manifest and persist it. Always JSON, synchronous.
/// The person using this device, from the editor's preferences. A change registers the peer again on
/// its next staged batch, and the newer registration wins everywhere.
pub fn set_user(&mut self, user: UserId) -> Result<(), Error> {
if self.session.user() == user {
return Ok(());
}
self.session.set_user(user);
self.persist_session_state()
}
pub fn update_manifest(&mut self, edit: impl FnOnce(&mut Manifest)) -> Result<(), Error> {
edit(&mut self.manifest);
io::write_single(&self.working, self.layout.manifest_basename(), MANIFEST_CODEC, &self.manifest)?;
@@ -57,7 +47,7 @@ impl<L: Layout> Gdd<L> {
/// declaration bytes. The working registry reflects the edit immediately, but nothing enters durable
/// retired history until [`retire_pending_interaction`](Self::retire_pending_interaction). Staging on
/// every edit while retiring only at interaction boundaries lets several edits coalesce into one retired
/// interaction. Returns the decoded declarations the snapshot references, for the caller's cache.
/// interaction.
///
/// # Errors
/// [`Error::Commit`] if the runtime diff is rejected by the session. On an [`Error::Container`] /
@@ -70,61 +60,33 @@ impl<L: Layout> Gdd<L> {
metadata: &M,
resources: &graphene_resource::ResourceRegistry,
byte_store: &dyn ResourceStorage,
) -> Result<document_graph_storage::Declarations, Error> {
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
self.persist_staged(&hot_ops)?;
) -> Result<(), Error> {
let (hot_ops, declaration_bytes) = self.session.stage_from_runtime(network, metadata, resources)?;
for hot_op in &hot_ops {
self.append_hot_frame(hot_op)?;
}
// Persist proto-node declaration content to the byte store (the global cache in the editor,
// the working-copy container for standalone export). Content-addressed, so re-storing
// identical bytes on every commit is an idempotent no-op.
for bytes in conversion.declaration_bytes.values() {
byte_store.store(bytes);
}
Ok(conversion.declarations)
}
/// Stage ops the caller built from what the editor recorded, rather than deriving them by converting
/// the whole document and diffing it against the working registry.
///
/// Otherwise identical to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot): each op becomes a
/// hot frame, is broadcast to any session, and the proto-node declaration bytes go to the byte store.
#[cfg(feature = "conversion")]
pub fn stage_constructed_ops(
&mut self,
ops: Vec<document_graph_storage::RegistryDelta>,
declaration_bytes: &document_graph_storage::from_runtime::DeclarationBytes,
byte_store: &dyn ResourceStorage,
) -> Result<Vec<HotOp>, Error> {
let hot_ops = self.stage_ops(ops)?;
for bytes in declaration_bytes.values() {
byte_store.store(bytes);
}
Ok(hot_ops)
}
/// Stage raw registry ops as hot ops, for callers that don't go through the runtime diff.
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, Error> {
let hot_ops = self.session.stage_ops(ops)?;
self.persist_staged(&hot_ops)?;
Ok(hot_ops)
}
/// Every staged hot op takes this path, whether it came from a recorded batch, a whole-document diff or
/// a raw op: the frame that survives a crash, then the broadcast that reaches the room.
fn persist_staged(&mut self, hot_ops: &[HotOp]) -> Result<(), Error> {
if hot_ops.iter().any(|hot_op| !matches!(hot_op.op, RegistryDelta::EndTransaction)) {
self.own_staged_since_tick = true;
}
for hot_op in hot_ops {
self.append_hot_frame(hot_op)?;
}
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
replica.broadcast_hot_ops(hot_ops)?;
}
Ok(())
}
/// Retire every pending hot op into durable history as a single interaction (marking the batch's last
/// delta as the interaction boundary), then re-snapshot the registry. One interaction is one undo unit,
/// so the caller invokes this at each undo-step boundary and before any undo/redo. A no-op when there
/// are no pending hot ops.
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
let Some(up_to) = self.session.hot_log().iter().map(|hot_op| hot_op.timestamp).max() else {
return Ok(Vec::new());
};
self.retire_inner(up_to, true)
}
/// Commit a runtime snapshot as one complete interaction: stage it, then immediately retire it into
/// durable history. Convenience for callers that produce a whole interaction atomically (tests, and any
/// one-shot commit). Equivalent to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot) followed
@@ -154,34 +116,24 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// Persist freshly-staged hot ops and immediately retire exactly them into durable history as one unit.
/// Appends each hot frame first, so a crash before retirement still recovers the work. Returns the
/// retired `Rev`s. A no-op when nothing was staged, and the ops stay hot on a peer that does not retire.
/// Persist freshly-staged hot ops and immediately retire them into durable history. Appends each
/// hot frame (so a crash before retirement still recovers the work), then retires up to the last
/// staged timestamp, which drains exactly these ops and re-snapshots the registry. Returns the
/// retired `Rev`s. A no-op when nothing was staged.
pub(crate) fn append_and_retire(&mut self, hot_ops: &[HotOp], interaction_end: bool) -> Result<Vec<Rev>, Error> {
if hot_ops.is_empty() {
return Ok(Vec::new());
}
let Some(last) = hot_ops.last() else { return Ok(Vec::new()) };
for hot_op in hot_ops {
self.append_hot_frame(hot_op)?;
}
if !self.retires_locally() {
return Ok(Vec::new());
}
let ids: Vec<_> = hot_ops.iter().map(HotOp::id).collect();
let revs = self.session.retire_hot_ops(&ids)?;
// Marked before the history frames are written, so the boundary is on disk with them.
if interaction_end && let Some(&last) = revs.last() {
self.session.mark_interaction_end(last);
}
self.finish_retirement(&revs, &ids)?;
Ok(revs)
self.retire_inner(last.timestamp, interaction_end)
}
/// Encode the history deltas identified by `revs` and append them to the history file. `revs` comes
/// from `Session::retire` in append order, which is a valid replay order, so a direct per-rev lookup
/// preserves replay order without scanning the whole history.
pub(crate) fn append_history_deltas(&mut self, revs: &[Rev]) -> Result<(), Error> {
fn append_history_deltas(&mut self, revs: &[Rev]) -> Result<(), Error> {
let mut buffer = Vec::new();
for &rev in revs {
let Some(delta) = self.session.delta(rev) else {
@@ -196,7 +148,7 @@ impl<L: Layout> Gdd<L> {
/// Set a local annotation (e.g. a commit message) on an existing retired delta and re-persist it.
/// Unlike the per-interaction marker written inline at retire, this targets an already-written delta, so
/// the whole history file is rewritten in topological order. O(history), fine for occasional user
/// the whole history file is rewritten in topological order. O(history) — fine for occasional user
/// labeling, not for per-interaction marking (which uses the inline path). No-op if `rev` is unknown.
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> Result<(), Error> {
if self.session.annotate_delta(rev, key, value) {
@@ -207,7 +159,7 @@ impl<L: Layout> Gdd<L> {
/// Rewrite the entire history file from the in-memory session. `history()` yields deltas in
/// topological (append) order, which is a valid replay order, so no separate sort is needed.
pub(crate) fn rewrite_history(&mut self) -> Result<(), Error> {
fn rewrite_history(&mut self) -> Result<(), Error> {
let mut buffer = Vec::new();
for delta in self.session.history() {
self.manifest.codecs.history.append(&mut buffer, delta)?;
@@ -216,67 +168,13 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// What people state about the history: users and their names, later labels and tags.
pub fn metadata(&self) -> &HistoryMetadata {
&self.metadata
}
/// State a fact about a user, `wall_ms` being now on the wall clock: put on record, persisted, and told
/// to the room when it changed anything. Returns whether it did.
pub fn record_user_attribute(&mut self, user: UserId, key: &str, value: serde_json::Value, wall_ms: f64) -> Result<bool, Error> {
let stamp = WallStamp {
ms: wall_ms.max(0.) as u64,
peer: self.session.peer(),
};
let Some(fact) = self.metadata.set_user_attribute(user, key, value, stamp) else {
return Ok(false);
};
self.append_facts(&[fact])?;
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
replica.send_metadata(&self.metadata)?;
}
Ok(true)
}
/// State a fact about a rev, the interaction it closes in the History panel's terms: a label or a tag. Put on
/// record, appended to the file, and told to the room when it changed anything. Returns whether it did.
pub fn record_rev_attribute(&mut self, rev: Rev, key: &str, value: serde_json::Value, wall_ms: f64) -> Result<bool, Error> {
let stamp = WallStamp {
ms: wall_ms.max(0.) as u64,
peer: self.session.peer(),
};
let Some(fact) = self.metadata.set_rev_attribute(rev, key, value, stamp) else {
return Ok(false);
};
self.append_facts(&[fact])?;
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
replica.send_metadata(&self.metadata)?;
}
Ok(true)
}
/// Append facts to the metadata file, one line each; the file is never rewritten.
pub(crate) fn append_facts(&mut self, facts: &[MetadataFact]) -> Result<(), Error> {
let mut buffer = Vec::new();
for fact in facts {
METADATA_CODEC.append(&mut buffer, fact)?;
}
self.working.append_non_blocking(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &buffer)?;
Ok(())
}
pub(crate) fn persist_session_state(&mut self) -> Result<(), Error> {
fn persist_session_state(&mut self) -> Result<(), Error> {
let state = SessionState {
peer_id: self.session.peer(),
user_id: self.session.user(),
head_rev: self.session.head_rev(),
last_broadcast_rev: self.session.last_broadcast_rev(),
redo_stack: self.session.redo_stack().to_vec(),
next_node_counter: self.session.next_node_counter(),
next_hot_sequence: self.session.next_hot_sequence(),
shared: self.shared,
view_settings: self.view_settings.clone(),
network_view_settings: self.network_view_settings.clone(),
};
@@ -288,7 +186,7 @@ impl<L: Layout> Gdd<L> {
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
pub(crate) fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
Ok(())
}
@@ -317,291 +215,45 @@ impl<L: Layout> Gdd<L> {
self.persist_session_state()
}
pub(crate) fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
let mut buffer = Vec::new();
self.manifest.codecs.hot_log.append(&mut buffer, op)?;
self.working.append_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
Ok(())
}
/// How many closed transactions have to be waiting before they retire. Later retirement fuses more
/// of a gesture's ops into one delta and keeps more of what an undo can still rewind silently.
pub const RETIRE_AFTER_TRANSACTIONS: usize = 10;
/// How long a closed transaction sits before it may retire, so every peer has seen all of it.
pub const RETIRE_MIN_AGE_MS: f64 = 2_000.0;
/// How long anything waits at most: a quiet session still retires, and a transaction with a gap in
/// its author's run retires with what arrived.
pub const RETIRE_MAX_AGE_MS: f64 = 60_000.0;
/// Closes this peer's open transaction, if it has one, with a marker that reaches the room like any
/// other hot op. The editor calls this at each undo-step boundary.
pub fn end_transaction(&mut self) -> Result<(), Error> {
let staged = self.session.end_transaction()?;
self.persist_staged(&staged)?;
Ok(())
}
/// Undo this peer's latest transaction while it is still hot: the ops leave the hot log here and, once
/// the retraction reaches them, on every peer, and they never retire. Returns whether there was a hot
/// transaction to take back; `false` means the step already retired and undo has to move the cursor.
/// What the ops named lands in the remote changes, so a mirror brings those entities into line with
/// whatever others wrote to them meanwhile.
pub fn retract_transaction(&mut self) -> Result<Option<Vec<RegistryDelta>>, Error> {
let Some(document_graph_storage::Retraction { ids, touched, ops }) = self.session.retract_transaction()? else {
return Ok(None);
};
self.own_last_staged_ms = None;
#[cfg(feature = "network")]
self.remote_changes.touched.extend(touched);
#[cfg(not(feature = "network"))]
let _ = touched;
self.rewrite_hot_log()?;
self.persist_registry_snapshot()?;
self.persist_session_state()?;
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
replica.broadcast_retraction(&ids)?;
}
#[cfg(not(feature = "network"))]
let _ = ids;
Ok(Some(ops))
}
/// Undo this peer's latest retired step in a session, the one [`Session::latest_own_interaction`]
/// names. The retirer drops it out of the shared line itself and tells the room, and what the step
/// named lands in the remote changes for the mirror to follow; anyone else asks the retirer, and the
/// head move comes back through the poll like any remote change. `None` when this peer has no retired
/// step of its own on the line.
#[cfg(feature = "network")]
pub fn undo_retired_step(&mut self) -> Result<Option<Rev>, Error> {
let Some(rev) = self.session.latest_own_interaction() else {
return Ok(None);
};
self.drop_step(rev)?;
Ok(Some(rev))
}
/// Drop any retired interaction out of the line, by the retirer directly or on request, the later steps minted
/// again on its parent; see [`Session::drop_interaction`]. What it named lands in the remote changes for the
/// mirror to follow. Works alone too, where this peer is its own retirer.
#[cfg(feature = "network")]
pub fn drop_step(&mut self, rev: Rev) -> Result<(), Error> {
if self.retires_locally() {
let (moved, touched) = self.session.drop_interaction(rev)?;
self.remote_changes.touched.extend(touched);
if let Some(head) = self.session.head_rev() {
self.session.publish_up_to(head);
}
self.rewrite_history()?;
self.rewrite_hot_log()?;
self.persist_registry_snapshot()?;
self.persist_session_state()?;
if let Some(replica) = &mut self.network {
replica.broadcast_head_move(moved)?;
}
} else if let Some(replica) = &mut self.network {
replica.request_undo(rev, false)?;
}
Ok(())
}
/// Move the head to an ancestor in a session, everything since staying as a branch; see
/// [`Session::move_head_to`]. The retirer does it and tells the room; anyone else asks the retirer.
#[cfg(feature = "network")]
pub fn move_head(&mut self, rev: Rev) -> Result<(), Error> {
if self.retires_locally() {
let (moved, touched) = self.session.move_head_to(rev)?;
self.remote_changes.touched.extend(touched);
if let Some(head) = self.session.head_rev() {
self.session.publish_up_to(head);
}
self.persist_registry_snapshot()?;
self.persist_session_state()?;
if let Some(replica) = &mut self.network {
replica.broadcast_head_move(moved)?;
}
} else if let Some(replica) = &mut self.network {
replica.request_move(rev)?;
}
Ok(())
}
/// Redo a step [`undo_retired_step`](Self::undo_retired_step) dropped: it comes back as a copy on top
/// of the line, by the retirer, directly or on request.
#[cfg(feature = "network")]
pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> {
if self.retires_locally() {
let revs = self.session.restore_interaction(rev)?;
let deltas: Vec<Delta> = revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
for delta in &deltas {
self.remote_changes.touched.record(&delta.kind);
}
if let Some(&last) = revs.last() {
self.session.publish_up_to(last);
}
self.rewrite_history()?;
self.rewrite_hot_log()?;
self.persist_registry_snapshot()?;
self.persist_session_state()?;
if let Some(replica) = &mut self.network {
replica.broadcast_retired(&deltas, &[])?;
}
} else if let Some(replica) = &mut self.network {
replica.request_undo(rev, true)?;
}
Ok(())
}
/// Stage ops a retraction took back, as a fresh transaction, noting what they name as a change for the
/// mirror to follow: the redo of a step taken back is a new edit to everyone, this peer included.
pub fn restage_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<(), Error> {
#[cfg(feature = "network")]
for op in &ops {
self.remote_changes.touched.record(op);
}
self.stage_ops(ops)?;
Ok(())
}
/// Retire every transaction the policy says is due at `now_ms`, on any monotonic millisecond clock the
/// caller keeps: closed transactions that have waited [`RETIRE_MIN_AGE_MS`](Self::RETIRE_MIN_AGE_MS),
/// once [`RETIRE_AFTER_TRANSACTIONS`](Self::RETIRE_AFTER_TRANSACTIONS) of them are waiting or the oldest
/// has waited [`RETIRE_MAX_AGE_MS`](Self::RETIRE_MAX_AGE_MS). An open transaction never retires, whoever
/// its author is. Called once a frame by the editor with whether it is between steps; a peer that does
/// not retire only closes its own transaction here, once it has gone quiet for the minimum age.
pub fn retire_due(&mut self, now_ms: f64, idle: bool) -> Result<Vec<Rev>, Error> {
// The editor's clock is the wall clock; retirements record it as the time a step happened.
self.wall_clock_ms = Some(now_ms);
// A gesture the editor never closed, or one interrupted by a reopen, closes on its own once quiet,
// but only while the editor is between steps: a pause inside a gesture must not split it, since undo
// takes a whole transaction back.
if self.own_staged_since_tick {
self.own_staged_since_tick = false;
self.own_last_staged_ms = Some(now_ms);
} else if idle && self.own_last_staged_ms.is_some_and(|last| now_ms - last >= Self::RETIRE_MIN_AGE_MS) {
self.end_transaction()?;
self.own_last_staged_ms = None;
}
if !self.retires_locally() {
return Ok(Vec::new());
}
let closed = self.session.closed_transactions();
let mut seen = std::mem::take(&mut self.transactions_seen);
let mut due = Vec::new();
let mut oldest_age: f64 = 0.0;
for transaction in &closed {
let Some(&marker) = transaction.ops.last() else { continue };
let age = now_ms - *seen.entry(marker).or_insert(now_ms);
if age >= Self::RETIRE_MIN_AGE_MS && (transaction.contiguous || age >= Self::RETIRE_MAX_AGE_MS) {
due.push(transaction.clone());
oldest_age = oldest_age.max(age);
}
}
seen.retain(|marker, _| closed.iter().any(|transaction| transaction.ops.last() == Some(marker)));
self.transactions_seen = seen;
if due.len() >= Self::RETIRE_AFTER_TRANSACTIONS || oldest_age >= Self::RETIRE_MAX_AGE_MS {
self.retire_transactions(&due)
} else {
Ok(Vec::new())
}
}
/// Close this peer's open transaction and retire every closed transaction, whoever its author is,
/// leaving other authors' open ones hot. The undo path takes this before moving the cursor, so the
/// interaction being undone is in history; a peer that does not retire only closes its own.
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
self.end_transaction()?;
self.own_last_staged_ms = None;
let closed = self.session.closed_transactions();
self.retire_transactions(&closed)
}
/// Retire the given closed transactions, each as one interaction, in one history append and one
/// broadcast. A no-op for a peer that leaves retirement to the session host.
pub fn retire_transactions(&mut self, transactions: &[document_graph_storage::ClosedTransaction]) -> Result<Vec<Rev>, Error> {
if !self.retires_locally() || transactions.is_empty() {
return Ok(Vec::new());
}
let mut revs = Vec::new();
let mut retired_hot_ops = Vec::new();
for transaction in transactions {
revs.extend(self.session.retire_transaction(transaction)?);
retired_hot_ops.extend(transaction.ops.iter().copied());
}
self.finish_retirement(&revs, &retired_hot_ops)?;
Ok(revs)
}
/// Working-copy checkpoint over a timestamp: promote every hot op stamped at or before `up_to` into
/// retired deltas, whatever its author and whether or not its transaction is closed. For callers
/// that own the whole log; a session retires by [`retire_transactions`](Self::retire_transactions).
/// Working-copy checkpoint: promote hot ops with timestamp `≤ up_to` into retired deltas,
/// append them to the history file, rewrite the hot log with remaining (unretired) ops, and
/// re-snapshot the registry. Synchronous.
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, Error> {
if !self.retires_locally() {
return Ok(Vec::new());
}
let retired_hot_ops = self.session.hot_ops_up_to(up_to);
let revs = self.session.retire(up_to)?;
self.finish_retirement(&revs, &retired_hot_ops)?;
Ok(revs)
self.retire_inner(up_to, false)
}
/// What every retirement ends with: the published frontier moves, the deltas reach the history file,
/// the hot log and snapshot are rewritten, and the room hears about it.
fn finish_retirement(&mut self, new_revs: &[Rev], retired_hot_ops: &[document_graph_storage::HotOpId]) -> Result<(), Error> {
// Stamped before the frames are written, so the time is on disk with them and goes out with the broadcast.
if let Some(wall_ms) = self.wall_clock_ms
&& !new_revs.is_empty()
{
self.session.stamp_retired_at(new_revs, wall_ms as u64);
}
// In a session these deltas are about to reach peers, so the published frontier moves with them.
// Rewinding a commit peers already hold would diverge from them for good, with nothing on the wire
// to tell them, so undo past this point has to go through forward inverse ops instead. Set before
// the persists below so the frontier survives a reopen.
#[cfg(feature = "network")]
if self.network.is_some()
&& let Some(&last) = new_revs.last()
{
self.session.publish_up_to(last);
/// `interaction_end`: mark the batch's last delta as an interaction boundary (one undo unit) before its
/// history frame is written, so the marker persists on reopen without a later frame rewrite.
fn retire_inner(&mut self, up_to: TimeStamp, interaction_end: bool) -> Result<Vec<Rev>, Error> {
let new_revs = self.session.retire(up_to)?;
// Mark before `append_history_deltas` so the on-disk frame carries the boundary.
if interaction_end && let Some(&last) = new_revs.last() {
self.session.mark_interaction_end(last);
}
if !new_revs.is_empty() {
self.append_history_deltas(new_revs)?;
self.append_history_deltas(&new_revs)?;
}
self.rewrite_hot_log()?;
// Rewrite hot log with whatever survived retirement.
let mut hot_buffer = Vec::new();
for hot_op in self.session.hot_log() {
self.manifest.codecs.hot_log.append(&mut hot_buffer, hot_op)?;
}
self.working
.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &hot_buffer)?;
self.persist_registry_snapshot()?;
self.persist_session_state()?;
#[cfg(feature = "network")]
if let Some(replica) = &mut self.network {
let deltas: Vec<_> = new_revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
replica.broadcast_retired(&deltas, retired_hot_ops)?;
}
#[cfg(not(feature = "network"))]
let _ = retired_hot_ops;
Ok(())
}
/// Guests leave retirement to the session host and keep their hot ops until the host's retired
/// deltas arrive.
fn retires_locally(&self) -> bool {
#[cfg(feature = "network")]
{
self.network.as_ref().is_none_or(|replica| replica.role() == peer_transport::Role::Host)
}
#[cfg(not(feature = "network"))]
true
}
pub(crate) fn rewrite_hot_log(&mut self) -> Result<(), Error> {
let mut buffer = Vec::new();
for hot_op in self.session.hot_log() {
self.manifest.codecs.hot_log.append(&mut buffer, hot_op)?;
}
self.working.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
Ok(())
Ok(new_revs)
}
}
-36
View File
@@ -91,36 +91,6 @@ impl<L: Layout> Gdd<L> {
{
ResourceProxy(self.working.clone(), self.layout.clone())
}
/// Point resource lookups at an external store instead of the working copy, for an embedder that
/// already keeps one cache for every open document.
pub fn set_byte_store(&mut self, byte_store: Arc<dyn ResourceStorage>) {
self.byte_store = Some(byte_store);
}
/// Whether this document's resource bytes are on hand, in whichever store backs it.
pub fn holds_resource(&self, hash: &ResourceHash) -> bool {
match &self.byte_store {
Some(byte_store) => byte_store.contains(hash),
None => self.working.exists_non_blocking(&self.layout.resource_path(hash)),
}
}
/// Put resource bytes into whichever store backs this document.
pub fn hold_resource(&self, bytes: &[u8]) -> Result<(), ContainerError> {
match &self.byte_store {
Some(byte_store) => {
byte_store.store(bytes);
Ok(())
}
None => self.working.write_non_blocking(&self.layout.resource_path(&ResourceHash::from(bytes)), bytes),
}
}
/// Resources the registry or its history names whose bytes are not on hand.
pub fn unstored_resources(&self) -> Vec<ResourceHash> {
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.holds_resource(hash)).collect()
}
}
impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
@@ -134,12 +104,6 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
pub struct ResourceProxy<T: Layout>(Arc<AnyContainer>, T);
impl<T: Layout + Clone> Clone for ResourceProxy<T> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1.clone())
}
}
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
Box::pin(async move {
+1 -13
View File
@@ -4,7 +4,7 @@
//!
//! Lives in `session.json`. Rewritten on retirement.
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev, UserId};
use document_graph_storage::{NetworkId, PeerId, Rev};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
@@ -15,10 +15,6 @@ pub struct SessionState {
/// tiebreaking and minting peer-scoped IDs.
#[serde(default)]
pub peer_id: PeerId,
/// The person using this device, from the editor's preferences: what the peer registers as in the CRDT,
/// so undo and authorship follow the person across the peer ids they accumulate. `0` until one is known.
#[serde(default)]
pub user_id: UserId,
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
/// document (no commits yet).
#[serde(default)]
@@ -43,12 +39,4 @@ pub struct SessionState {
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, serde_json::Value>>,
/// How many hot ops this peer has authored, feeding [`document_graph_storage::HotOp::sequence`]. A
/// reopen continues the run instead of reusing a spent sequence. Appended last: a positional codec
/// decodes these fields in declaration order.
#[serde(default)]
pub next_hot_sequence: HotSequence,
/// Whether the document was in its room when it was last persisted, so a reopen reconnects by itself.
#[serde(default)]
pub shared: bool,
}
-114
View File
@@ -1,114 +0,0 @@
// The record kept beside the history: what people state about the document's users, persisted with the
// working copy and merged with every copy met. Needs the network feature for a session and the runtime
// conversion for staging ops.
#![cfg(all(feature = "conversion", feature = "network"))]
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::from_runtime::DeclarationBytes;
use document_graph_storage::{Network, NetworkId, PeerId, RegistryDelta, Rev, TimeStamp, UserId, rev_attr, user_attr};
use peer_transport::mock::MockNetwork;
const NOW_MS: f64 = 1_700_000_000_000.;
async fn document(peer: u64, user: u64) -> GddV1 {
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(user), 1, "editor".into(), "stdlib".into())
.await
.expect("create")
}
/// Let the room settle: greetings, the sync handshake and whatever was broadcast, however many rounds it takes.
fn settle(network: &mut MockNetwork, peers: &mut [&mut GddV1]) {
for _ in 0..16 {
for peer in peers.iter_mut() {
peer.poll_peers();
}
network.deliver_all();
}
for peer in peers.iter_mut() {
peer.poll_peers();
}
}
#[test]
fn a_recorded_name_survives_a_reopen() {
futures::executor::block_on(async {
let mut gdd = document(1, 10).await;
assert!(gdd.record_user_attribute(UserId(10), user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
assert!(
!gdd.record_user_attribute(UserId(10), user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"),
"the same name is no change"
);
let step = Rev::new(7).expect("non-zero");
assert!(gdd.record_rev_attribute(step, rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record"));
assert!(gdd.record_rev_attribute(step, "tag:v1", true.into(), NOW_MS).expect("record"));
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.expect("open");
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
assert_eq!(reopened.metadata().rev_label(step), Some("Fixed the eye"), "a label appended after the name is folded back in");
assert_eq!(reopened.metadata().rev_tags(step), vec!["v1"]);
});
}
#[test]
fn names_reach_the_room_with_the_sync_and_as_they_change() {
futures::executor::block_on(async {
let mut host = document(1, 10).await;
let mut guest = document(2, 20).await;
host.record_user_attribute(UserId(10), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
// A name given before joining travels with the joiner and reaches the host.
guest.record_user_attribute(UserId(20), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
let mut network = MockNetwork::new(1);
let host_endpoint = network.endpoint();
let guest_endpoint = network.endpoint();
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
host.share(host_endpoint, UserId(10));
guest.join(guest_endpoint, UserId(20));
network.connect(host_id);
network.connect(guest_id);
settle(&mut network, &mut [&mut host, &mut guest]);
assert!(guest.is_synced());
assert_eq!(guest.metadata().user_name(UserId(10)), Some("Ada"), "the host's record came with the sync");
assert_eq!(host.metadata().user_name(UserId(20)), Some("Bea"), "the guest's record came back to the host");
// A rename while in the room goes round on its own.
assert!(guest.record_user_attribute(UserId(20), user_attr::NAME, "Beatrix".into(), NOW_MS + 5_000.).expect("record"));
settle(&mut network, &mut [&mut host, &mut guest]);
assert_eq!(host.metadata().user_name(UserId(20)), Some("Beatrix"));
assert_eq!(host.metadata(), guest.metadata(), "both copies hold the same record");
});
}
#[test]
fn a_retirement_records_when_it_happened() {
futures::executor::block_on(async {
let mut gdd = document(1, 10).await;
// The editor's per-frame tick is where the wall clock comes from.
gdd.retire_due(NOW_MS, true).expect("tick");
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
gdd.stage_constructed_ops(
vec![RegistryDelta::AddNetwork {
id: NetworkId(9),
network: Network::default(),
}],
&DeclarationBytes::default(),
&byte_store,
)
.expect("stage");
let everything = TimeStamp {
counter: u64::MAX,
peer: PeerId(u64::MAX),
};
let revs = gdd.retire(everything).expect("retire");
assert!(!revs.is_empty());
for rev in revs {
let delta = gdd.session().delta(rev).expect("retired delta");
assert_eq!(delta.retired_at(), Some(NOW_MS as u64));
}
});
}
+23 -36
View File
@@ -5,7 +5,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp, UserId};
use document_graph_storage::{HotOp, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
fn empty_container() -> AnyContainer {
AnyContainer::Memory(MemoryBackend::new())
@@ -44,7 +44,7 @@ fn create_in_round_trips_empty_document() {
futures::executor::block_on(async {
let container = empty_container();
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), UserId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()).await {
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()).await {
Ok(gdd) => gdd,
Err(error) => panic!("create_in failed: {error:?}"),
};
@@ -82,7 +82,7 @@ fn open_in_rejects_wrong_format_magic() {
#[test]
fn manifest_returns_what_create_in_wrote() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), UserId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -99,7 +99,7 @@ fn manifest_returns_what_create_in_wrote() {
#[test]
fn update_manifest_changes_visible_after_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -116,7 +116,7 @@ fn update_manifest_changes_visible_after_reopen() {
#[test]
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -128,7 +128,6 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
@@ -144,7 +143,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
#[test]
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -155,7 +154,6 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
let late = HotOp {
op: RegistryDelta::AddNetwork {
@@ -163,7 +161,6 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
sequence: HotSequence(2),
};
gdd.apply_hot_op(early).unwrap();
gdd.apply_hot_op(late).unwrap();
@@ -192,7 +189,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
#[test]
fn last_broadcast_rev_persists_across_reopen() {
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -203,7 +200,6 @@ fn last_broadcast_rev_persists_across_reopen() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(op).unwrap();
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
@@ -224,7 +220,7 @@ fn export_folder_round_trips_through_open() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xAB, "ed".into(), "std".into())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -254,7 +250,7 @@ fn export_zip_round_trips_via_deserialize() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), UserId(4), 0xCD, "ed".into(), "std".into())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -281,7 +277,7 @@ fn export_rejects_invalid_options() {
use document_format::{ExportFormat, ExportOptions};
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xEF, "ed".into(), "std".into())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -306,7 +302,7 @@ fn resource_round_trip_add_read_remove() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), UserId(99), 0xCAFE, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -338,7 +334,7 @@ fn resource_survives_reopen() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), UserId(7), 0xC0DE, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -369,7 +365,7 @@ fn resource_from_path_uses_fs_copy_on_folder_backend() {
// Need a folder-backed working copy to exercise the fs::copy path.
let working_dir = tempfile::tempdir().unwrap();
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -395,7 +391,7 @@ fn export_carries_resources() {
use graphene_resource::{ResourceHash, ResourceId};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), UserId(2), 0xBC, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -425,7 +421,7 @@ fn embed_all_resources_materializes_link_only_resource() {
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), UserId(8), 0xF00D, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -492,7 +488,7 @@ fn export_materializes_embedded_resource_from_byte_store() {
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -535,7 +531,7 @@ fn export_round_trips_unretired_hot_ops() {
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xF15E, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -590,7 +586,7 @@ fn open_in_rejects_future_format_version() {
#[test]
fn create_in_records_default_codecs_in_manifest() {
futures::executor::block_on(async {
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into())
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -613,7 +609,7 @@ fn first_commit_registers_peer_and_survives_reopen() {
use graphene_resource::ResourceRegistry;
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), UserId(21), 0xAB, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -634,19 +630,11 @@ fn first_commit_registers_peer_and_survives_reopen() {
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
assert_eq!(
gdd.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"first commit registers the peer"
);
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "first commit registers the peer");
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
assert_eq!(
reopened.registry().peer_users.get(&PeerId(21)).map(|registration| registration.user),
Some(UserId(21)),
"registration survives reopen"
);
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
});
}
@@ -657,7 +645,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
futures::executor::block_on(async {
use document_container::AsyncContainer;
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -667,7 +655,6 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
network: Network::default(),
},
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
sequence: HotSequence(1),
};
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
@@ -711,7 +698,7 @@ fn declarations_round_trip_through_byte_store() {
..Default::default()
};
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into())
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
.await
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
@@ -1,48 +0,0 @@
// Needs the runtime conversion for `stage_constructed_ops` and the network feature for a session.
#![cfg(all(feature = "conversion", feature = "network"))]
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::from_runtime::DeclarationBytes;
use document_graph_storage::{Network, NetworkId, PeerId, RegistryDelta, UserId};
use peer_transport::mock::MockNetwork;
/// Every staging path has to reach the room. The recorded-batch path once appended its hot frames and
/// stopped there, so an edit made through the interface was persisted and never sent.
#[test]
fn staging_a_constructed_batch_reaches_the_room() {
futures::executor::block_on(async {
let mut host = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 1, "editor".into(), "stdlib".into())
.await
.expect("create");
let mut network = MockNetwork::new(1);
let host_endpoint = network.endpoint();
let guest_endpoint = network.endpoint();
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
host.share(host_endpoint, UserId(1));
network.connect(host_id);
network.connect(guest_id);
// Greeting the guest is what lets the host send to it; the hello itself is then out of the way.
host.poll_peers();
network.deliver_all();
assert_eq!(network.pending(), 0);
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
let staged = host
.stage_constructed_ops(
vec![RegistryDelta::AddNetwork {
id: NetworkId(9),
network: Network::default(),
}],
&DeclarationBytes::default(),
&byte_store,
)
.expect("stage");
assert!(!staged.is_empty(), "the staged hot ops come back for the caller");
assert!(network.pending() > 0, "a staged batch must be broadcast to the room");
});
}
+1 -3
View File
@@ -1,12 +1,10 @@
[package]
name = "document-graph-storage"
description = "Provides a delta based graph representation used in the Graphite file format"
edition.workspace = true
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[features]
conversion = ["dep:graph-craft", "dep:core-types"]
+4 -25
View File
@@ -8,42 +8,21 @@ use std::collections::BTreeMap;
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// A type-erased attribute value paired with the timestamp at which it was last set. A deleted key
/// stays as a stamped tombstone, so a write older than the deletion is recognised as older whichever
/// order the two land in; readers see a tombstone as absent.
/// A type-erased attribute value paired with the timestamp at which it was last set.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Value {
pub value: serde_json::Value,
pub timestamp: TimeStamp,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub deleted: bool,
}
impl Value {
pub fn new(value: serde_json::Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp, deleted: false }
}
/// The tombstone of a key deleted at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
value: serde_json::Value::Null,
timestamp,
deleted: true,
}
Self { value, timestamp }
}
}
/// Attribute maps. Each entity carries an `attributes_timestamp` next to its map: when the map was last
/// written whole, by an addition or a whole-list input write. A key absent from the map is deleted as of
/// that stamp, so a write older than it is dropped, and a tombstone older than it is redundant.
pub type Attributes = BTreeMap<String, Value>;
/// The live entries of an attribute map: every key that is not a tombstone.
pub fn live(attributes: &Attributes) -> impl Iterator<Item = (&String, &Value)> {
attributes.iter().filter(|(_, value)| !value.deleted)
}
/// Write helpers for `Attributes`.
pub trait AttributesWrite {
/// Inserts a JSON value under `key`.
@@ -65,7 +44,7 @@ pub trait AttributesWrite {
impl AttributesWrite for Attributes {
fn set(&mut self, key: &str, value: serde_json::Value, timestamp: TimeStamp) {
self.insert(key.to_string(), Value::new(value, timestamp));
self.insert(key.to_string(), Value { value, timestamp });
}
}
@@ -87,6 +66,6 @@ pub trait AttributesRead {
impl AttributesRead for Attributes {
fn get_typed<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
self.get(key).filter(|v| !v.deleted).and_then(|v| serde_json::from_value(v.value.clone()).ok())
self.get(key).and_then(|v| serde_json::from_value(v.value.clone()).ok())
}
}
@@ -1,6 +1,5 @@
pub mod node {
pub const CALL_ARGUMENT: &str = "call_argument";
pub const CONTEXT_FEATURES: &str = "context_features";
pub const VISIBLE: &str = "visible";
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
pub const REFLECTION_METADATA: &str = "reflection_metadata";
@@ -32,6 +31,7 @@ pub mod node {
pub mod session {
pub mod network {
pub const PREVIEWING: &str = "ui::previewing";
// TODO: Remove these graph ui nav-specific attributes
pub const NAV_PTZ: &str = "ui::nav::ptz";
pub const NAV_TRANSFORM: &str = "ui::nav::transform";
@@ -59,17 +59,9 @@ pub mod network {
/// serialized blob so its shape can evolve (e.g. dropping the `Type`) without a model change. The
/// node references use stable storage IDs, resolved back to runtime-local IDs on conversion.
pub const SCOPE_INJECTIONS: &str = "scope_injections";
/// Whole-vec LWW of the display order of the network's pinned nodes, as stable storage IDs.
/// Concurrent reorders do not merge, but the pinned set is already shared, and a shared set with
/// per-peer ordering would diverge with no way to reconcile.
pub const PINNED_ORDER: &str = "ui::pinned_order";
}
pub mod delta {
/// Marks the last delta of a user interaction, so the undo cursor steps per-interaction, not per-delta.
pub const INTERACTION_END: &str = "interaction_end";
/// When the delta entered history, in wall-clock milliseconds since the Unix epoch as its retirer saw them.
/// For showing when a step happened; order always comes from the graph, never from this.
pub const RETIRED_AT: &str = "retired_at";
}
+22 -44
View File
@@ -1,6 +1,4 @@
use crate::{
Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev,
};
use crate::{Attributes, AttributesWrite, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
use graphene_resource::ResourceHash;
use serde::{Deserialize, Serialize};
@@ -78,11 +76,6 @@ impl Delta {
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == serde_json::Value::Bool(true))
}
/// When the delta entered history in wall-clock milliseconds, if its retirer recorded it.
pub fn retired_at(&self) -> Option<u64> {
self.attributes.get(attr::delta::RETIRED_AT).and_then(|recorded| recorded.value.as_u64())
}
/// The content-addressed `Rev` this delta's identity fields hash to. Equals `id` for a delta built
/// via `new`/`merge`; differs only if `id` was tampered with or the hash derivation changed.
pub fn recomputed_id(&self) -> Rev {
@@ -99,7 +92,7 @@ impl Delta {
/// Op payload. Timestamps live on the wrapping `Delta` — one per delta, applied to all LWW-eligible
/// writes within. See `notes/document-format-collaboration.md`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum RegistryDelta {
AddNode {
id: NodeId,
@@ -116,25 +109,6 @@ pub enum RegistryDelta {
index: u32,
new_input: NodeInput,
},
/// A node's whole input list, for a change to the number or order of its slots that the
/// index-addressed `ChangeNodeInput` cannot express. Assigns rather than merging: concurrent
/// per-slot edits are lost, which is inherent to the indices themselves moving.
///
/// Touches only the inputs, leaving the node's attributes and implementation alone, so it composes
/// with attribute ops on the same node instead of reverting them.
SetNodeInputs {
id: NodeId,
inputs: Vec<InputSlot>,
},
/// A node's implementation, for swapping what it computes without rebuilding the node.
///
/// Removing and re-adding the node would express the same change, but would also clear every
/// attribute it carries, so restating them would clobber whatever a concurrent peer wrote to the
/// node's name, lock or pin.
SetNodeImplementation {
id: NodeId,
implementation: Implementation,
},
ChangeNodeAttribute {
id: NodeId,
delta: AttributeDelta,
@@ -211,15 +185,12 @@ pub enum RegistryDelta {
Merge {
extra_parents: Vec<Rev>,
},
/// The last op of its author's transaction. Changes nothing; retirement takes an author's ops through
/// one of these as one unit and drops the marker itself. See [`Session::closed_transactions`](crate::Session::closed_transactions).
EndTransaction,
// Allow for future delta types without a model change
Other(serde_json::Value),
}
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<serde_json::Value>,
@@ -228,21 +199,28 @@ pub struct AttributeDelta {
pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta {
AttributeDelta {
key: delta.key.clone(),
value: attributes.get(&delta.key).filter(|previous| !previous.deleted).map(|previous| previous.value.clone()),
value: attributes.get(&delta.key).map(|previous| previous.value.clone()),
}
}
/// Lands a single-key write. `floor` is when the map was last written whole: a key the map does not
/// hold is deleted as of then, so a write older than it is dropped. A deletion leaves a tombstone.
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes, floor: TimeStamp) {
pub(crate) fn apply_attribute_delta(delta: AttributeDelta, timestamp: TimeStamp, force: bool, attributes: &mut Attributes) {
let AttributeDelta { key, value } = delta;
let decided = attributes.get(&key).map_or(floor, |existing| existing.timestamp);
if !force && timestamp <= decided {
return;
match value {
Some(value) => match attributes.entry(key) {
std::collections::btree_map::Entry::Occupied(mut entry) => {
if force || timestamp > entry.get().timestamp {
entry.insert(Value { value, timestamp });
}
}
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(Value { value, timestamp });
}
},
None => {
let should_remove = force || attributes.get(&key).is_none_or(|existing| timestamp > existing.timestamp);
if should_remove {
attributes.remove(&key);
}
}
}
let entry = match value {
Some(value) => Value::new(value, timestamp),
None => Value::deleted(timestamp),
};
attributes.insert(key, entry);
}
+6 -11
View File
@@ -166,14 +166,14 @@ fn diff_resource_entry(id: ResourceId, from: &ResourceEntry, to: &ResourceEntry,
deltas.push(RegistryDelta::SetResourceHash { id, hash: to.hash });
}
for (key, _) in from.live_sources() {
for (key, _) in &from.sources {
if to.source(key).is_none() {
deltas.push(RegistryDelta::RemoveSource { id, key: *key });
}
}
// Compare source bodies only; the per-source timestamp is derived from the diff, not part of it.
for (key, to_source) in to.live_sources() {
for (key, to_source) in &to.sources {
if from.source(key).is_none_or(|from_source| from_source.source != to_source.source) {
deltas.push(RegistryDelta::AddSource {
id,
@@ -196,16 +196,15 @@ fn nodes_have_same_implementation(a: &Node, b: &Node) -> bool {
fn compute_attribute_deltas(from: &crate::Attributes, to: &crate::Attributes) -> Vec<AttributeDelta> {
let mut deltas = Vec::new();
let held = |attributes: &crate::Attributes, key: &str| attributes.get(key).filter(|value| !value.deleted).map(|value| value.value.clone());
for (key, _) in crate::attributes::live(from) {
if held(to, key).is_none() {
for key in from.keys() {
if !to.contains_key(key) {
deltas.push(AttributeDelta { key: key.clone(), value: None });
}
}
// Compare by `value` only; the per-entry `timestamp` is derived from the diff, not part of it.
for (key, to_value) in crate::attributes::live(to) {
if held(from, key).is_none_or(|from_value| from_value != to_value.value) {
for (key, to_value) in to {
if from.get(key).is_none_or(|from_value| from_value.value != to_value.value) {
deltas.push(AttributeDelta {
key: key.clone(),
value: Some(to_value.value.clone()),
@@ -288,7 +287,6 @@ mod tests {
input: NodeInput::Import { index: 0 },
timestamp: TimeStamp::ORIGIN,
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
});
let deltas = compute_deltas(&from, &to);
@@ -346,7 +344,6 @@ mod tests {
crate::Value {
value: serde_json::json!("old"),
timestamp: stamp(0),
deleted: false,
},
);
from.node_instances.insert(NodeId(42), node);
@@ -357,7 +354,6 @@ mod tests {
crate::Value {
value: serde_json::json!("new"),
timestamp: stamp(1),
deleted: false,
},
);
@@ -383,7 +379,6 @@ mod tests {
crate::Value {
value: serde_json::json!("value"),
timestamp: stamp(1),
deleted: false,
},
);
File diff suppressed because it is too large. Load diff
+58 -367
View File
@@ -1,7 +1,6 @@
use std::collections::HashMap;
use core_types::Context;
use core_types::context::ContextDependencies;
use core_types::uuid::NodeId as RuntimeNodeId;
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
@@ -60,34 +59,6 @@ impl NodePath {
}
}
/// Resolves a node's storage identity: the identity the metadata source holds for it where there is
/// one, and a hash of its location otherwise. Every place a node is named goes through here, so a
/// node's own registry key and every reference to it agree.
///
/// A held identity travels with the node, so moving it between networks keeps it. A hashed one is
/// derived from the node's place in the tree, so it changes when the node moves; it stands in for a
/// node no source names, such as one in a network that has never been stored.
pub(crate) struct NodeIds<'a, M: NodeMetadataSource + ?Sized> {
pub(crate) metadata: Option<&'a M>,
pub(crate) metadata_path: &'a [RuntimeNodeId],
pub(crate) peer: PeerId,
}
impl<M: NodeMetadataSource + ?Sized> Clone for NodeIds<'_, M> {
fn clone(&self) -> Self {
*self
}
}
impl<M: NodeMetadataSource + ?Sized> Copy for NodeIds<'_, M> {}
impl<M: NodeMetadataSource + ?Sized> NodeIds<'_, M> {
fn resolve(&self, path: &NodePath, local_id: RuntimeNodeId) -> NodeId {
self.metadata
.and_then(|metadata| metadata.storage_node_id(self.metadata_path, local_id))
.unwrap_or_else(|| path.to_global_id(self.peer))
}
}
#[derive(Debug, thiserror::Error)]
pub enum ConversionError {
#[error("Failed to serialize value: {0}")]
@@ -117,17 +88,33 @@ impl TryFrom<&NodeNetwork> for Registry {
pub type DeclarationBytes = HashMap<ResourceHash, Vec<u8>>;
/// A `from_runtime` conversion result: the reference-only [`Registry`] plus the proto-node
/// declarations it extracted, as bytes keyed by content hash (for the caller's byte store) and as
/// decoded [`ProtoNode`]s keyed by id (for the caller's declaration cache).
/// declaration *bytes* it extracted, keyed by content hash. `document-graph-storage` doesn't own a byte
/// store, so the caller (the `Gdd`) persists these into its content store; the registry only holds
/// the `ResourceId`/`ResourceHash` references.
pub struct RuntimeConversion {
pub registry: Registry,
pub declaration_bytes: DeclarationBytes,
pub declarations: crate::Declarations,
/// Each network's runtime `metadata_path` mapped to its stable storage `NetworkId`, for associating
/// per-network, per-peer view state (`session.json`) without re-deriving ids.
pub network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
}
impl RuntimeConversion {
/// Rebuild the [`Declarations`](crate::Declarations) map (`ResourceId` → [`ProtoNode`]) from the
/// extracted bytes, for callers that keep the bytes in hand instead of routing them through a
/// byte store (tests, the round-trip CLI). Editor/`Gdd` paths persist the bytes and resolve via
/// their byte store instead.
pub fn declarations(&self) -> Result<crate::Declarations, ConversionError> {
self.declaration_bytes
.iter()
.map(|(hash, bytes)| {
let proto = decode_declaration(bytes).map_err(|error| ConversionError::SerializationError(format!("declaration {hash}: {error}")))?;
Ok((ResourceId::from_hash(hash), proto))
})
.collect()
}
}
/// Encode a [`ProtoNode`] declaration to its content-addressed bytes: through a self-describing
/// `serde_json::Value` (so serde aliases keep working and the on-disk shape stays migratable), then
/// rmp-serialized (which encodes the intermediate `Value` compactly). Paired with [`decode_declaration`].
@@ -161,7 +148,6 @@ impl Registry {
let mut ctx = ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
declarations: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
@@ -180,7 +166,6 @@ impl Registry {
Ok(RuntimeConversion {
registry,
declaration_bytes: ctx.declaration_bytes,
declarations: ctx.declarations,
network_ids: ctx.network_ids,
})
}
@@ -196,42 +181,33 @@ fn convert_resources(resources: &graphene_resource::ResourceRegistry, referenced
if !referenced.contains(&id) {
continue;
}
if let Some(entry) = convert_resource_entry(resources, id, peer)? {
registry.resources.insert(id, entry);
let Some(info) = resources.info(&id) else { continue };
let mut entry = crate::ResourceEntry {
hash: info.hash.copied(),
hash_timestamp: TimeStamp::ORIGIN,
..Default::default()
};
for (position, source) in info.sources.iter().enumerate() {
let key = crate::SourceKey {
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
},
);
}
registry.resources.insert(id, entry);
}
Ok(())
}
/// Snapshot one runtime resource into a storage entry, or `None` if the runtime has no such resource.
pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, id: ResourceId, peer: PeerId) -> Result<Option<crate::ResourceEntry>, ConversionError> {
let Some(info) = resources.info(&id) else { return Ok(None) };
let mut entry = crate::ResourceEntry {
hash: info.hash.copied(),
hash_timestamp: TimeStamp::ORIGIN,
..Default::default()
};
for (position, source) in info.sources.iter().enumerate() {
let key = crate::SourceKey {
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
// Built rather than written: the chain is put in place as converted, floor and all at the origin.
entry.force_set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
);
}
Ok(Some(entry))
}
/// Collect the `ResourceId`s referenced by `TaggedValue::Resource` inputs anywhere in the network
/// (recursively through nested networks). These are the resources the document actually uses; the
/// runtime cache may hold more (history-retained orphans) that shouldn't be snapshotted into storage.
@@ -277,8 +253,6 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
declaration_ids: HashMap<String, ResourceId>,
/// Extracted declaration content keyed by hash, handed back for the caller's byte store.
declaration_bytes: DeclarationBytes,
/// The same declarations decoded, keyed by id, handed back for the caller's declaration cache.
declarations: crate::Declarations,
/// Maps each network's runtime `metadata_path` to its stable storage `NetworkId`, so the caller can
/// associate per-network, per-peer view state (in `session.json`) with networks without re-deriving ids.
network_ids: HashMap<Vec<RuntimeNodeId>, NetworkId>,
@@ -286,20 +260,6 @@ struct ConversionContext<'m, M: NodeMetadataSource + ?Sized> {
peer: PeerId,
}
impl<'m, M: NodeMetadataSource + ?Sized> ConversionContext<'m, M> {
/// The identity resolver for nodes addressed inside the network at `metadata_path`.
fn ids<'a>(&self, metadata_path: &'a [RuntimeNodeId]) -> NodeIds<'a, M>
where
'm: 'a,
{
NodeIds {
metadata: Some(self.metadata),
metadata_path,
peer: self.peer,
}
}
}
fn convert_network<M: NodeMetadataSource + ?Sized>(
node_network: &NodeNetwork,
network_id: NetworkId,
@@ -310,7 +270,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
) -> Result<(), ConversionError> {
for (runtime_node_id, doc_node) in &node_network.nodes {
let node_path = child_path(parent_path, network_id, *runtime_node_id);
let global_id = ctx.ids(metadata_path).resolve(&node_path, *runtime_node_id);
let global_id = node_path.to_global_id(ctx.peer);
let location = NodeLocation {
network_id,
@@ -318,7 +278,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
metadata_path,
runtime_node_id: *runtime_node_id,
};
let mut node = convert_node(doc_node, location, registry, ctx, true)?;
let mut node = convert_node(doc_node, location, registry, ctx)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(global_id, node);
}
@@ -328,25 +288,17 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
.iter()
.map(|export| {
Ok(ExportSlot {
target: Some(convert_input(export, parent_path, network_id, ctx.ids(metadata_path))?),
target: Some(convert_input(export, parent_path, network_id, ctx.peer)?),
timestamp: TimeStamp::ORIGIN,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(&mut attributes, node_network, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.peer, TimeStamp::ORIGIN)?;
registry.networks.insert(
network_id,
Network {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
registry.networks.insert(network_id, Network { exports, attributes });
ctx.network_ids.insert(metadata_path.to_vec(), network_id);
Ok(())
@@ -355,12 +307,12 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
/// Serialize a network's `scope_injections` onto its attributes as one whole-map LWW blob, remapping
/// each runtime-local node reference to its stable storage global ID so the reference survives a
/// round trip even if runtime IDs are later reshuffled.
fn write_scope_injections<M: NodeMetadataSource + ?Sized>(
fn write_scope_injections(
attributes: &mut crate::Attributes,
node_network: &NodeNetwork,
parent_path: Option<&NodePath>,
network_id: NetworkId,
ids: NodeIds<'_, M>,
peer: PeerId,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
if node_network.scope_injections.is_empty() {
@@ -371,7 +323,7 @@ fn write_scope_injections<M: NodeMetadataSource + ?Sized>(
.scope_injections
.iter()
.map(|(key, (runtime_id, ty))| {
let storage_id = ids.resolve(&child_path(parent_path, network_id, *runtime_id), *runtime_id);
let storage_id = child_path(parent_path, network_id, *runtime_id).to_global_id(peer);
(key.clone(), (storage_id, ty.clone()))
})
.collect();
@@ -398,13 +350,7 @@ struct NodeLocation<'a> {
runtime_node_id: RuntimeNodeId,
}
fn convert_node<M: NodeMetadataSource + ?Sized>(
doc_node: &DocumentNode,
location: NodeLocation<'_>,
registry: &mut Registry,
ctx: &mut ConversionContext<'_, M>,
recurse: bool,
) -> Result<Node, ConversionError> {
fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, location: NodeLocation<'_>, registry: &mut Registry, ctx: &mut ConversionContext<'_, M>) -> Result<Node, ConversionError> {
let NodeLocation {
network_id,
parent_path,
@@ -421,10 +367,9 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
write_ui_input_attributes(&mut input_attrs, ctx.metadata, metadata_path, runtime_node_id, input_index, timestamp)?;
inputs.push(InputSlot {
input: convert_input(input, parent_path, network_id, ctx.ids(metadata_path))?,
input: convert_input(input, parent_path, network_id, ctx.peer)?,
timestamp,
attributes: input_attrs,
attributes_timestamp: timestamp,
});
}
@@ -437,16 +382,13 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
} else {
metadata_path
};
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx, recurse)?;
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx)?;
// Defaults match `DocumentNode::default()`; `to_runtime` rehydrates absent keys from the same defaults.
let mut attributes = crate::Attributes::new();
attributes
.set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp)
.map_err(map_serialization_error(node::CALL_ARGUMENT))?;
attributes
.set_if_not_default(node::CONTEXT_FEATURES, &doc_node.context_features, &ContextDependencies::default(), timestamp)
.map_err(map_serialization_error(node::CONTEXT_FEATURES))?;
attributes
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
.map_err(map_serialization_error(node::VISIBLE))?;
@@ -457,62 +399,13 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
write_ui_attributes(&mut attributes, ctx.metadata, metadata_path, runtime_node_id, timestamp)?;
Ok(Node {
presence: timestamp,
added: timestamp,
inputs_timestamp: timestamp,
implementation,
implementation_timestamp: timestamp,
inputs,
attributes,
attributes_timestamp: timestamp,
network: network_id,
})
}
/// The `call_argument` attribute write for a node, cleared when the value is the default that
/// `to_runtime` rehydrates an absent key from. For staging paths that encode this field alone.
pub fn encode_call_argument(call_argument: &core_types::Type) -> Result<crate::AttributeDelta, ConversionError> {
encode_if_not_default(node::CALL_ARGUMENT, call_argument, &concrete!(Context))
}
/// The `context_features` attribute write, cleared at its default like [`encode_call_argument`].
pub fn encode_context_features(context_features: &ContextDependencies) -> Result<crate::AttributeDelta, ConversionError> {
encode_if_not_default(node::CONTEXT_FEATURES, context_features, &ContextDependencies::default())
}
fn encode_if_not_default<T: Serialize + PartialEq>(key: &str, value: &T, default: &T) -> Result<crate::AttributeDelta, ConversionError> {
let value = if value == default {
None
} else {
Some(serde_json::to_value(value).map_err(map_serialization_error(key))?)
};
Ok(crate::AttributeDelta { key: key.to_string(), value })
}
/// Public form of the node ui-attribute encoding, for staging paths that encode single nodes.
pub fn encode_node_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
metadata_path: &[RuntimeNodeId],
runtime_node_id: RuntimeNodeId,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
write_ui_attributes(attributes, metadata, metadata_path, runtime_node_id, timestamp)
}
/// Public form of the per-input ui-attribute encoding, matching `encode_node_ui_attributes`.
pub fn encode_input_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
metadata_path: &[RuntimeNodeId],
runtime_node_id: RuntimeNodeId,
input_index: usize,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
write_ui_input_attributes(attributes, metadata, metadata_path, runtime_node_id, input_index, timestamp)
}
fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
@@ -554,36 +447,11 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
Ok(())
}
/// Node references here are remapped to stable storage IDs for the same reason `write_scope_injections`
/// does it: a runtime ID is not stable across a round trip.
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
node_network: &NodeNetwork,
network_path: &[RuntimeNodeId],
parent_path: Option<&NodePath>,
network_id: NetworkId,
ids: NodeIds<'_, M>,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
// The same source the IDs resolve through, so a network's attributes and the nodes they name agree.
let Some(metadata) = ids.metadata else { return Ok(()) };
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(attributes: &mut crate::Attributes, metadata: &M, network_path: &[RuntimeNodeId], timestamp: TimeStamp) -> Result<(), ConversionError> {
if let Some(reference) = metadata.reference(network_path) {
attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp);
}
let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id);
// Only nodes the converted network still holds: the read side drops a stored ID it cannot find, so
// persisting one for a node deleted or reparented elsewhere would leave stored state disagreeing with
// what a peer converting the same input produces.
let pinned_order: Vec<_> = metadata.pinned_order(network_path).into_iter().filter(|pinned| node_network.nodes.contains_key(pinned)).collect();
if !pinned_order.is_empty() {
let stored: Vec<NodeId> = pinned_order.into_iter().map(to_storage_id).collect();
attributes
.set_serialized(network::PINNED_ORDER, &stored, timestamp)
.map_err(map_serialization_error(network::PINNED_ORDER))?;
}
Ok(())
}
@@ -614,10 +482,10 @@ fn write_ui_input_attributes<M: NodeMetadataSource + ?Sized>(
Ok(())
}
fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, network_id: NetworkId, ids: NodeIds<'_, M>) -> Result<NodeInput, ConversionError> {
fn convert_input(input: &GraphCraftNodeInput, parent_path: Option<&NodePath>, network_id: NetworkId, peer: PeerId) -> Result<NodeInput, ConversionError> {
Ok(match input {
GraphCraftNodeInput::Node { node_id, output_index } => NodeInput::Node {
id: ids.resolve(&child_path(parent_path, network_id, *node_id), *node_id),
id: child_path(parent_path, network_id, *node_id).to_global_id(peer),
index: (*output_index).try_into().map_err(|_| ConversionError::IndexOverflow(*output_index))?,
},
GraphCraftNodeInput::Value { tagged_value, exposed } => {
@@ -634,9 +502,7 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
})
}
/// The non-ui attributes a slot carries, derived from the input itself: the declared type of an
/// import, and a reflection node's metadata.
pub fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
fn convert_input_attributes(input: &GraphCraftNodeInput) -> Result<crate::Attributes, ConversionError> {
let mut attributes = crate::Attributes::new();
let timestamp = TimeStamp::ORIGIN;
@@ -663,7 +529,6 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
child_metadata_path: &[RuntimeNodeId],
registry: &mut Registry,
ctx: &mut ConversionContext<'_, M>,
recurse: bool,
) -> Result<Implementation, ConversionError> {
Ok(match implementation {
DocumentNodeImplementation::ProtoNode(identifier) => {
@@ -686,7 +551,6 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
register_declaration_resource(registry, id, hash, ctx.peer);
ctx.declaration_bytes.insert(hash, bytes);
ctx.declarations.insert(id, proto);
ctx.declaration_ids.insert(identifier_str, id);
Implementation::ProtoNode(id)
@@ -696,183 +560,10 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
// `to_runtime` -> `from_runtime` round trip reproduces the same `NetworkId` (and thus the
// same node-path hashes underneath it).
let nested_network_id = current_node_path.owned_network_id(ctx.peer);
if recurse {
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
}
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
Implementation::Network(nested_network_id)
}
// TODO: Support Extract in the Registry format.
DocumentNodeImplementation::Extract => return Err(ConversionError::UnsupportedImplementation),
})
}
/// Derives the storage IDs for entities addressed by runtime network paths, resolving each through
/// the same [`NodeIds`] a whole-document conversion uses so scoped and whole-document conversions agree.
pub struct PathResolver<'m> {
metadata: Option<&'m dyn NodeMetadataSource>,
peer: PeerId,
}
impl<'m> PathResolver<'m> {
/// Without a metadata source every node falls back to a hash of its location, which only matches a
/// whole-document conversion while no node has a stored identity.
pub fn new(metadata: Option<&'m dyn NodeMetadataSource>, peer: PeerId) -> Self {
Self { metadata, peer }
}
/// The storage `NetworkId` of the network at `local_path` (`ROOT_NETWORK` for the empty path).
pub fn network_id(&self, local_path: &[RuntimeNodeId]) -> NetworkId {
match self.owner_path(local_path) {
None => ROOT_NETWORK,
Some(owner) => owner.owned_network_id(self.peer),
}
}
/// The storage `NodeId` of the node with `local_id` inside the network at `local_path`.
pub fn node_id(&self, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeId {
let owner = self.owner_path(local_path);
self.ids(local_path).resolve(&child_path(owner.as_ref(), self.network_id(local_path), local_id), local_id)
}
/// Converts one runtime input inside the network at `local_path` to its storage form, resolving
/// node references to their storage IDs.
pub fn convert_input_at(&self, input: &GraphCraftNodeInput, local_path: &[RuntimeNodeId]) -> Result<NodeInput, ConversionError> {
let owner = self.owner_path(local_path);
convert_input(input, owner.as_ref(), self.network_id(local_path), self.ids(local_path))
}
/// The identity resolver for nodes addressed inside the network at `local_path`.
fn ids<'a>(&self, local_path: &'a [RuntimeNodeId]) -> NodeIds<'a, dyn NodeMetadataSource + 'm>
where
'm: 'a,
{
NodeIds {
metadata: self.metadata,
metadata_path: local_path,
peer: self.peer,
}
}
/// The `NodePath` of the node owning the network at `local_path`, or `None` for the root network.
fn owner_path(&self, local_path: &[RuntimeNodeId]) -> Option<NodePath> {
let mut owner: Option<NodePath> = None;
for &local_id in local_path {
let network_id = match &owner {
None => ROOT_NETWORK,
Some(owner) => owner.owned_network_id(self.peer),
};
owner = Some(child_path(owner.as_ref(), network_id, local_id));
}
owner
}
}
/// Converts a chosen subset of runtime entities into a scratch [`Registry`] through the same
/// encoders as a whole-document conversion, so staging can derive deltas for just those entities.
pub struct ScopedConversion<'m> {
ctx: ConversionContext<'m, dyn NodeMetadataSource + 'm>,
resolver: PathResolver<'m>,
}
impl<'m> ScopedConversion<'m> {
pub fn new(metadata: &'m dyn NodeMetadataSource, peer: PeerId) -> Self {
Self {
ctx: ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
declarations: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
},
resolver: PathResolver::new(Some(metadata), peer),
}
}
/// Converts the node with `local_id` in the network at `local_path` into `registry` under its
/// stable IDs. `recurse` also converts the contents of any nested network the node implements;
/// without it only the node itself is converted, with its nested network referenced by ID.
pub fn convert_node_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId, doc_node: &DocumentNode, recurse: bool) -> Result<(), ConversionError> {
let owner_path = self.resolver.owner_path(local_path);
let location = NodeLocation {
network_id: self.resolver.network_id(local_path),
parent_path: owner_path.as_ref(),
metadata_path: local_path,
runtime_node_id: local_id,
};
let mut node = convert_node(doc_node, location, registry, &mut self.ctx, recurse)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(local_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(self.resolver.node_id(local_path, local_id), node);
Ok(())
}
/// Converts the entry of the network at `local_path` (its export slots and network-level
/// attributes, not its nodes) into `registry`.
pub fn convert_network_entry_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], node_network: &NodeNetwork) -> Result<(), ConversionError> {
let owner_path = self.resolver.owner_path(local_path);
let network_id = self.resolver.network_id(local_path);
let exports = node_network
.exports
.iter()
.map(|export| {
Ok(ExportSlot {
target: Some(convert_input(export, owner_path.as_ref(), network_id, self.ctx.ids(local_path))?),
timestamp: TimeStamp::ORIGIN,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(&mut attributes, node_network, local_path, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
registry.networks.insert(
network_id,
Network {
presence: TimeStamp::ORIGIN,
exports,
attributes,
attributes_timestamp: TimeStamp::ORIGIN,
},
);
Ok(())
}
/// The extracted proto-node declarations: the bytes for the caller's byte store, and the same
/// declarations decoded for its declaration cache.
pub fn finish(self) -> (DeclarationBytes, crate::Declarations) {
(self.ctx.declaration_bytes, self.ctx.declarations)
}
}
/// The `TaggedValue::Resource` IDs referenced by a stored node's value inputs.
///
/// Peeks at the externally-tagged serde shape (`{"Resource": <id>}`) rather than deserializing the
/// whole `TaggedValue`, which can be arbitrarily large. `resource_ref_shape_matches_serde` asserts
/// this stays in lockstep with the real serialization.
pub fn node_value_resource_refs(node: &Node) -> impl Iterator<Item = ResourceId> + '_ {
node.inputs.iter().filter_map(|slot| value_resource_ref(&slot.input))
}
/// The `TaggedValue::Resource` ID referenced by a stored value input, if any.
pub fn value_resource_ref(input: &NodeInput) -> Option<ResourceId> {
match input {
NodeInput::Value { value, .. } => value.get("Resource").and_then(|id| serde_json::from_value(id.clone()).ok()),
_ => None,
}
}
#[cfg(test)]
mod resource_ref_shape {
use super::*;
#[test]
fn resource_ref_shape_matches_serde() {
let id = ResourceId::from_hash(&ResourceHash::from(b"shape test".as_slice()));
let value = serde_json::to_value(TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
let parsed: Option<ResourceId> = value.get("Resource").and_then(|inner| serde_json::from_value(inner.clone()).ok());
assert_eq!(parsed, Some(id), "The shape peek in node_value_resource_refs must match TaggedValue's serde form");
}
}
+18 -123
View File
@@ -8,27 +8,16 @@
//! construction. The only operation that introduces out-of-order deltas is [`merge`](History::merge),
//! which re-sorts the combined set into the canonical order to restore the invariant.
use std::collections::{HashMap, HashSet};
use std::collections::HashMap;
use crate::{AttributesWrite, CrdtError, Delta, RegistryDelta, ResourceHash, Rev, TimeStamp};
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
/// The indexes are maintained by every mutator, so the questions the per-frame and per-interaction
/// paths ask (is this timestamp retired, what are the tips, which hashes does history name) are probes
/// rather than scans of a history that only ever grows.
#[derive(Clone, Debug, Default)]
pub struct History {
/// Deltas in topological order. Mutated only via [`push`](Self::push).
deltas: Vec<Delta>,
/// `Rev` to its position in `deltas`. Kept in sync with `deltas` by every mutator.
index: HashMap<Rev, usize>,
/// The timestamps the deltas were authored at.
timestamps: HashSet<TimeStamp>,
/// Every rev some delta names as a parent.
referenced: HashSet<Rev>,
/// Deltas no other delta names as a parent.
tips: HashSet<Rev>,
/// Content hashes the deltas name, from resource additions and removals.
resource_hashes: HashSet<ResourceHash>,
}
impl History {
@@ -38,16 +27,8 @@ impl History {
/// Build from deltas already in topological order (the on-disk load path), indexing them in place.
pub fn from_ordered(deltas: Vec<Delta>) -> Self {
let mut history = Self::default();
for delta in deltas {
history.push(delta);
}
history
}
/// Where `rev` sits in the file order, if it is here.
pub fn position(&self, rev: Rev) -> Option<usize> {
self.index.get(&rev).copied()
let index = deltas.iter().enumerate().map(|(position, delta)| (delta.id, position)).collect();
Self { deltas, index }
}
pub fn get(&self, rev: Rev) -> Option<&Delta> {
@@ -58,35 +39,6 @@ impl History {
self.index.contains_key(&rev)
}
/// Whether history holds a delta authored at `timestamp`.
pub fn contains_timestamp(&self, timestamp: TimeStamp) -> bool {
self.timestamps.contains(&timestamp)
}
/// The content hashes named by any resource addition or removal in history.
pub fn resource_hashes(&self) -> &HashSet<ResourceHash> {
&self.resource_hashes
}
/// Whether the deltas from `from` on extend the canonical order as they stand: a chain, each the
/// first's child in turn, hanging off the last delta before them. Such a tail is what every
/// retirement in a hosted session appends, and needs no re-sort.
///
/// The sort emits, among the deltas whose parents are all out, the lowest rev. A chain on the last
/// delta is alone in that set at every step, so it sorts where it was appended. A tail whose root
/// hangs off an earlier delta competes with that delta's later siblings and may sort before them.
pub fn extends_canonically(&self, from: usize) -> bool {
let Some(tail) = self.deltas.get(from..) else { return true };
let mut previous = from.checked_sub(1).map(|position| self.deltas[position].id);
for delta in tail {
if delta.parent != previous || matches!(delta.kind, RegistryDelta::Merge { .. }) {
return false;
}
previous = Some(delta.id);
}
true
}
pub fn len(&self) -> usize {
self.deltas.len()
}
@@ -99,23 +51,10 @@ impl History {
/// (idempotent re-apply) overwrites the existing entry in place rather than appending, so the
/// order and index are unchanged.
pub fn push(&mut self, delta: Delta) {
self.timestamps.insert(delta.timestamp);
match &delta.kind {
RegistryDelta::AddResource { entry, .. } => self.resource_hashes.extend(entry.hash),
RegistryDelta::RemoveResource { snapshot, .. } => self.resource_hashes.extend(snapshot.hash),
_ => {}
}
if let Some(&position) = self.index.get(&delta.id) {
self.deltas[position] = delta;
return;
}
for parent in delta.all_parents() {
self.referenced.insert(parent);
self.tips.remove(&parent);
}
if !self.referenced.contains(&delta.id) {
self.tips.insert(delta.id);
}
self.index.insert(delta.id, self.deltas.len());
self.deltas.push(delta);
}
@@ -125,17 +64,22 @@ impl History {
self.deltas.iter()
}
/// The delta at `position` in topological order.
pub fn at(&self, position: usize) -> Option<&Delta> {
self.deltas.get(position)
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
///
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
/// (LWW apply is commutative, so the registry converges regardless of order).
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
for delta in incoming {
self.push(delta);
}
self.canonical_sort();
}
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
///
/// Deterministic: two peers that absorb the same delta set end up with byte-identical history, not two
/// different valid orderings. Arrival order is erased.
pub fn canonical_sort(&mut self) {
fn canonical_sort(&mut self) {
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
@@ -175,60 +119,11 @@ impl History {
}
}
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
pub fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
let mut seen = HashSet::new();
let mut stack: Vec<Rev> = roots.into_iter().filter(|rev| self.contains(*rev)).collect();
while let Some(rev) = stack.pop() {
if !seen.insert(rev) {
continue;
}
if let Some(delta) = self.get(rev) {
stack.extend(delta.all_parents());
}
}
seen
}
pub fn is_ancestor(&self, ancestor: Rev, descendant: Rev) -> bool {
self.ancestors([descendant]).contains(&ancestor)
}
/// `tip` plus the revs at first-parent distance 1, 2, 4, 8, ... behind it. Sent to a remote peer
/// so it can locate the divergence point within a factor of two of the true distance.
pub fn sample_chain(&self, tip: Rev) -> Vec<Rev> {
let mut samples = vec![tip];
let mut current = tip;
let mut distance = 0;
let mut next_sample_distance = 1;
while let Some(parent) = self.get(current).and_then(|delta| delta.parent) {
current = parent;
distance += 1;
if distance == next_sample_distance {
samples.push(current);
next_sample_distance *= 2;
}
}
// The root always: two copies of one document share it however far their lines have diverged, so
// a peer answering the sample can tell a divergent copy from a stranger and merge rather than replace.
if samples.last() != Some(&current) {
samples.push(current);
}
samples
}
/// Every delta not reachable from the `known` revs the remote peer reported, in topological order.
pub fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
let known = self.ancestors(known);
self.deltas.iter().filter(|delta| !known.contains(&delta.id)).collect()
}
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
pub fn tips(&self) -> Vec<Rev> {
let mut tips: Vec<Rev> = self.tips.iter().copied().collect();
let referenced: std::collections::HashSet<Rev> = self.deltas.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = self.deltas.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
tips.sort_unstable();
tips
}
@@ -1,283 +0,0 @@
//! What people say about a document's history, kept beside it rather than in it: who its users are, what
//! its steps are called and which are tagged. None of it is folded into the document, so moving the head
//! never changes it and stating it never rewrites a delta. Every statement is a [`MetadataFact`] with a
//! wall-clock stamp, the newer of two about the same thing winning, which makes the record a state that
//! merges the same in any order and any number of times. On disk the facts are appended one per line and
//! folded on read, so a rename appends one line and nothing is ever rewritten.
use crate::ids::{PeerId, Rev, UserId};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// When a fact was stated and by whom: milliseconds since the Unix epoch, the peer breaking ties.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct WallStamp {
pub ms: u64,
pub peer: PeerId,
}
/// What a fact is about.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum Subject {
User(UserId),
Rev(Rev),
}
/// One statement: an attribute of a user or of a rev, with its stamp. The unit of the file and of a merge.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataFact {
pub subject: Subject,
pub key: String,
pub value: serde_json::Value,
pub stamp: WallStamp,
}
/// One stated value with its stamp, as the folded record holds it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Fact {
pub value: serde_json::Value,
pub stamp: WallStamp,
}
/// Everything on record about one user.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UserRecord {
pub user: UserId,
pub attributes: BTreeMap<String, Fact>,
}
/// Everything on record about one rev: the interaction it closes, in the History panel's terms.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RevRecord {
pub rev: Rev,
pub attributes: BTreeMap<String, Fact>,
}
/// The attribute keys the editor writes for a user.
pub mod user_attr {
/// The display name the user chose. Absent or empty means unnamed.
pub const NAME: &str = "name";
}
/// The attribute keys the editor writes for a rev.
pub mod rev_attr {
/// The name a person gave the interaction the rev closes. Absent or empty means unnamed.
pub const LABEL: &str = "label";
/// A tag on the rev, one key per tag name after this prefix; `true` while it stands, `false` once removed.
pub const TAG_PREFIX: &str = "tag:";
}
/// The folded record. Users and revs are kept sorted so two copies holding the same facts serialize alike.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct HistoryMetadata {
#[serde(default)]
pub users: Vec<UserRecord>,
#[serde(default)]
pub revs: Vec<RevRecord>,
}
impl HistoryMetadata {
pub fn is_empty(&self) -> bool {
self.users.is_empty() && self.revs.is_empty()
}
/// The record folded from facts in file order: each fact lands unless a newer one about the same thing stands.
pub fn fold(facts: impl IntoIterator<Item = MetadataFact>) -> Self {
let mut record = Self::default();
for fact in facts {
record.absorb(fact);
}
record
}
/// Every fact the record holds, users first then revs, for writing it out whole.
pub fn facts(&self) -> Vec<MetadataFact> {
let users = self.users.iter().flat_map(|record| {
record.attributes.iter().map(|(key, fact)| MetadataFact {
subject: Subject::User(record.user),
key: key.clone(),
value: fact.value.clone(),
stamp: fact.stamp,
})
});
let revs = self.revs.iter().flat_map(|record| {
record.attributes.iter().map(|(key, fact)| MetadataFact {
subject: Subject::Rev(record.rev),
key: key.clone(),
value: fact.value.clone(),
stamp: fact.stamp,
})
});
users.chain(revs).collect()
}
pub fn user(&self, user: UserId) -> Option<&UserRecord> {
self.users.binary_search_by_key(&user, |record| record.user).ok().map(|index| &self.users[index])
}
pub fn user_attribute(&self, user: UserId, key: &str) -> Option<&Fact> {
self.user(user)?.attributes.get(key)
}
/// The user's display name, if one is on record and not empty.
pub fn user_name(&self, user: UserId) -> Option<&str> {
self.user_attribute(user, user_attr::NAME)?.value.as_str().filter(|name| !name.is_empty())
}
pub fn rev(&self, rev: Rev) -> Option<&RevRecord> {
self.revs.binary_search_by_key(&rev, |record| record.rev).ok().map(|index| &self.revs[index])
}
pub fn rev_attribute(&self, rev: Rev, key: &str) -> Option<&Fact> {
self.rev(rev)?.attributes.get(key)
}
/// The name a person gave the interaction `rev` closes, if any and not empty.
pub fn rev_label(&self, rev: Rev) -> Option<&str> {
self.rev_attribute(rev, rev_attr::LABEL)?.value.as_str().filter(|label| !label.is_empty())
}
/// The tags standing on `rev`, in name order.
pub fn rev_tags(&self, rev: Rev) -> Vec<&str> {
let Some(record) = self.rev(rev) else { return Vec::new() };
record
.attributes
.iter()
.filter(|(_, fact)| fact.value == serde_json::Value::Bool(true))
.filter_map(|(key, _)| key.strip_prefix(rev_attr::TAG_PREFIX))
.collect()
}
/// State a fact about a user. Nothing changes when the same value already stands, whatever its stamp;
/// otherwise the fact is stamped no earlier than the one it replaces, so a clock behind a peer's still
/// gets its say. Returns the fact as stated, for appending to the file and telling the room.
pub fn set_user_attribute(&mut self, user: UserId, key: &str, value: serde_json::Value, stamp: WallStamp) -> Option<MetadataFact> {
self.state(Subject::User(user), key, value, stamp)
}
/// State a fact about a rev; see [`set_user_attribute`](Self::set_user_attribute).
pub fn set_rev_attribute(&mut self, rev: Rev, key: &str, value: serde_json::Value, stamp: WallStamp) -> Option<MetadataFact> {
self.state(Subject::Rev(rev), key, value, stamp)
}
fn state(&mut self, subject: Subject, key: &str, value: serde_json::Value, mut stamp: WallStamp) -> Option<MetadataFact> {
let attributes = self.attributes_mut(subject);
if let Some(existing) = attributes.get(key) {
if existing.value == value {
return None;
}
if stamp <= existing.stamp {
stamp.ms = existing.stamp.ms + 1;
}
}
attributes.insert(key.to_string(), Fact { value: value.clone(), stamp });
Some(MetadataFact {
subject,
key: key.to_string(),
value,
stamp,
})
}
/// Take on one fact as stated elsewhere: it lands unless an equal or newer stamp stands for the same thing.
/// Returns whether it landed.
pub fn absorb(&mut self, fact: MetadataFact) -> bool {
let attributes = self.attributes_mut(fact.subject);
if attributes.get(&fact.key).is_some_and(|mine| fact.stamp <= mine.stamp) {
return false;
}
attributes.insert(fact.key, Fact { value: fact.value, stamp: fact.stamp });
true
}
/// Take on another copy's record: for every key, the newer stamp wins. Returns the facts that landed, for
/// appending to the file.
pub fn merge(&mut self, other: &Self) -> Vec<MetadataFact> {
other.facts().into_iter().filter(|fact| self.absorb(fact.clone())).collect()
}
fn attributes_mut(&mut self, subject: Subject) -> &mut BTreeMap<String, Fact> {
match subject {
Subject::User(user) => {
let index = match self.users.binary_search_by_key(&user, |record| record.user) {
Ok(index) => index,
Err(index) => {
self.users.insert(index, UserRecord { user, attributes: BTreeMap::new() });
index
}
};
&mut self.users[index].attributes
}
Subject::Rev(rev) => {
let index = match self.revs.binary_search_by_key(&rev, |record| record.rev) {
Ok(index) => index,
Err(index) => {
self.revs.insert(index, RevRecord { rev, attributes: BTreeMap::new() });
index
}
};
&mut self.revs[index].attributes
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn stamp(ms: u64, peer: u64) -> WallStamp {
WallStamp { ms, peer: PeerId(peer) }
}
fn rev(n: u128) -> Rev {
Rev::new(n).expect("non-zero")
}
#[test]
fn the_newer_fact_wins_whatever_order_the_copies_meet_in() {
let mut a = HistoryMetadata::default();
let mut b = HistoryMetadata::default();
assert!(a.set_user_attribute(UserId(1), user_attr::NAME, "Ada".into(), stamp(10, 1)).is_some());
assert!(b.set_user_attribute(UserId(1), user_attr::NAME, "Ada L.".into(), stamp(20, 2)).is_some());
let mut ab = a.clone();
assert_eq!(ab.merge(&b).len(), 1);
let mut ba = b.clone();
assert!(ba.merge(&a).is_empty());
assert_eq!(ab, ba);
assert_eq!(ab.user_name(UserId(1)), Some("Ada L."));
assert!(ab.merge(&b).is_empty(), "merging again changes nothing");
}
#[test]
fn a_clock_behind_a_peers_still_gets_its_say() {
let mut record = HistoryMetadata::default();
record.set_user_attribute(UserId(1), user_attr::NAME, "Ada".into(), stamp(100, 2));
let stated = record.set_user_attribute(UserId(1), user_attr::NAME, "Countess".into(), stamp(5, 1)).expect("a change");
assert_eq!(stated.stamp.ms, 101);
assert_eq!(record.user_name(UserId(1)), Some("Countess"));
assert!(
record.set_user_attribute(UserId(1), user_attr::NAME, "Countess".into(), stamp(500, 1)).is_none(),
"the same value is no change"
);
}
#[test]
fn the_fold_of_the_facts_is_the_record_and_back() {
let mut record = HistoryMetadata::default();
record.set_user_attribute(UserId(9), user_attr::NAME, "".into(), stamp(1, 1));
record.set_user_attribute(UserId(3), user_attr::NAME, "Bea".into(), stamp(1, 1));
record.set_rev_attribute(rev(7), rev_attr::LABEL, "Fixed the eye".into(), stamp(2, 1));
record.set_rev_attribute(rev(7), "tag:v1", true.into(), stamp(3, 1));
record.set_rev_attribute(rev(7), "tag:draft", false.into(), stamp(4, 1));
assert_eq!(record.user_name(UserId(9)), None);
assert_eq!(record.users.iter().map(|record| record.user).collect::<Vec<_>>(), vec![UserId(3), UserId(9)]);
assert_eq!(record.rev_label(rev(7)), Some("Fixed the eye"));
assert_eq!(record.rev_tags(rev(7)), vec!["v1"]);
let facts = record.facts();
assert_eq!(facts.len(), 5);
assert_eq!(HistoryMetadata::fold(facts), record);
}
}
-2
View File
@@ -56,8 +56,6 @@ pub const ROOT_NETWORK: NetworkId = NetworkId(0);
/// Upper bound on a network's export slot count, guarding `SetExport` against a malicious or corrupted
/// slot index forcing an unbounded `exports` allocation.
pub(crate) const MAX_EXPORT_SLOTS: usize = 1 << 16;
/// A per-slot write can bring a slot past the end of the list into being, so it is capped the same way.
pub(crate) const MAX_INPUT_SLOTS: usize = 1 << 16;
/// Per-device identity. Stable per `(device, document)`. Used for CRDT tiebreaking and `NodeId`
/// scoping. Globally unique across all peers ever in a document.
+2 -11
View File
@@ -5,13 +5,11 @@ pub mod crdt;
pub mod delta;
pub mod document;
pub mod history;
pub mod history_metadata;
pub mod ids;
pub mod model;
pub mod registry;
pub mod resources;
pub mod session;
pub mod touched;
#[cfg(any(feature = "conversion", test))]
pub mod from_runtime;
@@ -24,28 +22,21 @@ pub use attributes::*;
pub use crdt::*;
pub use document::*;
pub use history::History;
pub use history_metadata::{Fact, HistoryMetadata, MetadataFact, RevRecord, Subject, UserRecord, WallStamp, rev_attr, user_attr};
pub use ids::*;
pub use model::*;
pub use registry::*;
pub use resources::*;
pub use session::*;
pub use touched::Touched;
#[cfg(any(feature = "conversion", test))]
pub use from_runtime::{
PathResolver, RuntimeConversion, ScopedConversion, convert_input_attributes, convert_resource_entry, decode_declaration, encode_declaration, encode_input_ui_attributes, encode_node_ui_attributes,
node_value_resource_refs, value_resource_ref,
};
pub use from_runtime::{RuntimeConversion, decode_declaration, encode_declaration};
#[cfg(any(feature = "conversion", test))]
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
#[cfg(any(feature = "conversion", test))]
pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProjection};
pub use to_runtime::Declarations;
#[cfg(test)]
mod tests {
mod bookkeeping;
mod crdt;
mod projection;
mod round_trip;
}
+28 -22
View File
@@ -8,15 +8,11 @@ use std::collections::HashMap;
use core_types::uuid::NodeId as RuntimeNodeId;
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`.
#[derive(Clone, Debug, PartialEq)]
pub struct NodeMetadataEntry {
pub network_path: Vec<RuntimeNodeId>,
pub local_id: RuntimeNodeId,
/// The node's storage identity. Restoring it pins the node to this identity, so a later conversion
/// keeps it instead of re-deriving one from the node's location.
pub storage_id: crate::NodeId,
pub position: Option<Position>,
pub is_layer: bool,
pub display_name: Option<String>,
@@ -28,7 +24,19 @@ pub struct NodeMetadataEntry {
pub output_names: Vec<String>,
}
/// Per-network metadata. Separate from `NodeMetadataEntry` since these are
impl NodeMetadataEntry {
pub fn is_empty(&self) -> bool {
self.position.is_none()
&& !self.is_layer
&& self.display_name.is_none()
&& !self.locked
&& !self.pinned
&& self.output_names.is_empty()
&& self.input_metadata.iter().all(InputMetadataEntry::is_empty)
}
}
/// Per-network metadata (navigation, previewing). Separate from `NodeMetadataEntry` since these are
/// properties of a network, not of any node.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NetworkMetadataEntry {
@@ -36,12 +44,16 @@ pub struct NetworkMetadataEntry {
/// Empty = root network.
pub network_path: Vec<RuntimeNodeId>,
/// Stable storage id of this network. Lets the editor associate per-network, per-peer view state
/// (the node-graph nav, in `session.json`) with a network across reparenting.
/// (node-graph nav + previewing, in `session.json`) with a network across reparenting.
pub network_id: crate::NetworkId,
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference`: the definition lineage tag.
/// Matches the runtime's `NodeNetworkPersistentMetadata::reference` — definition lineage tag.
pub reference: Option<String>,
/// The display order of the network's pinned nodes.
pub pinned_order: Vec<RuntimeNodeId>,
}
impl NetworkMetadataEntry {
pub fn is_empty(&self) -> bool {
self.reference.is_none()
}
}
/// Per-input editor metadata. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
@@ -55,6 +67,12 @@ pub struct InputMetadataEntry {
pub input_data: HashMap<String, serde_json::Value>,
}
impl InputMetadataEntry {
pub fn is_empty(&self) -> bool {
self.input_name.is_none() && self.input_description.is_none() && self.widget_override.is_none() && self.input_data.is_empty()
}
}
/// Editor-side metadata source. Methods default to "no data" so implementors only override what
/// they carry. Returns are JSON-shaped where the underlying types live editor-side (PTZ, etc.).
pub trait NodeMetadataSource {
@@ -92,21 +110,9 @@ pub trait NodeMetadataSource {
HashMap::new()
}
/// The storage identity this node is pinned to, if it has one. A node the source does not name
/// falls back to a hash of its location.
fn storage_node_id(&self, _network_path: &[RuntimeNodeId], _local_id: RuntimeNodeId) -> Option<crate::NodeId> {
None
}
/// The definition the network was instantiated from, if it still names one.
fn reference(&self, _network_path: &[RuntimeNodeId]) -> Option<&str> {
None
}
/// The display order of the network's pinned nodes.
fn pinned_order(&self, _network_path: &[RuntimeNodeId]) -> Vec<RuntimeNodeId> {
Vec::new()
}
}
/// No-op metadata source. Use when there's nothing to attach (synthetic networks, CLI tools).
-89
View File
@@ -4,29 +4,9 @@ use std::borrow::Cow;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Node {
/// When the node was last added, so a concurrent addition of the same id and a removal resolve by
/// last-writer-wins rather than by arrival order. See [`Registry::removed_nodes`](crate::Registry::removed_nodes).
#[serde(default)]
pub(crate) presence: TimeStamp,
/// When the node was last added, which is what decides its network between concurrent additions
/// of one id; every other field carries its own timestamp.
#[serde(default)]
pub(crate) added: TimeStamp,
/// When the input list last changed shape, so a whole-list write and a per-slot write resolve the
/// same whichever lands first: the list follows the newer of the two, and a slot the older list also
/// held keeps whichever of its values is newer.
#[serde(default)]
pub(crate) inputs_timestamp: TimeStamp,
pub(crate) implementation: Implementation,
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
#[serde(default)]
pub(crate) implementation_timestamp: TimeStamp,
pub(crate) inputs: Vec<InputSlot>,
pub(crate) attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub(crate) attributes_timestamp: TimeStamp,
pub(crate) network: NetworkId,
}
@@ -63,42 +43,12 @@ impl Node {
attributes_value_equal(&self.attributes, &other.attributes)
}
/// A node in `network` whose `inputs` slots are unset, for a caller that fills them in with
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
/// slot by position.
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
let slot = InputSlot::unset(TimeStamp::ORIGIN);
Self {
presence: TimeStamp::ORIGIN,
added: TimeStamp::ORIGIN,
inputs_timestamp: TimeStamp::ORIGIN,
implementation,
implementation_timestamp: TimeStamp::ORIGIN,
inputs: vec![slot; inputs],
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
network,
}
}
/// Dead content for a node nothing has added yet, so a write arriving ahead of the addition has
/// somewhere to land. Every field is at the origin, so the addition's values win when it comes.
pub(crate) fn placeholder() -> Self {
Self::new(crate::ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(0)), 0)
}
#[cfg(test)]
pub(crate) fn dummy() -> Self {
Self {
presence: TimeStamp::ORIGIN,
added: TimeStamp::ORIGIN,
inputs_timestamp: TimeStamp::ORIGIN,
implementation: Implementation::ProtoNode(ResourceId::new()),
implementation_timestamp: TimeStamp::default(),
inputs: vec![],
attributes: Attributes::new(),
attributes_timestamp: TimeStamp::ORIGIN,
network: crate::ROOT_NETWORK,
}
}
@@ -111,26 +61,6 @@ pub struct InputSlot {
pub input: NodeInput,
pub timestamp: TimeStamp,
pub attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub attributes_timestamp: TimeStamp,
}
impl InputSlot {
/// A slot holding nothing, stamped `at`.
pub fn unset(at: TimeStamp) -> Self {
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
Self {
input: NodeInput::Value {
value: serde_json::Value::String("None".to_string()),
exposed: false,
},
timestamp: at,
attributes: Attributes::new(),
attributes_timestamp: at,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -162,16 +92,10 @@ pub enum Implementation {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Network {
/// When the network was last added; see [`Node::presence`].
#[serde(default)]
pub presence: TimeStamp,
pub exports: Vec<ExportSlot>,
/// Per-network `ui::*` state (navigation, previewing). Separate from `Node.attributes` so
/// view-state edits LWW independently.
pub attributes: Attributes,
/// When `attributes` was last written whole; see [`Attributes`].
#[serde(default)]
pub attributes_timestamp: TimeStamp,
}
impl Network {
@@ -230,19 +154,6 @@ mod tests {
}
}
/// `to_runtime` has to read back what `Node::new` writes into an unset slot, so its literal must stay
/// in step with how `TaggedValue::None` serializes.
#[test]
fn unset_input_slot_deserializes_as_tagged_value_none() {
let node = Node::new(crate::ROOT_NETWORK, Implementation::Network(crate::ROOT_NETWORK), 1);
let NodeInput::Value { value, .. } = &node.inputs()[0].input else {
panic!("a fresh slot holds a value input");
};
let tagged: graph_craft::document::value::TaggedValue = serde_json::from_value(value.clone()).expect("the unset slot value must deserialize");
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
}
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
/// the same network without that slot, so the soak oracle doesn't false-report drift.
#[test]
+8 -63
View File
@@ -1,14 +1,7 @@
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// The live document: what exists and what it holds.
///
/// Every field is last-writer-wins on a timestamp, including whether an entity exists, so the registry
/// is a function of the set of ops applied and not of their order. An entity that was removed keeps a
/// tombstone here with the removal's timestamp: an addition or a write stamped earlier is recognised as
/// older and dropped whichever order it arrives in, and a write stamped later revives the entity from
/// the tombstone. The live maps hold only what exists, so a reader never sees a tombstone.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Registry {
pub node_instances: HashMap<NodeId, Node>,
@@ -16,61 +9,13 @@ pub struct Registry {
/// Content-addressable resources (images, fonts, eventually proto-node declarations) referenced
/// by `ResourceId`. See [`ResourceStore`].
pub resources: ResourceStore,
/// Which person each device is: a per-device `PeerId` to a per-human `UserId`, registered by a device's
/// first contribution via `RegistryDelta::RegisterPeer` and again whenever its user changes. Last writer
/// wins on the stamp like every other field, so undo and history authorship scope by person across the
/// peer ids one person accumulates.
pub peer_users: HashMap<PeerId, PeerRegistration>,
/// Append-only mapping from per-device `PeerId` to per-human `UserId`.
/// Registered by each device's first contribution via `RegistryDelta::RegisterPeer`.
pub peer_users: HashMap<PeerId, UserId>,
pub attributes: Attributes,
#[serde(default)]
pub removed_nodes: HashMap<NodeId, Tombstone<Node>>,
#[serde(default)]
pub removed_networks: HashMap<NetworkId, Tombstone<Network>>,
#[serde(default)]
pub removed_resources: HashMap<ResourceId, Tombstone<ResourceEntry>>,
}
/// A device's registration to a person, and when it was made.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerRegistration {
pub user: UserId,
pub at: TimeStamp,
}
/// A removed entity: its content as of the removal, for reviving it, and when it was removed, for
/// deciding whether a later-arriving op is older or newer than the removal.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Tombstone<T> {
pub content: T,
pub at: TimeStamp,
/// Nothing has added the entity yet: the content only holds writes that arrived ahead of the addition,
/// and the entity stays dead until one folds in. See [`Registry::removed_nodes`].
#[serde(default)]
pub placeholder: bool,
}
impl Registry {
/// The node under `id`, live or as it was when removed. For a reference to a node the runtime cannot
/// hold, which still needs the id the node had there.
pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> {
self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content))
}
/// The network under `id`, live or as it was when removed.
pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> {
self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content))
}
/// Whether both registries removed the same entities at the same times. The removal marks decide
/// how ops still to arrive land, so two registries that agree on their values but not on these
/// will not stay agreed.
pub fn removal_marks_equal(&self, other: &Self) -> bool {
fn same<K: std::hash::Hash + Eq, T>(a: &HashMap<K, Tombstone<T>>, b: &HashMap<K, Tombstone<T>>) -> bool {
a.len() == b.len() && a.iter().all(|(id, mark)| b.get(id).is_some_and(|other| other.at == mark.at && other.placeholder == mark.placeholder))
}
same(&self.removed_nodes, &other.removed_nodes) && same(&self.removed_networks, &other.removed_networks) && same(&self.removed_resources, &other.removed_resources)
}
/// True if both registries agree on every value-bearing field, ignoring per-slot and
/// per-attribute timestamps. Mirrors `compute_deltas`'s value-only semantics, so unchanged
/// state at a stamped slot doesn't count as drift. `peer_users` is excluded: it isn't diffed by
@@ -140,10 +85,10 @@ impl Registry {
}
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
if crate::attributes::live(a).count() != crate::attributes::live(b).count() {
if a.len() != b.len() {
return false;
}
crate::attributes::live(a).all(|(key, value)| b.get(key).is_some_and(|other| !other.deleted && value.value == other.value))
a.iter().all(|(key, value)| b.get(key).is_some_and(|other| value.value == other.value))
}
/// Value-level resource comparison: same resolved hashes and same source chains (keyed by
@@ -155,8 +100,8 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
a.iter().all(|(id, entry)| {
b.get(id).is_some_and(|other| {
entry.hash == other.hash
&& entry.live_sources().count() == other.live_sources().count()
&& entry.live_sources().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
&& entry.sources.len() == other.sources.len()
&& entry.sources.iter().all(|(key, value)| other.source(key).is_some_and(|other_value| value.source == other_value.source))
})
})
}
+26 -118
View File
@@ -18,21 +18,6 @@ pub struct SourceKey {
pub struct SourceValue {
pub source: serde_json::Value,
pub timestamp: TimeStamp,
/// A removed source stays as a stamped tombstone, so an addition older than the removal is recognised
/// as older whichever order the two land in; readers see a tombstone as absent.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub deleted: bool,
}
impl SourceValue {
/// The tombstone of a source removed at `timestamp`.
pub fn deleted(timestamp: TimeStamp) -> Self {
Self {
source: serde_json::Value::Null,
timestamp,
deleted: true,
}
}
}
/// A single content-addressable resource: an ordered, conflict-mergeable chain of fallback sources
@@ -41,13 +26,8 @@ impl SourceValue {
/// resource agree by construction, since the hash is content-derived).
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct ResourceEntry {
/// When the entry was last added; see [`Node::presence`](crate::Node).
pub presence: TimeStamp,
/// Fallback chain kept sorted by `SourceKey`, so iteration yields highest-priority first.
pub sources: Vec<(SourceKey, SourceValue)>,
/// When `sources` was last written whole, by an addition of the entry: a key the chain does not hold
/// is deleted as of then, the way [`Attributes`](crate::Attributes) work.
pub sources_timestamp: TimeStamp,
pub hash: Option<ResourceHash>,
pub hash_timestamp: TimeStamp,
}
@@ -59,22 +39,12 @@ impl<'de> Deserialize<'de> for ResourceEntry {
// collapse any duplicate keys, keeping the higher-timestamp value (LWW).
#[derive(Deserialize)]
struct Raw {
#[serde(default)]
presence: TimeStamp,
sources: Vec<(SourceKey, SourceValue)>,
#[serde(default)]
sources_timestamp: TimeStamp,
hash: Option<ResourceHash>,
hash_timestamp: TimeStamp,
}
let Raw {
presence,
mut sources,
sources_timestamp,
hash,
hash_timestamp,
} = Raw::deserialize(deserializer)?;
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
sources.sort_by_key(|(a, _)| *a);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
@@ -87,13 +57,7 @@ impl<'de> Deserialize<'de> for ResourceEntry {
true
});
Ok(Self {
presence,
sources,
sources_timestamp,
hash,
hash_timestamp,
})
Ok(Self { sources, hash, hash_timestamp })
}
}
@@ -104,106 +68,52 @@ impl ResourceEntry {
pub fn embedded(hash: ResourceHash, peer: PeerId, timestamp: TimeStamp) -> Self {
let embedded = serde_json::to_value(graphene_resource::DataSource::Embedded).expect("DataSource::Embedded serializes");
let priority = Priority::new(0.).expect("0. is finite");
let sources = vec![(
SourceKey { priority, peer },
SourceValue {
source: embedded,
timestamp,
deleted: false,
},
)];
let sources = vec![(SourceKey { priority, peer }, SourceValue { source: embedded, timestamp })];
Self {
presence: timestamp,
sources,
sources_timestamp: timestamp,
hash: Some(hash),
hash_timestamp: timestamp,
}
}
/// The live source stored under `key`, if any; a tombstone is absent.
/// The source body and timestamp stored under `key`, if any.
pub fn source(&self, key: &SourceKey) -> Option<&SourceValue> {
self.sources
.binary_search_by(|(candidate, _)| candidate.cmp(key))
.ok()
.map(|index| &self.sources[index].1)
.filter(|value| !value.deleted)
}
/// The live sources in precedence order, tombstones skipped.
pub fn live_sources(&self) -> impl Iterator<Item = (&SourceKey, &SourceValue)> {
self.sources.iter().filter(|(_, value)| !value.deleted).map(|(key, value)| (key, value))
}
/// The stamp that decides a write to `key`: its entry's, tombstone included, or the chain's floor.
fn decided(&self, key: &SourceKey) -> TimeStamp {
self.sources
.binary_search_by(|(candidate, _)| candidate.cmp(key))
.ok()
.map_or(self.sources_timestamp, |index| self.sources[index].1.timestamp)
}
fn put(&mut self, key: SourceKey, value: SourceValue) {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => self.sources[index].1 = value,
Err(index) => self.sources.insert(index, (key, value)),
}
}
/// Writes the chain whole at `at`: every source is written then and every other key is deleted as of
/// then, which the floor records without a tombstone per key.
pub(crate) fn stamp_sources(&mut self, at: TimeStamp) {
self.sources.retain(|(_, value)| !value.deleted);
for (_, value) in &mut self.sources {
value.timestamp = at;
}
self.sources_timestamp = at;
}
/// Folds another chain in key by key, the way attribute maps merge: a key only one chain holds is
/// dead when the other chain's floor is newer than it, and the newer entry wins where both hold a key.
pub(crate) fn merge_sources(&mut self, other: Vec<(SourceKey, SourceValue)>, other_floor: TimeStamp) {
self.sources.retain(|(_, value)| value.timestamp >= other_floor);
for (key, value) in other {
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => {
if value.timestamp > self.sources[index].1.timestamp {
self.sources[index].1 = value;
}
}
Err(index) => {
if value.timestamp >= self.sources_timestamp {
self.sources.insert(index, (key, value));
}
}
}
}
self.sources_timestamp = self.sources_timestamp.max(other_floor);
self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)).ok().map(|index| &self.sources[index].1)
}
/// Insert or LWW-overwrite the entry at `key`. A re-set at an existing key wins only if `value`'s
/// timestamp is strictly newer; a fresh key is inserted in sorted position.
pub fn set_source(&mut self, key: SourceKey, value: SourceValue) {
if value.timestamp > self.decided(&key) {
self.put(key, value);
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => {
if value.timestamp > self.sources[index].1.timestamp {
self.sources[index].1 = value;
}
}
Err(index) => self.sources.insert(index, (key, value)),
}
}
/// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind), where the
/// precomputed reverse/forward value is authoritative even if its timestamp ties what it replaces.
pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) {
self.put(key, value);
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(&key)) {
Ok(index) => self.sources[index].1 = value,
Err(index) => self.sources.insert(index, (key, value)),
}
}
/// Remove the source at `key` if what decides it is strictly older than `timestamp` (LWW), leaving a
/// tombstone. Returns whether the removal landed.
/// Remove the entry at `key` if its timestamp is strictly older than `timestamp` (LWW). Returns
/// whether anything was removed.
pub fn remove_source(&mut self, key: &SourceKey, timestamp: TimeStamp) -> bool {
if timestamp <= self.decided(key) {
return false;
match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) {
Ok(index) if timestamp > self.sources[index].1.timestamp => {
self.sources.remove(index);
true
}
_ => false,
}
self.put(*key, SourceValue::deleted(timestamp));
true
}
/// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind).
@@ -220,7 +130,7 @@ impl ResourceEntry {
/// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into
/// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection.
pub fn has_embedded_source(&self) -> bool {
self.live_sources().any(|(_, value)| {
self.sources.iter().any(|(_, value)| {
matches!(
serde_json::from_value::<graphene_resource::DataSource>(value.source.clone()),
Ok(graphene_resource::DataSource::Embedded)
@@ -231,7 +141,7 @@ impl ResourceEntry {
/// A `SourceKey` ordered strictly ahead of every current source, so an inserted entry becomes the
/// highest-precedence fallback.
pub fn highest_precedence_key(&self, peer: PeerId) -> SourceKey {
let min_priority = self.live_sources().next().map(|(key, _)| key.priority.value()).unwrap_or(0.);
let min_priority = self.sources.first().map(|(key, _)| key.priority.value()).unwrap_or(0.);
SourceKey {
priority: Priority::new(min_priority - 1.).expect("finite priority minus one is finite"),
peer,
@@ -340,7 +250,6 @@ mod tests {
SourceValue {
source: serde_json::json!(priority),
timestamp: TimeStamp::ORIGIN,
deleted: false,
},
)
};
@@ -371,7 +280,6 @@ mod tests {
SourceValue {
source: serde_json::json!(body),
timestamp: TimeStamp { counter, peer: PeerId(1) },
deleted: false,
},
)
};
File diff suppressed because it is too large. Load diff
@@ -1,608 +0,0 @@
use std::collections::HashSet;
use crate::{AttributeDelta, Delta, History, MergeOutcome, Network, NetworkId, NodeId, PeerId, RegistryDelta, ResourceEntry, ResourceHash, ResourceId, Rev, Session, UserId};
fn set_attribute(key: &str, value: u32) -> RegistryDelta {
RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: key.to_string(),
value: Some(serde_json::json!(value)),
},
}
}
fn add_network(id: u64) -> RegistryDelta {
RegistryDelta::AddNetwork {
id: NetworkId(id),
network: Network::default(),
}
}
/// The tips as a scan finds them, for checking the maintained set against.
fn scanned_tips(history: &History) -> Vec<Rev> {
let referenced: HashSet<Rev> = history.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = history.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
tips.sort_unstable();
tips
}
/// Two peers that branch from a shared base, so their histories hold two tips until merged.
fn branched_pair() -> (Session, Session) {
let mut a = Session::with_peer(PeerId(1));
a.commit_op_for_test(set_attribute("base", 0)).expect("base");
let mut b = a.clone();
b.document.peer = PeerId(2);
b.document.clock = crate::LamportClock::new(PeerId(2));
a.commit_op_for_test(set_attribute("a", 1)).expect("a edit");
b.commit_op_for_test(set_attribute("b", 2)).expect("b edit");
(a, b)
}
#[test]
fn the_tip_set_follows_pushes_merges_and_sorts() {
let (mut a, b) = branched_pair();
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
a.merge(b.cloned_deltas()).expect("merge");
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history), "after a merge joining two branches");
assert_eq!(a.document.history.tips().len(), 1, "the merge delta is the one tip");
a.commit_op_for_test(set_attribute("after", 3)).expect("edit after the merge");
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
// A reload builds the same indexes from the ordered deltas.
let reloaded = History::from_ordered(a.cloned_deltas());
assert_eq!(reloaded.tips(), a.document.history.tips());
for delta in a.history() {
assert!(reloaded.contains_timestamp(delta.timestamp));
}
}
#[test]
fn history_names_the_resource_hashes_it_carries() {
let hash = ResourceHash::from(b"bytes".as_slice());
let id = ResourceId::new();
let mut session = Session::with_peer(PeerId(1));
session
.commit_op_for_test(RegistryDelta::AddResource {
id,
entry: ResourceEntry::embedded(hash, PeerId(1), crate::TimeStamp::ORIGIN),
})
.expect("add");
assert!(session.document.history.resource_hashes().contains(&hash));
let entry = session.retired_registry().resources[&id].clone();
session.commit_op_for_test(RegistryDelta::RemoveResource { id, snapshot: entry }).expect("remove");
assert!(session.all_referenced_resource_hashes().contains(&hash), "a removed resource's hash is still referenced from history");
}
/// A retirement from the host chains off the guest's last delta, so it is placed without a sort and
/// without walking ancestry, and the result is exactly what the sort would have produced.
#[test]
fn a_chain_off_the_last_delta_fast_forwards_without_sorting() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("base", 0)).expect("base");
let mut guest = host.clone();
guest.document.peer = PeerId(2);
host.commit_op_for_test(set_attribute("x", 1)).expect("x");
host.commit_op_for_test(add_network(5)).expect("network");
host.commit_op_for_test(set_attribute("y", 2)).expect("y");
let incoming: Vec<Delta> = host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect();
assert!(guest.document.history.extends_canonically(guest.history_len()), "an empty tail extends trivially");
let outcome = guest.merge(incoming).expect("merge");
assert!(matches!(outcome, MergeOutcome::FastForward(rev) if Some(rev) == host.head_rev()), "{outcome:?}");
assert_eq!(guest.history().map(|delta| delta.id).collect::<Vec<_>>(), host.history().map(|delta| delta.id).collect::<Vec<_>>());
let mut sorted = guest.document.history.clone();
sorted.canonical_sort();
assert_eq!(
sorted.iter().map(|delta| delta.id).collect::<Vec<_>>(),
guest.history().map(|delta| delta.id).collect::<Vec<_>>(),
"the appended order was already canonical"
);
assert!(guest.retired_registry().value_equal(host.retired_registry()));
}
#[test]
fn a_batch_off_an_earlier_delta_is_sorted_into_place() {
let (mut a, b) = branched_pair();
let before = a.history_len();
let incoming: Vec<Delta> = b.cloned_deltas().into_iter().filter(|delta| a.delta(delta.id).is_none()).collect();
a.merge(incoming).expect("merge");
assert!(!a.document.history.extends_canonically(before), "b's delta hangs off the base, not off a's last delta");
let mut sorted = a.document.history.clone();
sorted.canonical_sort();
assert_eq!(sorted.iter().map(|delta| delta.id).collect::<Vec<_>>(), a.history().map(|delta| delta.id).collect::<Vec<_>>());
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
}
/// Retirement takes the ops under the cutoff whatever order the log applied them in: every op commutes,
/// so the snapshot folds to the working registry's values with a later-stamped op left hot.
#[test]
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
let mut host = Session::with_peer(PeerId(1));
// A guest's op stamped late sits first in the log, ahead of an op stamped earlier: the log is in
// arrival order, and stamps are the authors' clocks, not the arrival order.
let late = crate::HotOp {
op: add_network(9),
timestamp: crate::TimeStamp { counter: 50, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
let own = crate::HotOp {
op: set_attribute("x", 1),
timestamp: crate::TimeStamp { counter: 20, peer: PeerId(3) },
sequence: crate::HotSequence(1),
};
host.apply_hot_op(late.clone()).expect("the late-stamped op lands first");
host.apply_hot_op(own.clone()).expect("the earlier-stamped op lands second");
assert_eq!(host.hot_ops_up_to(own.timestamp).len(), 1, "only the op under the cutoff retires");
host.retire(own.timestamp).expect("retire");
assert_eq!(host.hot_log().len(), 1, "the later-stamped op stays hot");
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
assert!(host.registry().networks.contains_key(&NetworkId(9)));
assert!(host.retired_registry().attributes.get("x").is_some_and(|value| !value.deleted));
host.retire(late.timestamp).expect("retire the rest");
assert!(host.hot_log().is_empty());
assert!(host.registry().value_equal(host.retired_registry()));
}
/// A transaction closes with a marker its author stages, and only closed transactions retire: an author's
/// ops past its last marker stay hot however old they are, while a later transaction from someone else
/// retires around them.
#[test]
fn only_closed_transactions_retire_and_an_open_one_stays_hot() {
let mut host = Session::with_peer(PeerId(1));
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
op,
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
sequence: crate::HotSequence(sequence),
};
assert!(host.end_transaction().expect("nothing to close").is_empty(), "no op of this peer is open");
// The guest opens a transaction and leaves it open, stamped earlier than everything the host does.
host.apply_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
host.apply_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("guest op");
host.stage_ops([set_attribute("host", 1)]).expect("host op");
let marker = host.end_transaction().expect("close").pop().expect("the host's transaction was open");
assert!(matches!(marker.op, RegistryDelta::EndTransaction));
assert!(host.end_transaction().expect("nothing more to close").is_empty(), "closing twice stages nothing");
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1, "the guest's open transaction is not listed: {closed:?}");
assert_eq!(closed[0].author, PeerId(1));
assert!(closed[0].contiguous);
assert_eq!(closed[0].ops.len(), 3, "RegisterPeer, the attribute write and the marker");
let revs = host.retire_transaction(&closed[0]).expect("retire");
assert_eq!(revs.len(), 2, "the marker commits no delta");
assert!(host.history().any(|delta| delta.id == revs[1] && delta.is_interaction_end()), "the transaction is one interaction");
assert_eq!(host.hot_log().len(), 2, "the guest's ops stay hot");
assert!(host.hot_log().iter().all(|hot_op| hot_op.timestamp.peer == PeerId(2)));
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
assert!(host.registry().networks.contains_key(&NetworkId(9)));
// The guest closes: its transaction retires after the host's although it is stamped before it.
host.apply_hot_op(guest_op(12, 3, RegistryDelta::EndTransaction)).expect("guest marker");
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1);
assert_eq!(closed[0].author, PeerId(2));
host.retire_transaction(&closed[0]).expect("retire");
assert!(host.hot_log().is_empty());
assert!(host.registry().value_equal(host.retired_registry()));
assert!(host.document.history.extends_canonically(0), "retirement order is the parent chain, so history stays append-only");
}
/// A transaction with a gap in its author's run is listed as not contiguous, so the retirer can wait for
/// the re-announcement, and closes normally once the gap fills.
#[test]
fn a_transaction_with_a_gap_is_not_contiguous_until_the_gap_fills() {
let mut host = Session::with_peer(PeerId(1));
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
op,
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
sequence: crate::HotSequence(sequence),
};
host.apply_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
host.apply_hot_op(guest_op(12, 3, RegistryDelta::EndTransaction)).expect("guest marker, op 2 still in flight");
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1);
assert!(!closed[0].contiguous);
host.apply_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("the late op");
let closed = host.closed_transactions();
assert!(closed[0].contiguous);
assert_eq!(closed[0].ops.len(), 3);
}
/// Taking a hot transaction back removes its ops for good and re-derives what they touched from the
/// snapshot and the other hot ops, so a concurrent write to the same entity survives; the ops never
/// retire, and a late copy is dropped.
#[test]
fn a_retracted_transaction_leaves_no_trace_and_keeps_what_others_wrote() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(add_network(3)).expect("base");
host.document.working_registry = host.document.retired_snapshot.clone();
// A guest's write to the network and the host's own gesture on the same network, interleaved.
let guest_write = crate::HotOp {
op: RegistryDelta::ChangeNetworkAttribute {
id: NetworkId(3),
delta: AttributeDelta {
key: "guest".into(),
value: Some(serde_json::json!(1)),
},
},
timestamp: crate::TimeStamp { counter: 40, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
host.stage_ops([RegistryDelta::ChangeNetworkAttribute {
id: NetworkId(3),
delta: AttributeDelta {
key: "host".into(),
value: Some(serde_json::json!(1)),
},
}])
.expect("host op");
host.apply_hot_op(guest_write.clone()).expect("guest op");
host.stage_ops([add_network(9)]).expect("host op");
let own: Vec<crate::HotOpId> = host.hot_log().iter().filter(|hot_op| hot_op.timestamp.peer == PeerId(1)).map(crate::HotOp::id).collect();
let crate::Retraction { ids, touched, ops } = host.retract_transaction().expect("retract").expect("the host's transaction is hot");
assert_eq!(ops.len(), 3, "RegisterPeer and the two writes come back for a redo, the marker does not");
assert_eq!(ids, own, "the whole open transaction is taken back");
assert!(touched.networks.contains(&NetworkId(3)) && touched.networks.contains(&NetworkId(9)));
assert_eq!(host.hot_log().len(), 1, "only the guest's op stays");
assert!(!host.registry().networks.contains_key(&NetworkId(9)));
let network = &host.registry().networks[&NetworkId(3)];
assert!(!network.attributes.contains_key("host"), "the host's write is gone");
assert!(network.attributes.contains_key("guest"), "the guest's concurrent write survives");
assert!(host.retract_transaction().expect("nothing left").is_none());
// A late copy of a retracted op is dropped, and nothing of it ever retires.
let late = crate::HotOp {
op: add_network(9),
timestamp: crate::TimeStamp { counter: 2, peer: PeerId(1) },
sequence: own[1].sequence,
};
host.replay_hot_op(late).expect("dropped, not an error");
assert_eq!(host.hot_log().len(), 1);
assert!(host.closed_transactions().is_empty());
// Another peer learns of the retraction from the marks alone.
let mut guest = Session::with_peer(PeerId(2));
guest.commit_op_for_test(add_network(3)).expect("base");
guest.document.working_registry = guest.document.retired_snapshot.clone();
guest
.apply_hot_op(crate::HotOp {
op: add_network(9),
timestamp: crate::TimeStamp { counter: 2, peer: PeerId(1) },
sequence: own[1].sequence,
})
.expect("the host's op reached the guest");
assert!(guest.registry().networks.contains_key(&NetworkId(9)));
let touched = guest.absorb_retracted_marks(host.retracted_marks());
assert!(touched.networks.contains(&NetworkId(9)));
assert!(!guest.registry().networks.contains_key(&NetworkId(9)));
assert!(guest.hot_log().is_empty());
}
/// A step the cursor walked away from is not sent to a peer, and a merge never joins it: the peer gets the
/// branch the cursor is on, and the undone step's effect stays gone.
#[test]
fn an_undone_branch_is_kept_to_itself() {
let mut author = Session::with_peer(PeerId(1));
author.commit_op_for_test(set_attribute("base", 0)).expect("base");
let base = author.head_rev().expect("base rev");
author.mark_interaction_end(base);
let mut peer = author.clone();
peer.document.peer = PeerId(2);
author.commit_op_for_test(set_attribute("undone", 1)).expect("the step to undo");
let undone = author.head_rev().expect("rev");
author.mark_interaction_end(undone);
author.undo().expect("undo");
assert_eq!(author.head_rev(), Some(base));
author.commit_op_for_test(set_attribute("kept", 2)).expect("a new branch");
let kept = author.head_rev().expect("rev");
let sent: Vec<Rev> = author.deltas_unknown_to(peer.known_revs()).into_iter().map(|delta| delta.id).collect();
assert_eq!(sent, vec![kept], "only the branch the cursor is on goes out, not the undone step");
assert!(author.delta(undone).is_some(), "the undone step stays in the author's DAG for a history panel");
let incoming: Vec<Delta> = sent.iter().filter_map(|&rev| author.delta(rev).cloned()).collect();
let outcome = peer.merge(incoming).expect("merge");
assert!(matches!(outcome, MergeOutcome::FastForward(rev) if rev == kept), "{outcome:?}");
assert!(peer.retired_registry().attributes.get("kept").is_some_and(|value| !value.deleted));
assert!(!peer.retired_registry().attributes.contains_key("undone"), "the undone step never reached the peer");
}
/// Undoing a retired step in a session drops it out of the shared line: the later steps are minted again
/// on its parent, the head moves, every peer that follows the move holds the same history and registry,
/// a field a later step wrote keeps that value, and the dropped step comes back on redo as a copy on top.
#[test]
fn a_dropped_interaction_leaves_the_line_and_the_room_follows() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("base", 0)).expect("base");
let base = host.head_rev().expect("rev");
host.mark_interaction_end(base);
// The guest's step, retired by the host: it writes its own key and one the host writes after it. A
// guest of its own, clock included, so its ops carry its authorship.
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let guest_ops = [set_attribute("guest", 1), set_attribute("shared", 1)];
let hot = guest.stage_ops(guest_ops).expect("stage");
for hot_op in &hot {
host.apply_hot_op(hot_op.clone()).expect("the guest's ops reach the host");
}
let guest_ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
let revs = host.retire_hot_ops(&guest_ids).expect("retire");
let undone = *revs.last().expect("the guest's step");
host.mark_interaction_end(undone);
guest
.merge(host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect::<Vec<Delta>>())
.expect("merge");
guest.discard_hot_ops(&guest_ids).expect("discard");
// A later step by the host writes the shared key.
host.commit_op_for_test(set_attribute("shared", 2)).expect("later step");
let later = host.head_rev().expect("rev");
host.mark_interaction_end(later);
host.stamp_retired_at(&[later], 1_234);
guest
.merge(host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect::<Vec<Delta>>())
.expect("merge");
assert_eq!(guest.head_rev(), host.head_rev());
assert_eq!(guest.latest_own_interaction(), Some(undone));
let (moved, touched) = host.drop_interaction(undone).expect("drop");
assert_eq!(moved.from, Some(later));
assert_eq!(moved.copies.len(), 1, "the later step is minted again");
assert_eq!(moved.copies[0].parent, Some(base), "the copy hangs off the dropped step's parent");
assert!(moved.copies[0].is_interaction_end(), "the copy keeps its interaction end");
assert_eq!(moved.copies[0].retired_at(), Some(1_234), "the copy keeps when the original was retired");
assert!(touched.nodes.is_empty() && !touched.resources, "document attributes only");
let snapshot = host.retired_registry();
assert!(snapshot.attributes.get("guest").is_none_or(|value| value.deleted), "the dropped step's write is gone");
assert_eq!(
snapshot.attributes.get("shared").map(|value| &value.value),
Some(&serde_json::json!(2)),
"the later step's write stands"
);
assert!(host.delta(undone).is_some() && host.delta(later).is_some(), "the abandoned branch stays for a history panel");
assert!(host.registry().value_equal(host.retired_registry()));
guest.apply_head_move(&moved).expect("follow");
assert_eq!(guest.head_rev(), host.head_rev());
assert_eq!(guest.retired_registry(), host.retired_registry());
assert_eq!(guest.history().map(|delta| delta.id).collect::<Vec<_>>(), host.history().map(|delta| delta.id).collect::<Vec<_>>());
assert!(
matches!(guest.apply_head_move(&moved), Err(crate::CrdtError::CursorMismatch { .. })),
"a move only applies from where it started"
);
// Redo: the dropped step returns as a copy on top, its older stamp losing the shared key.
let restored = host.restore_interaction(undone).expect("restore");
assert_eq!(restored.len(), 3, "RegisterPeer and the two writes come back");
assert!(host.retired_registry().attributes.get("guest").is_some_and(|value| value.value == serde_json::json!(1)));
assert_eq!(host.retired_registry().attributes.get("shared").map(|value| &value.value), Some(&serde_json::json!(2)));
guest
.merge(host.cloned_deltas().into_iter().filter(|delta| guest.delta(delta.id).is_none()).collect::<Vec<Delta>>())
.expect("merge the copies");
assert_eq!(guest.head_rev(), host.head_rev());
assert_eq!(guest.retired_registry(), host.retired_registry());
}
/// An author's ops can reach the retirer out of order, the later ones first through a re-announcement
/// after a lapsed link. Coarsening keeps the newest write by stamp, not by position in the log, so the
/// retired delta carries the value every working registry shows.
#[test]
fn a_transaction_that_arrived_out_of_order_retires_to_its_newest_write() {
let mut author = Session::with_peer(PeerId(2));
author.stage_ops(vec![set_attribute("name", 1), set_attribute("name", 2)]).expect("stage");
author.end_transaction().expect("close");
let ops = author.hot_log().to_vec();
let mut in_order = Session::with_peer(PeerId(1));
let mut reversed = Session::with_peer(PeerId(1));
for hot_op in &ops {
in_order.replay_hot_op(hot_op.clone()).expect("replay");
}
for hot_op in ops.iter().rev() {
reversed.replay_hot_op(hot_op.clone()).expect("replay");
}
for host in [&mut in_order, &mut reversed] {
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1);
host.retire_transaction(&closed[0]).expect("retire");
assert!(host.registry().value_equal(host.retired_registry()), "the retired value is the one the working registry showed");
}
assert_eq!(reversed.retired_registry(), in_order.retired_registry(), "arrival order decides nothing");
}
/// A transaction retires coarsened: of the writes to one field only the newest becomes a delta, a
/// whole-list input write supersedes the slot writes before it, a write wiring an input to a node stays
/// while what supersedes it wires elsewhere, and the fold is the one every op would have produced.
#[test]
fn a_transaction_retires_to_one_delta_per_field() {
let attribute = |value: u32| set_attribute("name", value);
let wire = |target: u64| RegistryDelta::ChangeNodeInput {
id: NodeId(1),
index: 0,
new_input: crate::NodeInput::Node { id: NodeId(target), index: 0 },
};
let value = |value: u32| RegistryDelta::ChangeNodeInput {
id: NodeId(1),
index: 1,
new_input: crate::NodeInput::Value {
value: serde_json::json!(value),
exposed: false,
},
};
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(add_network(3)).expect("network");
host.document.working_registry = host.document.retired_snapshot.clone();
let node = |id: u64| RegistryDelta::AddNode {
id: NodeId(id),
node: crate::Node::new(NetworkId(3), crate::Implementation::ProtoNode(ResourceId::from(7)), 2),
};
let ops = vec![node(1), node(2), node(4), attribute(1), value(1), attribute(2), wire(2), value(2), wire(4), attribute(3), value(3)];
let mut raw = host.clone();
raw.stage_ops(ops.clone()).expect("stage");
host.stage_ops(ops).expect("stage");
host.end_transaction().expect("close");
raw.end_transaction().expect("close");
let closed = host.closed_transactions();
assert_eq!(closed.len(), 1);
let coarsened = host.retire_transaction(&closed[0]).expect("retire");
let raw_ids: Vec<crate::HotOpId> = raw.hot_log().iter().map(crate::HotOp::id).collect();
let uncoarsened = raw.retire_hot_ops(&raw_ids).expect("retire raw");
assert_eq!(uncoarsened.len(), 12, "RegisterPeer, three additions and eight writes");
assert_eq!(
coarsened.len(),
8,
"RegisterPeer, three additions, the newest attribute, the newest value, and both wires: {coarsened:?}"
);
assert!(host.hot_log().is_empty());
assert!(host.retired_registry().value_equal(raw.retired_registry()), "the fold is unchanged");
assert!(host.registry().value_equal(host.retired_registry()), "the working registry, built from every op, agrees");
assert_eq!(host.retired_registry(), raw.retired_registry(), "stamps included: the survivor keeps its own");
let kinds: Vec<&RegistryDelta> = host.history().map(|delta| &delta.kind).collect();
assert!(kinds.iter().filter(|kind| matches!(kind, RegistryDelta::ChangeDocumentAttribute { .. })).count() == 1);
assert!(
kinds.iter().filter(|kind| matches!(kind, RegistryDelta::ChangeNodeInput { index: 0, .. })).count() == 2,
"the wire to node 2 stays as evidence node 2 exists"
);
assert!(kinds.iter().filter(|kind| matches!(kind, RegistryDelta::ChangeNodeInput { index: 1, .. })).count() == 1);
assert!(host.history().last().is_some_and(|delta| delta.is_interaction_end()));
}
/// A merge delta joins a line this peer holds as a branch it walked away from. Following it as a plain
/// extension of the line would leave that branch's effects out of the snapshot, so the snapshot is
/// folded from the joined head's whole ancestry instead, and matches the host's.
#[test]
fn following_a_merge_refolds_the_branch_it_joins() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(add_network(1)).expect("root");
let mut guest = Session::with_peer(PeerId(2));
let root: Vec<crate::Delta> = host.history().cloned().collect();
guest.follow(root, host.head_rev()).expect("follow the root");
// The guest retires a step of its own while apart, then follows the host's line, which leaves it behind.
guest.commit_op_for_test(add_network(2)).expect("own step");
let own: Vec<crate::Delta> = guest.history().filter(|delta| delta.author == PeerId(2)).cloned().collect();
host.commit_op_for_test(add_network(3)).expect("host step");
let line: Vec<crate::Delta> = host.history().cloned().collect();
guest.follow(line, host.head_rev()).expect("follow the host");
assert!(!guest.retired_registry().networks.contains_key(&NetworkId(2)), "the guest's own step is off the line");
// The host merges the guest's step and the guest follows to the joined head.
host.merge(own).expect("merge");
let merged: Vec<crate::Delta> = host.history().cloned().collect();
guest.follow(merged, host.head_rev()).expect("follow the merge");
let fold = guest.snapshot_from_history().expect("fold");
assert_eq!(guest.retired_registry(), &fold, "the snapshot is the fold of the joined head's ancestry");
assert!(guest.retired_registry().networks.contains_key(&NetworkId(2)), "the branch is back on the line");
assert_eq!(guest.retired_registry(), host.retired_registry());
assert!(guest.registry().value_equal(guest.retired_registry()));
}
/// A device's registration to a person is a write like any other: a later one replaces it, and a peer that
/// receives the two in the other order ends up with the same mapping.
#[test]
fn a_peers_registration_is_the_newest_by_stamp_whatever_order_it_lands() {
// Registration rides the staging path, so the steps go through the hot log and retire.
fn stage_and_retire(session: &mut Session, op: RegistryDelta) {
let hot = session.stage_ops([op]).expect("stage");
let ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
session.retire_hot_ops(&ids).expect("retire");
}
let mut device = Session::with_identity(PeerId(1), UserId(10));
stage_and_retire(&mut device, set_attribute("first", 1));
assert_eq!(device.user_of(PeerId(1)), Some(UserId(10)));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(10));
// The person at the device changes: the next batch registers again, and the newer registration wins.
device.set_user(UserId(20));
stage_and_retire(&mut device, set_attribute("second", 2));
assert_eq!(device.registry().peer_users[&PeerId(1)].user, UserId(20));
let registrations = device.history().filter(|delta| matches!(delta.kind, RegistryDelta::RegisterPeer { .. })).count();
assert_eq!(registrations, 2, "one registration per person the device stood for");
let mut reversed = Session::with_peer(PeerId(2));
let deltas: Vec<Delta> = device.cloned_deltas().into_iter().rev().collect();
reversed.merge(deltas).expect("merge");
assert_eq!(reversed.user_of(PeerId(1)), Some(UserId(20)), "the newest registration wins in any order");
assert_eq!(reversed.user_of(PeerId(2)), Some(UserId(2)), "a peer without a stored identity stands for itself");
}
/// Undo of a retired step in a session names the person's latest step, not the device's: a fresh copy of
/// the document under a new peer id still undoes what its user did from the old one, and nobody else's.
#[test]
fn undo_in_a_session_finds_the_users_step_from_another_peer() {
let mut host = Session::with_identity(PeerId(1), UserId(1));
host.commit_op_for_test(set_attribute("base", 0)).expect("base");
let base = host.head_rev().expect("rev");
host.mark_interaction_end(base);
let mut old_device = Session::load(PeerId(2), UserId(7), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let hot = old_device.stage_ops([set_attribute("mine", 1)]).expect("stage");
for hot_op in &hot {
host.apply_hot_op(hot_op.clone()).expect("the step reaches the host");
}
let ids: Vec<crate::HotOpId> = hot.iter().map(crate::HotOp::id).collect();
let revs = host.retire_hot_ops(&ids).expect("retire");
let step = *revs.last().expect("the step");
host.mark_interaction_end(step);
let new_device = Session::load(PeerId(3), UserId(7), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
assert_eq!(new_device.latest_own_interaction(), Some(step), "the same person under a new peer id owns the step");
assert!(new_device.is_mine(PeerId(2)));
let stranger = Session::load(PeerId(4), UserId(8), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
assert_eq!(stranger.latest_own_interaction(), None, "someone else has nothing of theirs to undo");
assert!(!stranger.is_mine(PeerId(2)));
}
#[test]
fn moving_the_head_back_leaves_the_line_since_as_a_branch_everyone_follows() {
let mut host = Session::with_identity(PeerId(1), UserId(1));
host.commit_op_for_test(set_attribute("a", 1)).expect("first");
let first = host.head_rev().expect("rev");
host.mark_interaction_end(first);
host.commit_op_for_test(set_attribute("b", 2)).expect("second");
let second = host.head_rev().expect("rev");
host.mark_interaction_end(second);
host.commit_op_for_test(set_attribute("c", 3)).expect("third");
let third = host.head_rev().expect("rev");
host.mark_interaction_end(third);
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let (moved, touched) = host.move_head_to(first).expect("move");
assert_eq!(moved.from, Some(third));
assert_eq!(moved.head, Some(first));
assert!(moved.copies.is_empty(), "nothing is minted: the line since is left behind");
assert!(touched.nodes.is_empty() && !touched.resources, "document attributes only");
let snapshot = host.retired_registry();
assert!(snapshot.attributes.get("b").is_none_or(|value| value.deleted), "the second step's write is gone");
assert!(snapshot.attributes.get("c").is_none_or(|value| value.deleted), "the third step's write is gone");
assert_eq!(snapshot.attributes.get("a").map(|value| &value.value), Some(&serde_json::json!(1)));
assert!(host.delta(second).is_some() && host.delta(third).is_some(), "the steps left behind stay as a branch");
assert!(host.registry().value_equal(host.retired_registry()));
guest.apply_head_move(&moved).expect("follow");
assert_eq!(guest.head_rev(), Some(first));
assert!(guest.retired_registry().value_equal(host.retired_registry()), "the follower folds to the same state");
}
+47 -698
View File
@@ -40,7 +40,6 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() {
let hot_op = HotOp {
op: remove_node_op(NodeId(99)),
timestamp: observed,
sequence: crate::HotSequence(1),
};
document.apply_hot_op(hot_op).expect("RemoveNode on absent node is a no-op, not an error");
@@ -183,10 +182,9 @@ fn merge_converges_to_identical_history() {
// Cross-merge: feed each peer the other's full delta set. The shared base dedups by `Rev`.
let deltas_a = session_a.cloned_deltas();
let deltas_b = session_b.cloned_deltas();
let merge_a = session_a.merge(deltas_b).expect("merge into A failed");
let merge_b = session_b.merge(deltas_a).expect("merge into B failed");
let merge_a = session_a.merge(deltas_b).expect("merge into A failed").expect("A produced a merge");
let merge_b = session_b.merge(deltas_a).expect("merge into B failed").expect("B produced a merge");
assert!(matches!(merge_a, crate::MergeOutcome::Merged(_)), "divergent branches must produce a merge delta");
assert_eq!(merge_a, merge_b, "same tips must mint the identical parent-set-addressed merge commit");
let order_a: Vec<crate::Rev> = session_a.history().map(|d| d.id).collect();
@@ -195,31 +193,9 @@ fn merge_converges_to_identical_history() {
assert_eq!(session_a.head_rev(), session_b.head_rev(), "both peers land on the same merge head");
}
/// A peer whose history is a prefix of the incoming one moves its head forward without minting a
/// merge delta, and the negotiated transfer sends only the deltas past the sampled known revs.
#[test]
fn merge_fast_forwards_a_prefix_history() {
let mut session_a = Session::with_peer(PeerId(1));
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
let mut session_b = session_a.clone();
for value in 1..=5 {
session_b.commit_op_for_test(set_document_attribute("compute::b", value)).expect("B edit");
}
let known = session_a.known_revs();
let missing: Vec<_> = session_b.deltas_unknown_to(known).into_iter().cloned().collect();
assert_eq!(missing.len(), 5, "only B's new commits are unknown to A");
let outcome = session_a.merge(missing).expect("merge failed");
assert_eq!(outcome, crate::MergeOutcome::FastForward(session_b.head_rev().unwrap()));
assert_eq!(session_a.history().count(), session_b.history().count(), "no merge delta was added");
assert_eq!(session_b.merge(session_a.cloned_deltas()).expect("merge failed"), crate::MergeOutcome::NoOp);
}
/// A write to a network removed on a merged-in branch revives it: the removal keeps the network as a
/// tombstone, and the write is newer than the removal.
/// Resurrection must reach into a merged-in branch: a network added then removed on the other peer's
/// branch lives only under the merge's secondary parent, so a `SetNetworkExport` targeting it after
/// the merge can only restore it by traversing all ancestors (not the primary-parent chain).
#[test]
fn resurrection_reaches_across_a_merge() {
let network_id = NetworkId(7);
@@ -246,15 +222,15 @@ fn resurrection_reaches_across_a_merge() {
// A merges B's branch: 7's AddNetwork now lives only under the merge's secondary parent.
session_a.merge(session_b.cloned_deltas()).expect("merge failed");
// A SetNetworkExport on 7 is newer than its removal, so it brings 7 back from its tombstone.
// A SetNetworkExport on 7 must resurrect it by walking into the merged-in branch. Before the
// all-ancestors fix this failed with NetworkNotInHistory (the primary-parent walk missed B's branch).
session_a
.commit_op_for_test(RegistryDelta::SetNetworkExport {
id: network_id,
index: 0,
export: None,
})
.expect("a write newer than the removal revives the network");
assert!(session_a.retired_registry().networks.contains_key(&network_id));
.expect("resurrection must find the AddNetwork on the merged-in branch");
}
/// Committing the same NodeNetwork twice must produce zero history entries on the second commit.
@@ -287,11 +263,7 @@ fn first_contribution_registers_the_peer() {
let registrations = first.iter().filter(|hot_op| matches!(hot_op.op, RegistryDelta::RegisterPeer { .. })).count();
assert_eq!(registrations, 1, "exactly one RegisterPeer on first contribution");
assert!(matches!(first[0].op, RegistryDelta::RegisterPeer { .. }), "RegisterPeer must precede the edit ops");
assert_eq!(
session.registry().peer_users.get(&PeerId(7)).map(|registration| registration.user),
Some(crate::UserId(7)),
"peer mapped to its UserId"
);
assert_eq!(session.registry().peer_users.get(&PeerId(7)), Some(&crate::UserId(7)), "peer mapped to its UserId");
// A second, distinct contribution must not re-register.
let mut other_network = tiny_network();
@@ -312,7 +284,7 @@ fn first_contribution_registers_the_peer() {
assert_eq!(fresh.registry().peer_users, peers_before, "a no-op batch must not add a registration");
}
/// A SetExport newer than a network.s removal revives the network from its tombstone rather than error.
/// A SetExport against a removed network must restore the network from history rather than error.
#[test]
fn set_export_resurrects_absent_network() {
let mut document = fresh_document(PeerId(1));
@@ -346,7 +318,7 @@ fn set_export_resurrects_absent_network() {
assert!(document.working_registry.networks.contains_key(&network_id), "SetExport should have resurrected the network");
}
/// An addition into a removed network is evidence the network exists, so it brings the network back.
/// Cascading resurrection: bringing a node back must also restore its owning network when absent.
#[test]
fn add_node_resurrects_owning_network() {
use crate::Node;
@@ -380,8 +352,9 @@ fn add_node_resurrects_owning_network() {
assert!(document.working_registry.node_instances.contains_key(&node_id), "the node itself should also be present");
}
/// The same revival arriving twice, from two peers reverting one removal, lands once: the second copy
/// is not newer than what the first wrote.
/// Reverting the same removal twice (the moral equivalent of two peers concurrently resurrecting
/// the same node) must not error on the second apply. Today the second revert hits
/// `apply_op(AddNode, false)` against a present node and returns `NodeAlreadyExists`.
#[test]
fn concurrent_resurrection_via_revert_is_idempotent() {
use crate::Node;
@@ -402,17 +375,38 @@ fn concurrent_resurrection_via_revert_is_idempotent() {
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed before the resurrection test");
let revive = RegistryDelta::AddNode {
id: node_id,
node: Node { network: network_id, ..Node::dummy() },
};
let at = document.clock.tick();
document.apply_op_idempotent(revive.clone(), at).expect("first revival");
assert!(document.working_registry.node_instances.contains_key(&node_id), "the first revival brings the node back");
document.restore_node_from_history(RegistryTarget::Working, node_id).expect("first resurrection should succeed");
assert!(document.working_registry.node_instances.contains_key(&node_id), "first resurrection should bring the node back");
let second = document.apply_op_idempotent(revive, at);
assert!(second.is_ok(), "the same revival again is a no-op, got {second:?}");
assert!(document.working_registry.node_instances.contains_key(&node_id));
let second = document.restore_node_from_history(RegistryTarget::Working, node_id);
assert!(second.is_ok(), "second resurrection of an already-present node should be a no-op, got {second:?}");
}
/// History-based resurrection must work when the matching delta is the *root* commit. The history
/// walk used to drop the root (its empty parent list short-circuited the iterator before yielding
/// it), so a node removed by the very first commit could not be restored.
#[test]
fn restore_node_from_root_commit() {
use crate::Node;
let mut document = fresh_document(PeerId(1));
let node_id = NodeId(42);
let node = Node::dummy();
// Seed the working state so the root commit can remove the node (its reverse is the `AddNode` the
// resurrection looks for). This `RemoveNode` is the only commit, so the match sits at the root.
document.working_registry.networks.insert(ROOT_NETWORK, Network::default());
document.retired_snapshot.networks.insert(ROOT_NETWORK, Network::default());
document.working_registry.node_instances.insert(node_id, node.clone());
document.retired_snapshot.node_instances.insert(node_id, node.clone());
commit_op(&mut document, RegistryDelta::RemoveNode { id: node_id, snapshot: node });
assert!(!document.working_registry.node_instances.contains_key(&node_id), "node should be removed by the root commit");
document
.restore_node_from_history(RegistryTarget::Working, node_id)
.expect("resurrection from the root commit should succeed");
assert!(document.working_registry.node_instances.contains_key(&node_id), "node must be restored from the root commit");
}
/// Erroring ops still bump the clock: we observed the timestamp on the wire, the fact that the
@@ -445,11 +439,6 @@ fn source_key(priority: f64, peer: u64) -> SourceKey {
}
}
/// Whether the map holds a live value under `key`: a deleted key stays as a tombstone.
fn holds(attributes: &crate::Attributes, key: &str) -> bool {
crate::attributes::live(attributes).any(|(held, _)| held == key)
}
fn ts(counter: u64, peer: u64) -> TimeStamp {
TimeStamp { counter, peer: PeerId(peer) }
}
@@ -574,10 +563,7 @@ fn remove_source_reverse_restores_prior() {
}
document.apply_op(RD::RemoveSource { id, key }, ts(5, 1)).unwrap();
assert!(
document.working_registry.resources.get(&id).unwrap().live_sources().next().is_none(),
"source removed, a tombstone left"
);
assert!(document.working_registry.resources.get(&id).unwrap().sources.is_empty(), "source removed");
// Applying the reverse restores the chain.
document.apply_op(reverse, ts(6, 1)).unwrap();
@@ -637,16 +623,7 @@ use crate::{ResourceEntry, ResourceStore, SourceValue};
fn entry_with_source(priority: f64, peer: u64, body: serde_json::Value, hash: Option<ResourceHash>) -> ResourceEntry {
ResourceEntry {
presence: ts(1, peer),
sources: vec![(
source_key(priority, peer),
SourceValue {
source: body,
timestamp: ts(1, peer),
deleted: false,
},
)],
sources_timestamp: TimeStamp::ORIGIN,
sources: vec![(source_key(priority, peer), SourceValue { source: body, timestamp: ts(1, peer) })],
hash,
hash_timestamp: ts(1, peer),
}
@@ -697,7 +674,6 @@ fn compute_deltas_diffs_resources_and_round_trips() {
SourceValue {
source: serde_json::json!("url"),
timestamp: ts(1, 1),
deleted: false,
},
);
to.insert(kept, kept_entry);
@@ -723,8 +699,6 @@ fn compute_deltas_diffs_resources_and_round_trips() {
// Apply the diff to a document seeded with `from`, then check it matches `to` by value.
let mut document = fresh_document(PeerId(1));
document.working_registry = registry_with_resources(from);
// A clock is past every stamp in the registry it edits, as a session.s persisted clock is.
document.clock.observe(ts(1, 1));
for op in deltas {
let timestamp = document.clock.tick();
document.apply_op(op, timestamp).expect("apply resource delta");
@@ -859,18 +833,12 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
input: crate::NodeInput::Import { index: 0 },
timestamp: TimeStamp::ORIGIN,
attributes: input_attributes,
attributes_timestamp: TimeStamp::ORIGIN,
}];
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: implementation.clone(),
implementation_timestamp: Default::default(),
inputs,
attributes,
attributes_timestamp: Default::default(),
network: ROOT_NETWORK,
}
};
@@ -911,622 +879,3 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order");
}
/// Commit a retired delta and mirror it onto the working registry; `commit_op_for_test` alone only
/// advances the snapshot zone.
fn commit_retired(session: &mut Session, op: RegistryDelta) {
let before = session.history().count();
session.commit_op_for_test(op).expect("commit failed");
for delta in session.cloned_deltas().into_iter().skip(before) {
session.document.apply_op_idempotent(delta.kind, delta.timestamp).expect("mirroring onto the working registry");
}
}
/// Merge `deltas` into a copy of `base` in the given order, reporting node 7's surviving `tint`.
fn merge_order_outcome(base: &Session, deltas: &[Delta], order: [usize; 2]) -> Option<(serde_json::Value, TimeStamp)> {
let mut session = base.clone();
let ordered: Vec<Delta> = order.iter().map(|&index| deltas[index].clone()).collect();
session.merge(ordered).expect("merge failed");
session
.retired_registry()
.node_instances
.get(&NodeId(7))
.and_then(|node| node.attributes.get("tint"))
.map(|value| (value.value.clone(), value.timestamp))
}
/// The raw ops are arrival-order dependent: change-first leaves the node gone, remove-first resurrects
/// it from the removal's snapshot. Merge has to fold both orders onto the same retired registry.
#[test]
fn a_concurrent_remove_and_attribute_change_commute() {
let network_id = NetworkId(5);
let node = Node::new(network_id, crate::Implementation::Network(network_id), 0);
// Shared base holding node 7, then the two peers diverge.
let mut base = Session::with_peer(PeerId(1));
commit_retired(
&mut base,
RegistryDelta::AddNetwork {
id: network_id,
network: Network::default(),
},
);
commit_retired(&mut base, RegistryDelta::AddNode { id: NodeId(7), node: node.clone() });
let mut remover = base.clone();
commit_retired(&mut remover, RegistryDelta::RemoveNode { id: NodeId(7), snapshot: node });
let mut changer = Session::with_peer(PeerId(2));
changer.merge(base.cloned_deltas()).expect("changer adopts the base");
commit_retired(
&mut changer,
RegistryDelta::ChangeNodeAttribute {
id: NodeId(7),
delta: crate::AttributeDelta {
key: "tint".to_string(),
value: Some(serde_json::json!(75)),
},
},
);
// One delta from each branch, neither an ancestor of the other.
let removal = remover.cloned_deltas().into_iter().last().expect("removal delta");
let change = changer.cloned_deltas().into_iter().last().expect("change delta");
let deltas = [removal, change];
let removal_first = merge_order_outcome(&base, &deltas, [0, 1]);
let change_first = merge_order_outcome(&base, &deltas, [1, 0]);
assert_eq!(removal_first, change_first, "the retired registry must not depend on delta arrival order");
}
/// An op can retire before an earlier one from its author arrives, so the marks cover it out of order.
/// The prefix absorbs it once the gap fills, which bounds the exception set.
#[test]
fn retired_marks_cover_a_gap_and_compact_once_it_fills() {
let author = PeerId(1);
let id = |sequence: u64| crate::HotOpId {
peer: author,
sequence: crate::HotSequence(sequence),
};
let mut marks = crate::RetiredHotOps::default();
marks.extend([id(1), id(2)]);
assert_eq!(marks.retired_up_to.get(&author), Some(&crate::HotSequence(2)), "a contiguous run folds straight into the prefix");
assert!(marks.retired_beyond.is_empty());
// Sequence 3 never arrived, so 4 retires above the prefix rather than extending it.
marks.extend([id(4)]);
assert_eq!(marks.retired_up_to.get(&author), Some(&crate::HotSequence(2)));
assert!(marks.covers(id(4)), "an op past the gap is still recognized as retired");
assert!(!marks.covers(id(3)), "the missing op is not claimed");
// The gap fills, so the prefix swallows both it and the exception behind it.
marks.extend([id(3)]);
assert_eq!(marks.retired_up_to.get(&author), Some(&crate::HotSequence(4)));
assert!(marks.retired_beyond.is_empty(), "the exception set empties once the prefix reaches it");
}
/// Marks merge by union, so adopting a peer's wholesale must not lose local coverage.
#[test]
fn absorbing_marks_keeps_both_sides_coverage() {
let author = PeerId(1);
let id = |sequence: u64| crate::HotOpId {
peer: author,
sequence: crate::HotSequence(sequence),
};
let mut local = crate::RetiredHotOps::default();
local.extend([id(1), id(4)]);
let mut remote = crate::RetiredHotOps::default();
remote.extend([id(1), id(2), id(3), id(5)]);
local.absorb(&remote);
// The union is 1..=5 contiguous, so it all collapses into the prefix.
assert_eq!(local.retired_up_to.get(&author), Some(&crate::HotSequence(5)));
assert!(local.retired_beyond.is_empty());
for sequence in 1..=5 {
assert!(local.covers(id(sequence)), "sequence {sequence} must stay covered");
}
}
/// Undo rewinds retired history and must leave the hot tail alone: copying the working registry onto
/// the snapshot promotes unretired work. Hot ops exist between staging and retirement even solo.
#[test]
fn undo_does_not_promote_hot_ops_into_the_retired_snapshot() {
let mut session = Session::with_peer(PeerId(1));
// Two retired interactions, so the second is undoable.
commit_retired(&mut session, set_document_attribute("first", 1));
let boundary = session.history().last().expect("a committed delta").id;
session.mark_interaction_end(boundary);
commit_retired(&mut session, set_document_attribute("second", 2));
// Unretired live work sitting on top, on a key no retired delta touches.
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
assert!(holds(&session.registry().attributes, "hot"), "the hot op must be in the working registry");
assert!(!holds(&session.retired_registry().attributes, "hot"), "and must not be in the snapshot");
session.undo().expect("undo");
assert!(!holds(&session.retired_registry().attributes, "second"), "undo must rewind the retired snapshot");
assert!(!holds(&session.retired_registry().attributes, "hot"), "undo promoted an unretired hot op into the retired snapshot");
}
/// Redo puts the interaction back on both zones, so the pair does not drift the other way.
#[test]
fn redo_restores_the_retired_snapshot_without_the_hot_tail() {
let mut session = Session::with_peer(PeerId(1));
commit_retired(&mut session, set_document_attribute("first", 1));
let boundary = session.history().last().expect("a committed delta").id;
session.mark_interaction_end(boundary);
commit_retired(&mut session, set_document_attribute("second", 2));
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
session.undo().expect("undo");
session.redo().expect("redo");
assert!(holds(&session.retired_registry().attributes, "second"), "redo must restore the retired delta");
assert!(!holds(&session.retired_registry().attributes, "hot"), "redo promoted an unretired hot op into the retired snapshot");
assert!(holds(&session.registry().attributes, "hot"), "the hot op must survive an undo/redo round trip");
}
/// Silent undo emits nothing, so it is only legal while a commit is unpublished. Once peers hold it, a
/// rewind would diverge from them for good.
#[test]
fn publishing_a_commit_disables_silent_undo() {
let mut session = Session::with_peer(PeerId(1));
commit_retired(&mut session, set_document_attribute("first", 1));
let boundary = session.history().last().expect("a committed delta").id;
session.mark_interaction_end(boundary);
commit_retired(&mut session, set_document_attribute("second", 2));
let head = session.head_rev().expect("a head");
assert!(session.can_undo(), "an unpublished interaction is undoable");
session.publish_up_to(head);
assert!(!session.can_undo(), "a published interaction must not be silently rewound");
}
/// An undone delta stays in the DAG for redo, outside `head`'s ancestry. A fold that ignores that
/// restores work the user undid.
#[test]
fn snapshot_from_history_ignores_undone_deltas() {
let mut session = Session::with_peer(PeerId(1));
commit_retired(&mut session, set_document_attribute("first", 1));
let boundary = session.history().last().expect("a committed delta").id;
session.mark_interaction_end(boundary);
commit_retired(&mut session, set_document_attribute("second", 2));
session.undo().expect("undo");
assert!(!holds(&session.retired_registry().attributes, "second"), "undo rewound the snapshot");
let folded = session.snapshot_from_history().expect("fold");
assert!(holds(&folded.attributes, "first"), "history still holds the kept interaction");
assert!(!holds(&folded.attributes, "second"), "a fold restored an undone delta");
}
/// A node removed, revived by a reference and removed again with a snapshot placing it elsewhere folds
/// to the same snapshot whether the deltas land one by one or all at once (simulation seed 3588534,
/// which once caught a revival reading the wrong removal).
#[test]
fn snapshot_from_history_reproduces_a_revival_between_two_removals() {
let node_id = NodeId(3);
let first_network = NetworkId(1);
let later_network = NetworkId(3);
let node_in = |network: NetworkId| Node { network, ..Node::dummy() };
let mut session = Session::with_peer(PeerId(1));
commit_retired(
&mut session,
RegistryDelta::AddNetwork {
id: first_network,
network: Network::default(),
},
);
commit_retired(
&mut session,
RegistryDelta::AddNode {
id: node_id,
node: node_in(first_network),
},
);
commit_retired(
&mut session,
RegistryDelta::RemoveNode {
id: node_id,
snapshot: node_in(first_network),
},
);
// Resurrects the node from the removal above, the only one so far.
commit_retired(
&mut session,
RegistryDelta::SetNetworkExport {
id: first_network,
index: 0,
export: Some(crate::NodeInput::Node { id: node_id, index: 0 }),
},
);
commit_retired(
&mut session,
RegistryDelta::AddNetwork {
id: later_network,
network: Network::default(),
},
);
// A later removal whose snapshot places the node in the network created after the export.
commit_retired(
&mut session,
RegistryDelta::RemoveNode {
id: node_id,
snapshot: node_in(later_network),
},
);
let folded = session.snapshot_from_history().expect("fold");
assert_eq!(&folded, session.retired_registry(), "the fold must reproduce the snapshot the deltas built as they landed");
}
/// The newtype is `#[serde(transparent)]`, so persisted state and the wire carry a bare number and the
/// field's encoding is unchanged.
#[test]
fn hot_sequence_serializes_as_a_bare_number() {
let encoded = serde_json::to_string(&crate::HotSequence(7)).expect("serialize");
assert_eq!(encoded, "7");
assert_eq!(serde_json::from_str::<crate::HotSequence>("7").expect("deserialize"), crate::HotSequence(7));
}
/// Retirement drains the hot log, so a retirer that never received an author's earlier op cannot
/// retire it. The later op still retires, landing beyond the author's prefix instead of extending it.
#[test]
fn retiring_over_a_gap_lands_beyond_the_prefix() {
let author = PeerId(2);
let mut host = Session::with_peer(PeerId(1));
// Only the author's second op reaches this peer; the first was lost with the link that carried it.
let second = HotOp {
op: set_document_attribute("late", 1),
timestamp: TimeStamp { counter: 9, peer: author },
sequence: crate::HotSequence(2),
};
host.apply_hot_op(second.clone()).expect("apply");
host.retire(second.timestamp).expect("retire");
let retired = host.retired_marks();
let prefix = retired.retired_up_to.get(&author).copied().unwrap_or(crate::HotSequence::NONE);
assert_eq!(prefix, crate::HotSequence::NONE, "sequence 1 never arrived, so the prefix cannot move");
assert!(retired.retired_beyond.contains_key(&author), "the retired op has to be recorded past the gap");
assert!(retired.covers(second.id()), "and still count as retired");
}
/// A gap that never fills pins the prefix, so every later op from that author lands past it. Stored as
/// runs, that stays one entry however many ops follow.
#[test]
fn a_permanent_gap_accumulates_every_later_op() {
let author = PeerId(2);
let id = |sequence: u64| crate::HotOpId {
peer: author,
sequence: crate::HotSequence(sequence),
};
let mut marks = crate::RetiredHotOps::default();
// Sequence 1 is lost for good; everything this author writes afterwards still retires.
for sequence in 2..=20 {
marks.extend([id(sequence)]);
}
let runs = marks.retired_beyond.get(&author).map(Vec::len).unwrap_or_default();
assert_eq!(runs, 1, "the ops after the gap coalesce into a single run");
for sequence in 2..=20 {
assert!(marks.covers(id(sequence)), "sequence {sequence} must stay covered");
}
assert!(!marks.covers(id(1)), "the lost op is not claimed");
}
/// A retired delta keeps its op's authoring timestamp, so the snapshot resolves LWW on the same stamps
/// the live view did rather than on retirement order.
#[test]
fn retirement_preserves_the_live_lww_winner() {
let mut host = Session::with_peer(PeerId(1));
// Same key from two authors, the newer op arriving first, so LWW keeps it and discards the older.
let newer = HotOp {
op: set_document_attribute("k", 1),
timestamp: TimeStamp { counter: 10, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
let older = HotOp {
op: set_document_attribute("k", 2),
timestamp: TimeStamp { counter: 5, peer: PeerId(3) },
sequence: crate::HotSequence(1),
};
host.apply_hot_op(newer.clone()).expect("apply newer");
host.apply_hot_op(older).expect("apply older");
let live = host.registry().attributes.get("k").cloned();
host.retire(newer.timestamp).expect("retire");
assert_eq!(host.registry().attributes.get("k"), live.as_ref(), "retirement must not move the live value");
assert_eq!(
host.retired_registry().attributes.get("k").map(|attribute| &attribute.value),
live.as_ref().map(|attribute| &attribute.value),
"the snapshot has to record the value the live view settled on"
);
}
/// A straggler LWW discarded still retires, and must not return by doing so: stamped at retirement it
/// would outrank the op that beat it, putting the discarded value into history itself.
#[test]
fn retiring_a_straggler_leaves_the_discarded_value_behind() {
let mut host = Session::with_peer(PeerId(1));
let winner = HotOp {
op: set_document_attribute("k", 1),
timestamp: TimeStamp { counter: 10, peer: PeerId(2) },
sequence: crate::HotSequence(1),
};
host.apply_hot_op(winner.clone()).expect("apply winner");
host.retire(winner.timestamp).expect("retire winner");
// Arriving behind the winner, this op loses in the live view and its value is dropped.
let straggler = HotOp {
op: set_document_attribute("k", 2),
timestamp: TimeStamp { counter: 5, peer: PeerId(3) },
sequence: crate::HotSequence(1),
};
host.apply_hot_op(straggler.clone()).expect("apply straggler");
host.retire(straggler.timestamp).expect("retire straggler");
let value = |registry: &crate::Registry| registry.attributes.get("k").map(|attribute| attribute.value.clone());
assert_eq!(value(host.registry()), Some(serde_json::json!(1)), "the live view keeps the winner");
assert_eq!(value(host.retired_registry()), Some(serde_json::json!(1)), "and retiring the straggler must not overwrite it");
let replayed = host.snapshot_from_history().expect("refold");
assert_eq!(value(&replayed), Some(serde_json::json!(1)), "nor may history replay to the discarded value");
}
/// Every field of the registry is last-writer-wins on a timestamp, whether an entity exists included, so
/// a set of ops folds to one registry whatever order it lands in. Random sets of structural and field
/// ops, attribute deletions included, over a few ids so additions, removals and writes collide, folded
/// in random orders with an op naming an entity not yet seen retried after the rest.
#[test]
fn a_set_of_ops_folds_to_one_registry_in_any_order() {
use crate::Priority;
use crate::{Implementation, ResourceEntry, SourceKey};
use graphene_resource::ResourceId;
struct Lcg(u64);
impl Lcg {
fn below(&mut self, bound: u64) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 33) % bound
}
}
fn random_op(rng: &mut Lcg, at: TimeStamp) -> RegistryDelta {
let node_id = NodeId(1 + rng.below(4));
let network_id = NetworkId(1 + rng.below(3));
let resource_id = ResourceId::from(1 + rng.below(2));
let input = |rng: &mut Lcg| match rng.below(3) {
0 => crate::NodeInput::Node {
id: NodeId(1 + rng.below(4)),
index: 0,
},
_ => crate::NodeInput::Value {
value: serde_json::json!(rng.below(100)),
exposed: false,
},
};
match rng.below(18) {
0 => RegistryDelta::AddNetwork {
id: network_id,
network: Network::default(),
},
1 => RegistryDelta::RemoveNetwork {
id: network_id,
snapshot: Network::default(),
},
2 | 3 => RegistryDelta::AddNode {
id: node_id,
node: Node::new(network_id, Implementation::ProtoNode(ResourceId::from(7)), 1 + rng.below(2) as usize),
},
// A real snapshot is a fold of ops the remover saw, so two snapshots agreeing on a stamp agree on the
// value; a fabricated one has to be constant for that to hold.
4 => RegistryDelta::RemoveNode {
id: node_id,
snapshot: Node::new(NetworkId(1), Implementation::ProtoNode(ResourceId::from(7)), 2),
},
5 | 6 => RegistryDelta::ChangeNodeInput {
id: node_id,
index: rng.below(2) as u32,
new_input: input(rng),
},
7 => RegistryDelta::SetNodeInputs {
id: node_id,
inputs: (0..1 + rng.below(3))
.map(|_| InputSlot {
input: input(rng),
timestamp: TimeStamp::ORIGIN,
attributes: Default::default(),
attributes_timestamp: TimeStamp::ORIGIN,
})
.collect(),
},
8 => RegistryDelta::ChangeNodeAttribute {
id: node_id,
delta: crate::AttributeDelta {
key: ["name", "lock"][rng.below(2) as usize].into(),
value: (rng.below(4) > 0).then(|| serde_json::json!(rng.below(100))),
},
},
15 => RegistryDelta::ChangeNodeInputAttribute {
id: node_id,
index: rng.below(2) as u32,
delta: crate::AttributeDelta {
key: "label".into(),
value: (rng.below(4) > 0).then(|| serde_json::json!(rng.below(100))),
},
},
16 => RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: crate::AttributeDelta {
key: "name".into(),
value: (rng.below(4) > 0).then(|| serde_json::json!(rng.below(100))),
},
},
9 => RegistryDelta::SetNodeImplementation {
id: node_id,
implementation: match rng.below(2) {
0 => Implementation::Network(network_id),
_ => Implementation::ProtoNode(ResourceId::from(rng.below(3))),
},
},
10 => RegistryDelta::SetNetworkExport {
id: network_id,
index: rng.below(2) as u32,
export: match rng.below(2) {
0 => None,
_ => Some(input(rng)),
},
},
11 => RegistryDelta::AddResource {
id: resource_id,
entry: ResourceEntry::default(),
},
12 => RegistryDelta::RemoveResource {
id: resource_id,
snapshot: ResourceEntry::default(),
},
13 => RegistryDelta::SetResourceHash {
id: resource_id,
hash: Some(graphene_resource::ResourceHash::from([rng.below(2) as u8; 32])),
},
_ => RegistryDelta::AddSource {
id: resource_id,
key: SourceKey {
priority: Priority::new(rng.below(2) as f64).expect("finite"),
peer: at.peer,
},
source: serde_json::json!(rng.below(100)),
},
}
}
/// Folds the ops in the order given, retrying the ones that name an entity not yet seen until no
/// retry lands, and returns the working registry.
fn fold(ops: &[(RegistryDelta, TimeStamp)]) -> crate::Registry {
let mut document = fresh_document(PeerId(9));
let mut pending: Vec<&(RegistryDelta, TimeStamp)> = ops.iter().collect();
loop {
let before = pending.len();
pending.retain(|(op, at)| document.apply_op_idempotent(op.clone(), *at).is_err());
if pending.is_empty() || pending.len() == before {
return document.working_registry;
}
}
}
for seed in 0..300u64 {
let mut rng = Lcg(seed);
let ops: Vec<(RegistryDelta, TimeStamp)> = (0..8 + rng.below(24))
.map(|i| {
let at = TimeStamp {
counter: 1 + i,
peer: PeerId(1 + rng.below(3)),
};
(random_op(&mut rng, at), at)
})
.collect();
let reference = fold(&ops);
for _ in 0..6 {
let mut shuffled = ops.clone();
for i in (1..shuffled.len()).rev() {
shuffled.swap(i, rng.below(i as u64 + 1) as usize);
}
let folded = fold(&shuffled);
assert_eq!(
folded,
reference,
"seed {seed}: the ops {:?} folded differently in the order {:?}",
ops.iter().map(|(_, at)| at.counter).collect::<Vec<_>>(),
shuffled.iter().map(|(_, at)| at.counter).collect::<Vec<_>>()
);
}
}
}
/// A removal's snapshot is a copy of the node, stamped exactly as the addition stamped it. Folding it in
/// must keep what the addition wrote: an entry stamped at a map's floor was written by the same op that
/// set the floor, not before it. Caught in the editor as a revived node missing `reflection_metadata`.
#[test]
fn a_removal_snapshot_keeps_the_attributes_the_addition_wrote() {
use crate::{AttributesRead, AttributesWrite};
let mut document = fresh_document(PeerId(1));
let node_id = NodeId(4);
let mut node = Node::new(ROOT_NETWORK, crate::Implementation::ProtoNode(graphene_resource::ResourceId::from(7)), 1);
node.attributes.set("ui::name", serde_json::json!("Layer"), TimeStamp::ORIGIN);
node.inputs[0].attributes.set("reflection_metadata", serde_json::json!("meta"), TimeStamp::ORIGIN);
commit_op(
&mut document,
RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
);
commit_op(&mut document, RegistryDelta::AddNode { id: node_id, node });
let added = document.working_registry.node_instances[&node_id].clone();
// A removal and a concurrent, newer write to the node: the write revives it from the tombstone.
let removed_at = document.clock.tick();
document
.apply_op_idempotent(RegistryDelta::RemoveNode { id: node_id, snapshot: added.clone() }, removed_at)
.expect("removal");
let written_at = document.clock.tick();
document
.apply_op_idempotent(
RegistryDelta::ChangeNodeAttribute {
id: node_id,
delta: crate::AttributeDelta {
key: "ui::lock".into(),
value: Some(serde_json::json!(true)),
},
},
written_at,
)
.expect("write");
let revived = &document.working_registry.node_instances[&node_id];
assert_eq!(
revived.attributes.get_typed::<String>("ui::name").as_deref(),
Some("Layer"),
"the node attribute the addition wrote survives"
);
assert_eq!(
revived.inputs()[0].attributes.get_typed::<String>("reflection_metadata").as_deref(),
Some("meta"),
"the slot attribute the addition wrote survives"
);
// The same snapshot folding into the live node, from a removal too old to land, changes nothing.
let mut untouched = document.clone();
untouched
.apply_op_idempotent(RegistryDelta::RemoveNode { id: node_id, snapshot: added }, removed_at)
.expect("a replayed removal");
assert_eq!(untouched.working_registry, document.working_registry);
}
@@ -1,156 +0,0 @@
use std::collections::BTreeSet;
use core_types::uuid::NodeId as RuntimeNodeId;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use crate::{NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, Registry};
fn proto(identifier: &'static str, inputs: Vec<NodeInput>) -> DocumentNode {
DocumentNode {
inputs,
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
..Default::default()
}
}
/// A root network holding a proto node and a group, with another proto node and a nested group inside
/// the group, so projection is exercised two networks deep.
fn nested_network() -> NodeNetwork {
let inner = NodeNetwork {
exports: vec![NodeInput::node(RuntimeNodeId(30), 0)],
nodes: [(RuntimeNodeId(30), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::import(concrete!(u32), 0)]))]
.into_iter()
.collect(),
..Default::default()
};
let group = NodeNetwork {
exports: vec![NodeInput::node(RuntimeNodeId(20), 0)],
nodes: [
(RuntimeNodeId(20), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::node(RuntimeNodeId(21), 0)])),
(
RuntimeNodeId(21),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Integer(3), false)],
implementation: DocumentNodeImplementation::Network(inner),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
};
NodeNetwork {
exports: vec![NodeInput::node(RuntimeNodeId(1), 0)],
nodes: [
(RuntimeNodeId(1), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::node(RuntimeNodeId(2), 0)])),
(
RuntimeNodeId(2),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Integer(7), true)],
implementation: DocumentNodeImplementation::Network(group),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
}
}
fn find_node<'a>(network: &'a NodeNetwork, path: &[RuntimeNodeId], id: RuntimeNodeId) -> &'a DocumentNode {
let nested = network.nested_network(path).expect("the path should resolve");
nested.nodes.get(&id).expect("the node should exist")
}
/// A node projected on its own must be what the whole-document conversion holds for it, metadata
/// included, since a mirror patched from projections has to match a mirror rebuilt whole.
#[test]
fn projecting_a_node_matches_the_whole_conversion() {
let resources = graphene_resource::ResourceRegistry::new();
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
let registry = &conversion.registry;
let (whole, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
let projection = registry.runtime_projection(&conversion.declarations);
for &id in registry.node_instances.keys() {
let projected = projection.node(id).expect("every stored node projects");
let (path, local_id) = projection.node_address(id).expect("every stored node has an address");
assert_eq!((path.as_slice(), local_id), (projected.network_path.as_slice(), projected.local_id));
assert_eq!(
&projected.node,
find_node(&whole, &path, local_id),
"node {id} projected differently than the whole conversion converts it"
);
let own_entry = node_entries.iter().find(|entry| entry.storage_id == id).expect("the whole conversion emits an entry per node");
assert_eq!(projected.node_entries.first(), Some(own_entry), "the node's own entry comes first");
// The nested entries are exactly the whole conversion's entries under this node.
let nested_prefix: Vec<RuntimeNodeId> = [path.as_slice(), &[local_id]].concat();
let expected_nested: BTreeSet<_> = node_entries
.iter()
.filter(|entry| entry.network_path.starts_with(&nested_prefix))
.map(|entry| entry.storage_id)
.collect();
let projected_nested: BTreeSet<_> = projected.node_entries.iter().skip(1).map(|entry| entry.storage_id).collect();
assert_eq!(projected_nested, expected_nested, "nested node entries under {id}");
let expected_networks: BTreeSet<_> = network_entries
.iter()
.filter(|entry| entry.network_path.starts_with(&nested_prefix))
.map(|entry| entry.network_id)
.collect();
let projected_networks: BTreeSet<_> = projected.network_entries.iter().map(|entry| entry.network_id).collect();
assert_eq!(projected_networks, expected_networks, "nested network entries under {id}");
}
}
#[test]
fn a_network_entry_projects_its_dense_exports_and_path() {
let resources = graphene_resource::ResourceRegistry::new();
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
let registry = &conversion.registry;
let (whole, _, _) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
let projection = registry.runtime_projection(&conversion.declarations);
let root = projection.network_entry(ROOT_NETWORK).expect("root");
assert!(root.network_path.is_empty());
assert_eq!(root.exports, whole.exports);
for &network_id in registry.networks.keys() {
let entry = projection.network_entry(network_id).expect("every stored network projects");
let nested = whole.nested_network(&entry.network_path).expect("the projected path exists in the whole conversion");
assert_eq!(entry.exports, nested.exports, "exports of the network at {:?}", entry.network_path);
assert_eq!(entry.scope_injections, nested.scope_injections);
if let Some(owner) = projection.owner(network_id) {
let (owner_path, owner_local) = projection.node_address(owner).expect("owner address");
assert_eq!(
entry.network_path,
[owner_path.as_slice(), &[owner_local]].concat(),
"a network's path ends in the node implementing it"
);
}
}
}
/// A network no node implements is not in the runtime, so nothing inside it has an address.
#[test]
fn an_unreachable_network_has_no_address() {
let mut registry = Registry::default();
registry.networks.insert(crate::NetworkId(5), crate::Network::default());
let mut node = Node::dummy();
node.network = crate::NetworkId(5);
registry.node_instances.insert(NodeId(9), node);
let declarations = crate::Declarations::new();
let projection = registry.runtime_projection(&declarations);
assert_eq!(projection.network_path(crate::NetworkId(5)), None);
assert_eq!(projection.node_address(NodeId(9)), None);
assert!(matches!(projection.node(NodeId(9)), Err(crate::to_runtime::ConversionError::NetworkNotFound(_))));
}
+18 -26
View File
@@ -14,16 +14,20 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
/// Test networks with Import inputs will fail compilation (which is expected).
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
let compiler = Compiler {};
compiler.compile_single(network.clone()).map_err(|e| format!("Compilation failed: {:?}", e))?;
compiler
.compile_single(network.clone(), &graph_craft::proto::Registry::new())
.map_err(|e| format!("Compilation failed: {:?}", e))?;
Ok(())
}
/// Convert a runtime network to a storage `Registry`, returning the declarations alongside it.
/// Proto-node declaration content is no longer stored in the registry (it lives in a byte store);
/// these tests have no byte store, so they keep the extracted `Declarations` in hand for the back-conversion.
/// these tests have no byte store, so they keep the extracted bytes in hand and rebuild a
/// `Declarations` map for the back-conversion.
fn to_registry(network: &NodeNetwork) -> (Registry, crate::Declarations) {
let conversion = Registry::convert_from_runtime(network, &crate::NoMetadata, &Default::default(), PeerId(0)).expect("Failed to convert NodeNetwork to Registry");
(conversion.registry, conversion.declarations)
let declarations = conversion.declarations().expect("rebuild declarations");
(conversion.registry, declarations)
}
/// A one-node network whose single node references `id` via a `TaggedValue::Resource` input, so
@@ -244,11 +248,6 @@ fn test_nested_network_flattening() {
#[test]
fn test_metadata_preservation() {
// Create a network with nodes that have non-default metadata
let context_features = ContextDependencies {
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
..Default::default()
};
let network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
@@ -258,7 +257,6 @@ fn test_metadata_preservation() {
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
call_argument: concrete!(String),
context_features,
visible: false, // Non-default value
skip_deduplication: true, // Non-default value
..Default::default()
@@ -292,8 +290,12 @@ fn test_metadata_preservation() {
let conv_node_1 = converted.nodes.get(&NodeId(1)).unwrap();
assert_eq!(orig_node_1.call_argument, conv_node_1.call_argument, "call_argument for node 1 should be preserved");
// Verify context_features is preserved
assert_eq!(orig_node_0.context_features, conv_node_0.context_features, "context_features should be preserved");
// Verify context_features is not stored
assert_eq!(
conv_node_0.context_features,
ContextDependencies::default(),
"context_features should resolve at compile, not round-trip"
);
// Verify visible is preserved
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved");
@@ -475,7 +477,7 @@ fn test_ui_metadata_round_trip() {
);
let conversion = Registry::convert_from_runtime(&network, &metadata, &Default::default(), PeerId(0)).expect("Failed to convert to Registry with metadata");
let declarations = conversion.declarations;
let declarations = conversion.declarations().expect("rebuild declarations");
let registry = conversion.registry;
let (converted, entries) = registry.to_runtime_with_metadata(&declarations).expect("Failed to convert Registry back with metadata");
@@ -609,7 +611,7 @@ fn unreferenced_runtime_resource_is_not_snapshotted() {
assert!(!registry.resources.contains_key(&orphan), "the unreferenced (orphan) resource must not be snapshotted");
}
/// A node-input `TaggedValue::Number` must survive the storage round-trip bit-exact. Inputs are stored as a
/// A node-input `TaggedValue::F64` must survive the storage round-trip bit-exact. Inputs are stored as a
/// self-describing `serde_json::Value` (encoded with the registry's MessagePack codec), so this guards
/// against any precision loss in the f64 -> serde_json::Number -> f64 path for a value with a full
/// 17-significant-digit mantissa.
@@ -623,7 +625,7 @@ fn node_input_f64_round_trips_bit_exact() {
nodes: [(
NodeId(0),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Number(precise), false)],
inputs: vec![NodeInput::value(TaggedValue::F64(precise), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
..Default::default()
},
@@ -640,8 +642,8 @@ fn node_input_f64_round_trips_bit_exact() {
let NodeInput::Value { tagged_value, .. } = input else {
panic!("expected a value input, got {input:?}")
};
let TaggedValue::Number(actual) = &**tagged_value else {
panic!("expected Number, got {:?}", tagged_value)
let TaggedValue::F64(actual) = &**tagged_value else {
panic!("expected F64, got {:?}", tagged_value)
};
assert_eq!(actual.to_bits(), precise.to_bits(), "f64 node input drifted: {actual} != {precise}");
@@ -758,28 +760,18 @@ fn cyclic_network_reference_is_rejected() {
registry.node_instances.insert(
crate::NodeId(0),
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(child_network_id),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
attributes_timestamp: Default::default(),
network: crate::ROOT_NETWORK,
},
);
registry.node_instances.insert(
crate::NodeId(1),
Node {
presence: Default::default(),
added: Default::default(),
inputs_timestamp: Default::default(),
implementation: Implementation::Network(crate::ROOT_NETWORK),
implementation_timestamp: Default::default(),
inputs: Vec::new(),
attributes: crate::Attributes::default(),
attributes_timestamp: Default::default(),
network: child_network_id,
},
);
+37 -191
View File
@@ -38,8 +38,7 @@ pub enum ConversionError {
pub type Declarations = std::collections::HashMap<ResourceId, ProtoNode>;
impl Registry {
/// Returns the network plus one metadata entry per node, since every node carries an identity to
/// restore even when it has no `ui::*` attribute.
/// Returns the network plus per-node metadata entries (one per node carrying any `ui::*` attribute).
pub fn to_runtime_with_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations)?;
Ok((network, node_entries))
@@ -51,10 +50,19 @@ impl Registry {
let mut node_metadata = Some(Vec::new());
let mut network_metadata = Some(Vec::new());
// Nodes are grouped by their owning network in one pass, so each `convert_network` call (one per
// Group nodes by their owning network in one pass, so each `convert_network` call (one per
// network, including nested ones) takes its node list by lookup instead of rescanning the whole
// flat `node_instances` map, which would be quadratic on graphs with many networks.
let context = ConversionContext::new(self, declarations);
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &self.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
let context = ConversionContext {
registry: self,
declarations,
nodes_by_network,
};
// Reject cycles up front so the recursive conversion below can assume the network reference
// graph is acyclic and never blow the stack on a self-referential `Implementation::Network`.
@@ -73,7 +81,7 @@ impl Registry {
let mut registry = graphene_resource::ResourceRegistry::new();
for (id, entry) in &self.resources {
for (_, source) in entry.live_sources() {
for (_, source) in &entry.sources {
let decoded: graphene_resource::DataSource = serde_json::from_value(source.source.clone()).map_err(|error| ConversionError::DeserializationError(error.to_string()))?;
registry.push_source_back(id, decoded);
}
@@ -95,155 +103,6 @@ struct ConversionContext<'a> {
nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &'a Node)>>,
}
impl<'a> ConversionContext<'a> {
fn new(registry: &'a Registry, declarations: &'a Declarations) -> Self {
let mut nodes_by_network: FxHashMap<NetworkId, Vec<(NodeId, &Node)>> = FxHashMap::default();
for (&global_id, node) in &registry.node_instances {
nodes_by_network.entry(node.network).or_default().push((global_id, node));
}
Self {
registry,
declarations,
nodes_by_network,
}
}
}
/// The id the node had in the runtime it was converted from, which storage keeps as an attribute so a
/// conversion back lands the node under the id the editor's metadata is keyed by.
fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
RuntimeNodeId(node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|value| value.value.as_u64()).unwrap_or(global_id.0))
}
/// One node in runtime form together with the metadata for it and everything nested under it, as
/// [`RuntimeProjection::node`] produces it. Entry paths are absolute, the way a whole-document
/// conversion writes them.
pub struct ProjectedNode {
/// The runtime path of the network the node sits in.
pub network_path: Vec<RuntimeNodeId>,
pub local_id: RuntimeNodeId,
pub node: DocumentNode,
/// The node's own entry first, then one per nested node.
pub node_entries: Vec<NodeMetadataEntry>,
/// One per network the node's implementation nests, outermost first.
pub network_entries: Vec<NetworkMetadataEntry>,
}
/// A network's own runtime form without its nodes, as [`RuntimeProjection::network_entry`] produces it.
pub struct ProjectedNetwork {
pub network_path: Vec<RuntimeNodeId>,
/// Dense, the way the runtime holds them: a storage slot holding nothing is skipped.
pub exports: Vec<GraphCraftNodeInput>,
pub scope_injections: FxHashMap<String, (RuntimeNodeId, Type)>,
pub metadata: NetworkMetadataEntry,
}
/// Converts single entities of the registry to their runtime form, for a caller keeping a runtime
/// mirror in step with the registry rather than rebuilding it. Owner relationships are gathered once at
/// construction so each address lookup is a probe.
pub struct RuntimeProjection<'a> {
context: ConversionContext<'a>,
/// The node whose implementation each nested network is.
owners: FxHashMap<NetworkId, NodeId>,
}
impl Registry {
pub fn runtime_projection<'a>(&'a self, declarations: &'a Declarations) -> RuntimeProjection<'a> {
let owners = self
.node_instances
.iter()
.filter_map(|(&id, node)| match node.implementation {
Implementation::Network(network) => Some((network, id)),
Implementation::ProtoNode(_) => None,
})
.collect();
RuntimeProjection {
context: ConversionContext::new(self, declarations),
owners,
}
}
}
impl RuntimeProjection<'_> {
/// The node implementing `network`, or `None` for the root and for a network no node implements.
pub fn owner(&self, network: NetworkId) -> Option<NodeId> {
self.owners.get(&network).copied()
}
/// The runtime path of `network`: the nodes implementing it and its ancestors, outermost first.
/// `None` for a network the root does not reach, which the runtime does not hold.
pub fn network_path(&self, network: NetworkId) -> Option<Vec<RuntimeNodeId>> {
let mut chain = Vec::new();
let mut current = network;
while current != ROOT_NETWORK {
let owner = self.owner(current)?;
let node = self.context.registry.node_instances.get(&owner)?;
// Owners can form a cycle through concurrent implementation swaps, which the runtime rejects.
if chain.contains(&owner) {
return None;
}
chain.push(owner);
current = node.network;
}
Some(chain.into_iter().rev().map(|owner| runtime_node_id(owner, &self.context.registry.node_instances[&owner])).collect())
}
/// Where the node sits in the runtime: the path of its network, and its id within that network.
pub fn node_address(&self, id: NodeId) -> Option<(Vec<RuntimeNodeId>, RuntimeNodeId)> {
let node = self.context.registry.node_instances.get(&id)?;
Some((self.network_path(node.network)?, runtime_node_id(id, node)))
}
/// The node and everything nested under it, converted the way a whole-document conversion converts
/// them, so a mirror patched with the result matches a rebuild.
pub fn node(&self, id: NodeId) -> Result<ProjectedNode, ConversionError> {
let node = self.context.registry.node_instances.get(&id).ok_or(ConversionError::NodeNotFound(id))?;
let network_path = self.network_path(node.network).ok_or(ConversionError::NetworkNotFound(node.network))?;
let local_id = runtime_node_id(id, node);
if let Implementation::Network(nested) = node.implementation {
detect_network_cycle(&self.context, nested)?;
}
let mut node_entries = Some(vec![extract_ui_metadata(node, id, &network_path, local_id)]);
let mut network_entries = Some(Vec::new());
let document_node = convert_node(&self.context, node, &network_path, local_id, &mut node_entries, &mut network_entries)?;
Ok(ProjectedNode {
network_path,
local_id,
node: document_node,
node_entries: node_entries.expect("seeded above"),
network_entries: network_entries.expect("seeded above"),
})
}
/// The network's exports, scope injections and metadata, without its nodes.
pub fn network_entry(&self, id: NetworkId) -> Result<ProjectedNetwork, ConversionError> {
let registry = self.context.registry;
// A network removed concurrently with a write into it renders as it was, so the nodes still in it
// keep their place.
let network = registry.network_or_removed(id).ok_or(ConversionError::NetworkNotFound(id))?;
let network_path = self.network_path(id).ok_or(ConversionError::NetworkNotFound(id))?;
let empty_attrs = crate::Attributes::new();
let exports = network
.exports
.iter()
.filter_map(|slot| slot.target.as_ref())
.map(|input| convert_input(registry, id, input, &empty_attrs))
.collect::<Result<Vec<_>, _>>()?;
Ok(ProjectedNetwork {
metadata: extract_network_metadata(registry, &network.attributes, &network_path, id),
scope_injections: read_scope_injections(registry, id, &network.attributes)?,
exports,
network_path,
})
}
}
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
///
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
@@ -306,19 +165,21 @@ fn convert_network(
node_collector: &mut Option<Vec<NodeMetadataEntry>>,
network_collector: &mut Option<Vec<NetworkMetadataEntry>>,
) -> Result<NodeNetwork, ConversionError> {
let network = context.registry.network_or_removed(network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
let network = context.registry.networks.get(&network_id).ok_or(ConversionError::NetworkNotFound(network_id))?;
if let Some(collector) = network_collector.as_mut() {
collector.push(extract_network_metadata(context.registry, &network.attributes, metadata_path, network_id));
collector.push(extract_network_metadata(&network.attributes, metadata_path, network_id));
}
let mut nodes: FxHashMap<RuntimeNodeId, DocumentNode> = FxHashMap::default();
for &(global_id, node) in context.nodes_by_network.get(&network_id).map(Vec::as_slice).unwrap_or_default() {
let runtime_id = runtime_node_id(global_id, node);
let local_id = runtime_id.0;
let local_id = node.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(global_id.0);
let runtime_id = RuntimeNodeId(local_id);
if let Some(collector) = node_collector.as_mut() {
collector.push(extract_ui_metadata(node, global_id, metadata_path, runtime_id));
if let Some(collector) = node_collector.as_mut()
&& let Some(entry) = extract_ui_metadata(node, metadata_path, runtime_id)
{
collector.push(entry);
}
let doc_node = convert_node(context, node, metadata_path, runtime_id, node_collector, network_collector)?;
@@ -372,15 +233,16 @@ fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes:
});
};
Ok((key, (runtime_node_id(storage_id, referenced), ty)))
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(storage_id.0);
Ok((key, (RuntimeNodeId(local_id), ty)))
})
.collect()
}
/// Emitted for every node, since `storage_id` is worth restoring even where no `ui::*` attribute is.
/// `input_metadata` is always sized to match `node.inputs.len()` for a strict slot-by-slot rebuild;
/// empty slots use `InputMetadataEntry::default()`.
fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeMetadataEntry {
/// Returns `None` when the node has no `ui::*` attributes at all so callers don't end up with
/// empty entries for unconverted-from-runtime nodes. `input_metadata` is always sized to match
/// `node.inputs.len()` for a strict slot-by-slot rebuild; empty slots use `InputMetadataEntry::default()`.
fn extract_ui_metadata(node: &crate::Node, network_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> Option<NodeMetadataEntry> {
let position: Option<Position> = node.attributes.get_typed(node::ui::POSITION);
let is_layer = node.attributes.get_or(node::ui::IS_LAYER, false);
let display_name: Option<String> = node.attributes.get_typed(node::ui::DISPLAY_NAME);
@@ -390,10 +252,9 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
let input_metadata: Vec<InputMetadataEntry> = node.inputs.iter().map(|slot| &slot.attributes).map(extract_input_metadata).collect();
NodeMetadataEntry {
let entry = NodeMetadataEntry {
network_path: network_path.to_vec(),
local_id,
storage_id,
position,
is_layer,
display_name,
@@ -401,36 +262,22 @@ fn extract_ui_metadata(node: &crate::Node, storage_id: NodeId, network_path: &[R
pinned,
input_metadata,
output_names,
}
};
(!entry.is_empty()).then_some(entry)
}
/// Node references stored here are storage IDs, resolved back to runtime-local IDs the way
/// `read_scope_injections` does. A reference to a node that is no longer in this network is dropped
/// rather than failing the conversion: a pinned node can have been deleted.
fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
let to_runtime_id = |storage_id: NodeId| {
let node = registry.node_instances.get(&storage_id).filter(|node| node.network == network_id)?;
Some(runtime_node_id(storage_id, node))
};
let pinned_order = attributes
.get_typed::<Vec<NodeId>>(network::PINNED_ORDER)
.unwrap_or_default()
.into_iter()
.filter_map(to_runtime_id)
.collect();
fn extract_network_metadata(attributes: &crate::Attributes, network_path: &[RuntimeNodeId], network_id: NetworkId) -> NetworkMetadataEntry {
NetworkMetadataEntry {
network_path: network_path.to_vec(),
network_id,
reference: attributes.get_typed(node::ui::REFERENCE),
pinned_order,
}
}
/// Reassembles `input_data` by scanning every attribute under `ui::input_data::` and stripping the prefix.
fn extract_input_metadata(attributes: &crate::Attributes) -> InputMetadataEntry {
let input_data: HashMap<String, serde_json::Value> = crate::attributes::live(attributes)
let input_data: HashMap<String, serde_json::Value> = attributes
.iter()
.filter_map(|(key, value)| key.strip_prefix(node::input::ui::DATA_PREFIX).map(|sub_key| (sub_key.to_owned(), value.value.clone())))
.collect();
@@ -463,8 +310,8 @@ fn convert_node(
implementation: convert_implementation(context, &node.implementation, metadata_path, runtime_node_id, node_collector, network_collector)?,
visible: node.attributes.get_or(node::VISIBLE, true),
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
context_features: node.attributes.get_or_default(node::CONTEXT_FEATURES),
// Regenerated during compilation; not stored.
context_features: Default::default(),
original_location: Default::default(),
})
}
@@ -472,9 +319,7 @@ fn convert_node(
fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput, input_attributes: &crate::Attributes) -> Result<GraphCraftNodeInput, ConversionError> {
Ok(match input {
NodeInput::Node { id: node_id, index: output_index } => {
// A reference to a node removed concurrently keeps the id it had, the way the editor holds a
// dangling input; only a node never seen has no id to map to.
let referenced = registry.node_or_removed(*node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
let referenced = registry.node_instances.get(node_id).ok_or(ConversionError::NodeNotFound(*node_id))?;
// Runtime references are local to one network. A cross-network reference would remap to a
// local ID that doesn't exist in the current runtime network, so reject it.
@@ -485,8 +330,9 @@ fn convert_input(registry: &Registry, network_id: NetworkId, input: &NodeInput,
});
}
let local_id = referenced.attributes.get(node::ORIGINAL_NODE_ID).and_then(|v| v.value.as_u64()).unwrap_or(node_id.0);
GraphCraftNodeInput::Node {
node_id: runtime_node_id(*node_id, referenced),
node_id: RuntimeNodeId(local_id),
output_index: *output_index as usize,
}
}
-146
View File
@@ -1,146 +0,0 @@
//! Which entities a run of ops named, for a runtime mirror of the registry to bring back into line
//! without being rebuilt from the whole registry.
//!
//! The set is over-approximate on purpose: an op is recorded whether or not it changed anything, so a
//! late-writer-wins loser, an idempotent replay and a failed apply all land here. What the op did to the
//! registry is settled by comparing the entity's stored and mirrored forms afterwards, which is cheaper
//! than having every apply arm report its outcome and stays correct when an op resurrects an entity it
//! only references.
use std::collections::BTreeSet;
use crate::{NetworkId, NodeId, NodeInput, RegistryDelta};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Touched {
pub nodes: BTreeSet<NodeId>,
pub networks: BTreeSet<NetworkId>,
/// Some resource entry changed. Resources are mirrored as one registry rather than per entity.
pub resources: bool,
}
impl Touched {
/// Records every entity `op` names: its target, and any node it references, since applying it can
/// resurrect a referenced node that was concurrently removed.
pub fn record(&mut self, op: &RegistryDelta) {
match op {
RegistryDelta::AddNode { id, node } => {
self.nodes.insert(*id);
self.reference_inputs(node.inputs().iter().map(|slot| &slot.input));
}
RegistryDelta::RemoveNode { id, .. }
| RegistryDelta::SetNodeImplementation { id, .. }
| RegistryDelta::ChangeNodeAttribute { id, .. }
| RegistryDelta::ChangeNodeInputAttribute { id, .. } => {
self.nodes.insert(*id);
}
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
self.nodes.insert(*id);
self.reference_inputs([new_input]);
}
RegistryDelta::SetNodeInputs { id, inputs } => {
self.nodes.insert(*id);
self.reference_inputs(inputs.iter().map(|slot| &slot.input));
}
RegistryDelta::SetNetworkExport { id, export, .. } => {
self.networks.insert(*id);
self.reference_inputs(export.iter());
}
RegistryDelta::ChangeNetworkAttribute { id, .. } | RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => {
self.networks.insert(*id);
}
RegistryDelta::AddResource { .. } | RegistryDelta::SetResourceHash { .. } | RegistryDelta::RemoveResource { .. } | RegistryDelta::AddSource { .. } | RegistryDelta::RemoveSource { .. } => {
self.resources = true;
}
RegistryDelta::RegisterPeer { .. } | RegistryDelta::ChangeDocumentAttribute { .. } | RegistryDelta::Merge { .. } | RegistryDelta::EndTransaction | RegistryDelta::Other(_) => {}
}
}
pub fn extend(&mut self, other: Touched) {
self.nodes.extend(other.nodes);
self.networks.extend(other.networks);
self.resources |= other.resources;
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty() && self.networks.is_empty() && !self.resources
}
fn reference_inputs<'a>(&mut self, inputs: impl IntoIterator<Item = &'a NodeInput>) {
for input in inputs {
if let NodeInput::Node { id, .. } = input {
self.nodes.insert(*id);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{AttributeDelta, Network, Node};
#[test]
fn an_input_write_touches_the_node_it_references_as_well_as_its_target() {
let mut touched = Touched::default();
touched.record(&RegistryDelta::ChangeNodeInput {
id: NodeId(1),
index: 0,
new_input: NodeInput::Node { id: NodeId(2), index: 0 },
});
assert_eq!(touched.nodes, BTreeSet::from([NodeId(1), NodeId(2)]));
assert!(touched.networks.is_empty());
assert!(!touched.resources);
}
#[test]
fn an_export_touches_the_network_and_the_node_it_targets() {
let mut touched = Touched::default();
touched.record(&RegistryDelta::SetNetworkExport {
id: NetworkId(3),
index: 0,
export: Some(NodeInput::Node { id: NodeId(4), index: 0 }),
});
assert_eq!(touched.networks, BTreeSet::from([NetworkId(3)]));
assert_eq!(touched.nodes, BTreeSet::from([NodeId(4)]));
}
#[test]
fn ops_outside_the_graph_touch_nothing_or_only_the_resource_flag() {
let mut touched = Touched::default();
touched.record(&RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta { key: "key".into(), value: None },
});
touched.record(&RegistryDelta::Merge { extra_parents: Vec::new() });
assert!(touched.is_empty());
touched.record(&RegistryDelta::SetResourceHash {
id: crate::ResourceId::new(),
hash: None,
});
assert!(touched.resources);
assert!(touched.nodes.is_empty());
}
#[test]
fn a_node_add_touches_the_node_and_what_its_inputs_reference() {
let mut node = Node::dummy();
node.inputs.push(crate::InputSlot {
input: NodeInput::Node { id: NodeId(9), index: 0 },
timestamp: crate::TimeStamp::ORIGIN,
attributes: Default::default(),
attributes_timestamp: crate::TimeStamp::ORIGIN,
});
let mut touched = Touched::default();
touched.record(&RegistryDelta::AddNode { id: NodeId(8), node });
touched.record(&RegistryDelta::AddNetwork {
id: NetworkId(5),
network: Network::default(),
});
assert_eq!(touched.nodes, BTreeSet::from([NodeId(8), NodeId(9)]));
assert_eq!(touched.networks, BTreeSet::from([NetworkId(5)]));
}
}
-21
View File
@@ -1,21 +0,0 @@
[package]
name = "document-live"
description = "A memory-backed document following or hosting a collaborative session, for viewers and embedders"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
publish.workspace = true
[dependencies]
document-container = { workspace = true }
document-format = { workspace = true }
document-graph-storage = { workspace = true }
peer-transport = { workspace = true }
graph-craft = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
[lints]
workspace = true
-124
View File
@@ -1,124 +0,0 @@
//! A document that lives in a collaborative session rather than on disk. Hosts a session or follows
//! one, and hands out the current runtime `NodeNetwork` on demand. Owns no executor, window, or
//! async runtime: the caller spawns the transport driver and decides how to render.
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout, ResourceProxy};
use document_graph_storage::{PeerId, UserId};
use graph_craft::application_io::resource::ResourceHash;
use graph_craft::document::NodeNetwork;
use peer_transport::{Room, SyncTarget};
pub use document_format::Error as FormatError;
pub use document_graph_storage::to_runtime::ConversionError;
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, Role, SessionToken};
#[derive(Debug, thiserror::Error)]
pub enum LiveError {
#[error(transparent)]
Format(#[from] FormatError),
#[error(transparent)]
Conversion(#[from] ConversionError),
}
pub struct LiveDocument {
gdd: GddV1,
token: SessionToken,
}
impl LiveDocument {
/// Create an empty document and host a session under `token`. `spawn` must drive the returned
/// future for as long as the session lives.
pub async fn host(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
let gdd = Self::empty_document(peer).await?;
Ok(Self::host_document(gdd, signaling_server, token, user, spawn))
}
/// Host a session on an already opened document.
pub fn host_document(mut gdd: GddV1, signaling_server: &str, token: SessionToken, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Self {
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
spawn(driver);
gdd.share(room, user);
Self { gdd, token }
}
/// Join the session under `token`; the document fills in once the host's sync arrives.
pub async fn join(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
let mut gdd = Self::empty_document(peer).await?;
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
spawn(driver);
gdd.join(room, user);
Ok(Self { gdd, token })
}
async fn empty_document(peer: PeerId) -> Result<GddV1, FormatError> {
let version = env!("CARGO_PKG_VERSION").to_string();
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, peer, UserId(peer.0), peer.0, version.clone(), version).await
}
pub fn token(&self) -> SessionToken {
self.token
}
pub fn role(&self) -> Option<Role> {
self.gdd.role()
}
pub fn is_synced(&self) -> bool {
self.gdd.is_synced()
}
/// Synced and holding every resource the document references, so `network` can be built and run.
pub fn is_ready(&self) -> bool {
self.is_synced() && SyncTarget::missing_resources(&self.gdd).is_empty()
}
/// Resources the document references whose bytes no peer has sent yet; `is_ready` waits on them.
pub fn missing_resources(&self) -> Vec<ResourceHash> {
let mut missing: Vec<ResourceHash> = SyncTarget::missing_resources(&self.gdd).into_iter().collect();
missing.sort_unstable();
missing
}
/// Apply whatever peers sent since the last call and answer their resource requests. Call it regularly.
pub async fn poll(&mut self) -> Vec<Event> {
let events = self.gdd.poll_peers();
for event in &events {
let Event::ResourceRequested { from, hash } = event else { continue };
match self.gdd.read_resource(hash).await {
Ok(bytes) => {
if let Err(error) = self.gdd.send_resource(*from, *hash, bytes.as_slice().to_vec()) {
log::warn!("Failed to send resource {hash}: {error}");
}
}
Err(error) => log::warn!("Peer asked for resource {hash} which is not in this document: {error}"),
}
}
events
}
pub fn document(&self) -> &GddV1 {
&self.gdd
}
pub fn document_mut(&mut self) -> &mut GddV1 {
&mut self.gdd
}
/// The current runtime graph, rebuilt from the registry. Async because proto-node declarations are resources.
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
let declarations = self.gdd.declarations(&self.gdd).await;
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations)?;
Ok(network)
}
/// Byte store for resources received from peers, for an executor to load from.
pub fn resource_proxy(&self) -> ResourceProxy<GddV1Layout> {
self.gdd.resource_proxy()
}
pub fn leave(&mut self) {
self.gdd.leave();
}
}
-34
View File
@@ -1,34 +0,0 @@
[package]
name = "peer-transport"
description = "Peer-to-peer sync of hot ops and retired history between document-graph-storage sessions over WebRTC"
rust-version.workspace = true
edition.workspace = true
authors.workspace = true
homepage.workspace = true
repository.workspace = true
license.workspace = true
version.workspace = true
publish.workspace = true
[dependencies]
core-types = { workspace = true }
document-graph-storage = { workspace = true }
matchbox_socket = "0.14.0"
futures = { workspace = true }
log = { workspace = true }
serde = { workspace = true }
serde_bytes = { workspace = true }
rmp-serde = { workspace = true }
base64 = { workspace = true }
thiserror = { workspace = true }
uuid = "1"
[target.'cfg(not(target_family = "wasm"))'.dependencies]
rustls = { version = "0.23", default-features = false, features = ["ring"] }
[dev-dependencies]
serde_json = { workspace = true }
env_logger = { workspace = true }
[lints]
workspace = true
-19
View File
@@ -1,19 +0,0 @@
pub mod mock;
mod packet;
mod replica;
mod room;
mod target;
mod token;
mod transport;
pub use packet::{CursorPosition, CursorSpace, PacketError, Role, SyncPacket, SyncPayload};
pub use replica::{Event, RemotePeer, Replica, ReplicaError};
pub use room::{Incoming, Room};
pub use target::{SyncTarget, TargetError};
pub use token::{InvalidSessionToken, SessionToken};
pub use transport::{Transport, TransportEvent, TransportPeerId};
pub use matchbox_socket::MessageLoopFuture;
/// Matchbox signaling server for sessions, behind TLS so browsers on HTTPS pages can reach it.
pub const DEFAULT_SIGNALING_SERVER: &str = "wss://graphite.kobert.dev";
-175
View File
@@ -1,175 +0,0 @@
//! In-process transport for deterministic simulation. Every packet sits in a per-(sender, receiver)
//! queue until `step` delivers it, so interleavings across peers are driven by the seed while each
//! pair stays ordered like a reliable channel.
use crate::packet::{PacketError, SyncPacket};
use crate::transport::{Transport, TransportEvent, TransportPeerId};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::{Arc, Mutex};
#[derive(Default)]
struct Shared {
connected: Vec<TransportPeerId>,
inboxes: HashMap<TransportPeerId, VecDeque<TransportEvent>>,
in_flight: BTreeMap<(TransportPeerId, TransportPeerId), VecDeque<SyncPacket>>,
next_peer: u128,
}
impl Shared {
fn disconnect(&mut self, id: TransportPeerId) {
self.connected.retain(|&other| other != id);
self.in_flight.retain(|&(from, to), _| from != id && to != id);
for &other in &self.connected.clone() {
self.inboxes.entry(other).or_default().push_back(TransportEvent::PeerDisconnected(id));
self.inboxes.entry(id).or_default().push_back(TransportEvent::PeerDisconnected(other));
}
}
}
pub struct MockNetwork {
shared: Arc<Mutex<Shared>>,
rng: SplitMix64,
}
impl MockNetwork {
pub fn new(seed: u64) -> Self {
Self {
shared: Arc::new(Mutex::new(Shared::default())),
rng: SplitMix64(seed),
}
}
/// A new, not yet connected peer.
pub fn endpoint(&mut self) -> MockEndpoint {
let mut shared = self.shared.lock().unwrap();
shared.next_peer += 1;
let id = TransportPeerId(uuid::Uuid::from_u128(shared.next_peer));
shared.inboxes.insert(id, VecDeque::new());
MockEndpoint {
id,
shared: self.shared.clone(),
known_peers: Vec::new(),
}
}
pub fn connect(&mut self, id: TransportPeerId) {
let mut shared = self.shared.lock().unwrap();
if shared.connected.contains(&id) {
return;
}
for &other in &shared.connected.clone() {
shared.inboxes.entry(other).or_default().push_back(TransportEvent::PeerConnected(id));
shared.inboxes.entry(id).or_default().push_back(TransportEvent::PeerConnected(other));
}
shared.connected.push(id);
}
pub fn disconnect(&mut self, id: TransportPeerId) {
self.shared.lock().unwrap().disconnect(id);
}
pub fn pending(&self) -> usize {
self.shared.lock().unwrap().in_flight.values().map(VecDeque::len).sum()
}
/// Deliver one in-flight packet from a randomly chosen sender/receiver pair.
pub fn step(&mut self) -> bool {
let mut shared = self.shared.lock().unwrap();
let queues: Vec<_> = shared.in_flight.iter().filter(|(_, queue)| !queue.is_empty()).map(|(&key, _)| key).collect();
if queues.is_empty() {
return false;
}
let (from, to) = queues[self.rng.below(queues.len())];
let packet = shared.in_flight.get_mut(&(from, to)).and_then(VecDeque::pop_front).expect("queue is non-empty");
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(from, packet));
true
}
pub fn deliver_all(&mut self) {
while self.step() {}
}
/// Deliver everything in flight to one peer, leaving every other peer's queues untouched. Random
/// stepping cannot target a receiver, so this is how a test puts a packet in one peer's hands and
/// not another's.
pub fn deliver_to(&mut self, to: TransportPeerId) {
let mut shared = self.shared.lock().unwrap();
let queues: Vec<_> = shared.in_flight.keys().copied().filter(|&(_, receiver)| receiver == to).collect();
for key in queues {
let packets: VecDeque<SyncPacket> = shared.in_flight.get_mut(&key).map(std::mem::take).unwrap_or_default();
for packet in packets {
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(key.0, packet));
}
}
}
pub fn random_below(&mut self, bound: usize) -> usize {
self.rng.below(bound)
}
}
/// Like a real socket, an endpoint only knows the peers whose connect events it has polled, so it
/// can't send to a peer before it had the chance to greet it.
pub struct MockEndpoint {
id: TransportPeerId,
shared: Arc<Mutex<Shared>>,
known_peers: Vec<TransportPeerId>,
}
impl MockEndpoint {
pub fn id(&self) -> TransportPeerId {
self.id
}
}
impl Transport for MockEndpoint {
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
if self.known_peers.contains(&to) {
self.shared.lock().unwrap().in_flight.entry((self.id, to)).or_default().push_back(packet.clone());
}
Ok(())
}
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
for to in self.known_peers.clone() {
if Some(to) != excluded {
self.send(to, packet)?;
}
}
Ok(())
}
fn poll(&mut self) -> Vec<TransportEvent> {
let events: Vec<_> = self.shared.lock().unwrap().inboxes.get_mut(&self.id).map(|inbox| inbox.drain(..).collect()).unwrap_or_default();
for event in &events {
match event {
TransportEvent::PeerConnected(peer) => self.known_peers.push(*peer),
TransportEvent::PeerDisconnected(peer) => self.known_peers.retain(|known| known != peer),
_ => {}
}
}
events
}
fn close(&mut self) {
self.shared.lock().unwrap().disconnect(self.id);
}
}
struct SplitMix64(u64);
impl SplitMix64 {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
fn below(&mut self, bound: usize) -> usize {
(self.next() % bound as u64) as usize
}
}
-161
View File
@@ -1,161 +0,0 @@
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredHotOps, Rev, UserId};
use serde::{Deserialize, Serialize};
/// The host is the single peer that retires hot ops.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Role {
Host,
Guest,
/// Connected to the document's room without knowing yet whether a host is there: a host's hello makes
/// this peer a guest, and a room with no host makes it the host after a grace period.
Undecided,
}
/// How far one peer's broadcasts had got. A peer keeps its `PeerId` across a reconnect but restarts
/// `seq`, so `epoch` names the incarnation that produced it and counters from different epochs are
/// never compared.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerSeq {
pub peer: PeerId,
pub epoch: u64,
pub seq: u64,
}
/// MessagePack-encoded on the wire.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum SyncPacket {
/// Sent first on every new connection. `epoch` and `seq` anchor the receiver's counter for this
/// sender, since broadcasts made before the connection were never sent to it.
Hello {
peer: PeerId,
user: UserId,
role: Role,
epoch: u64,
seq: u64,
},
/// `known_revs` come from `Session::known_revs`, so the host can send only what's missing.
SyncRequest {
known_revs: Vec<Rev>,
},
Sync(Box<SyncPayload>),
Broadcast(Broadcast),
/// A guest asks the host to undo (`restore: false`) or redo (`restore: true`) one of its retired
/// interactions, named by its last delta. The host answers the room with a `HeadMove` or new deltas.
UndoRequest {
rev: Rev,
restore: bool,
},
/// A guest asks the host to move the shared head to `rev`, an ancestor of it, leaving the line since as a
/// branch. The host answers the room with a `HeadMove` without copies.
MoveRequest {
rev: Rev,
},
ResourceRequest(Vec<ResourceHash>),
Resource {
hash: ResourceHash,
#[serde(with = "serde_bytes")]
bytes: Vec<u8>,
},
/// Who the sender is, for display. Sent to a peer after the hello and to everyone when it changes; the
/// newest wins. Presence like this is never history, so it stays outside the causal broadcast.
Profile {
name: String,
},
/// Where the sender's pointer is, `None` when it left the viewport. Sent at most once a frame and identified
/// by the link it arrives on, so it carries nothing but the position and the space it is in.
Cursor {
position: Option<CursorPosition>,
},
/// A peer's statements about the history, users and their names among it. Outside the causal order: the
/// record merges the same whatever order it arrives in.
Metadata(HistoryMetadata),
}
/// The host's answer to a `SyncRequest`. `registry` is only sent when the host recognized none of
/// the requester's revs; otherwise `deltas` extend the requester's history. `seen` is the host's
/// delivery vector at snapshot time, which the guest adopts so later broadcasts line up.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SyncPayload {
pub registry: Option<Registry>,
pub deltas: Vec<Delta>,
pub head: Option<Rev>,
pub hot_log: Vec<HotOp>,
pub known_revs: Vec<Rev>,
pub seen: Vec<PeerSeq>,
/// Which hot ops the history being handed over already covers, so the requester can recognize one
/// it is holding rather than re-entering it as live work.
pub retired: RetiredHotOps,
/// Which hot ops their authors took back, so the requester drops any it still holds.
#[serde(default)]
pub retracted: RetiredHotOps,
/// The document's identity, so a peer that started from an empty document adopts it and can reconnect
/// to the same room by opening its own copy later.
#[serde(default)]
pub document_id: Option<u64>,
/// What the host has on record about the history's users, so a joiner can name every author.
#[serde(default)]
pub metadata: HistoryMetadata,
}
/// Causal broadcast envelope. `seq` numbers the sender's broadcasts from 1 within `epoch`, and `seen`
/// is the sender's delivery vector; a receiver holds the packet until it has delivered everything in
/// `seen`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Broadcast {
pub epoch: u64,
pub seq: u64,
pub seen: Vec<PeerSeq>,
pub body: BroadcastBody,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum BroadcastBody {
HotOps(Vec<HotOp>),
/// `deltas` are in causal order. `retires` names the hot ops they replace (empty for a plain history transfer).
Deltas {
deltas: Vec<Delta>,
retires: Vec<HotOpId>,
},
/// Hot ops their author took back: they leave every hot log and never retire.
Retract(Vec<HotOpId>),
/// Everything a peer knows to have been taken back, re-announced on a membership change the way hot
/// ops are, so a peer that joined while a retraction was in flight still hears of it.
RetractedMarks(RetiredHotOps),
/// The host dropped a retired interaction out of the line: every peer walks back and follows the head.
HeadMove(HeadMove),
}
#[derive(Debug, thiserror::Error)]
pub enum PacketError {
#[error("failed to encode packet: {0}")]
Encode(#[from] rmp_serde::encode::Error),
#[error("failed to decode packet: {0}")]
Decode(#[from] rmp_serde::decode::Error),
}
impl SyncPacket {
pub fn encode(&self) -> Result<Box<[u8]>, PacketError> {
Ok(rmp_serde::to_vec(self)?.into_boxed_slice())
}
pub fn decode(bytes: &[u8]) -> Result<Self, PacketError> {
Ok(rmp_serde::from_slice(bytes)?)
}
}
/// A peer's pointer: where, and in which of the editor's spaces, so it is drawn only where it means something.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CursorPosition {
pub position: [f64; 2],
pub space: CursorSpace,
/// The icon name of the tool the peer holds, shown beside the pointer; `None` from a viewer with no tools.
pub tool: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CursorSpace {
/// Document coordinates over the canvas.
Document,
/// Node-graph coordinates of the network at this path of node ids, from the document network down.
Graph { network: Vec<u64> },
}
File diff suppressed because it is too large. Load diff
-332
View File
@@ -1,332 +0,0 @@
use crate::packet::{PacketError, SyncPacket};
use crate::transport::{Transport, TransportEvent, TransportPeerId};
use futures::StreamExt;
use futures::channel::mpsc::UnboundedSender;
use matchbox_socket::{MessageLoopFuture, Packet, PeerState, WebRtcSocket};
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
const CHANNEL: usize = 0;
/// Largest SCTP message every browser accepts.
const CHUNK_BYTES: usize = 16 * 1024;
const FRAME_FINAL: u8 = 1;
const FRAME_MORE: u8 = 0;
/// Split a packet into `[flag][bytes]` chunks, the last carrying [`FRAME_FINAL`] so a receiver finds
/// the packet boundary without a length prefix.
fn frames(bytes: &[u8]) -> Vec<Box<[u8]>> {
// An empty packet still gets one frame. Chunking it would yield none at all, and the packet would
// leave no trace on the wire rather than arriving empty.
let chunks: Vec<&[u8]> = if bytes.is_empty() { vec![&[]] } else { bytes.chunks(CHUNK_BYTES).collect() };
chunks
.iter()
.enumerate()
.map(|(index, chunk)| {
let flag = if index + 1 == chunks.len() { FRAME_FINAL } else { FRAME_MORE };
std::iter::once(flag).chain(chunk.iter().copied()).collect()
})
.collect()
}
/// Per-peer reassembly of framed packets. The channel is reliable and ordered per peer, so chunks
/// arrive in the order they were sent and a packet ends at the first [`FRAME_FINAL`].
#[derive(Default)]
struct Reassembler {
partial: HashMap<TransportPeerId, Vec<u8>>,
}
impl Reassembler {
/// The packet's bytes once its final chunk lands, or `None` while more are still to come.
fn accept(&mut self, peer: TransportPeerId, frame: &[u8]) -> Option<Vec<u8>> {
let (&flag, chunk) = frame.split_first()?;
let buffer = self.partial.entry(peer).or_default();
buffer.extend_from_slice(chunk);
(flag == FRAME_FINAL).then(|| std::mem::take(buffer))
}
/// Drop a peer's half-received packet, which nothing will ever complete.
fn forget(&mut self, peer: TransportPeerId) {
self.partial.remove(&peer);
}
}
/// Packets that arrived and wait to be polled, and whoever is waiting for them.
#[derive(Debug, Default)]
struct Inbox {
packets: VecDeque<(TransportPeerId, Packet)>,
waker: Option<Waker>,
/// Set once the socket loop ended: nothing more will arrive.
closed: bool,
}
fn lock(inbox: &Mutex<Inbox>) -> std::sync::MutexGuard<'_, Inbox> {
inbox.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
/// A handle onto a room's inbox that resolves when a packet is waiting, so the room is polled as packets
/// arrive rather than once per frame. A hidden browser tab gets about one frame a second, which made a
/// host answer each step of a join a second late while the data channel itself delivered on time.
#[derive(Clone, Debug)]
pub struct Incoming {
inbox: Arc<Mutex<Inbox>>,
}
impl Incoming {
/// Resolves to `true` once a packet is waiting, and to `false` once the room's loop has ended and
/// nothing more can arrive, so the caller knows not to wait again.
pub async fn wait(&self) -> bool {
std::future::poll_fn(|cx| self.poll_ready(cx)).await
}
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<bool> {
let mut inbox = lock(&self.inbox);
if !inbox.packets.is_empty() {
return Poll::Ready(true);
}
if inbox.closed {
return Poll::Ready(false);
}
inbox.waker = Some(cx.waker().clone());
Poll::Pending
}
}
/// One matchbox room over WebRTC. Packets are split into `[flag][bytes]` chunks; the reliable
/// channel is ordered per peer, so the receiver reassembles by appending until the final flag.
/// The returned future must be polled continuously by the caller.
pub struct Room {
socket: WebRtcSocket,
outgoing: UnboundedSender<(TransportPeerId, Packet)>,
inbox: Arc<Mutex<Inbox>>,
incoming: Reassembler,
}
impl Room {
pub fn connect(signaling_url: &str) -> (Self, MessageLoopFuture) {
// WebRTC's DTLS goes through rustls, which needs one provider chosen when several are linked.
#[cfg(not(target_family = "wasm"))]
let _ = rustls::crypto::ring::default_provider().install_default();
let (mut socket, driver) = WebRtcSocket::new_reliable(signaling_url);
let (outgoing, mut received) = socket.take_channel(CHANNEL).expect("a reliable socket has its one channel").split();
let inbox = Arc::new(Mutex::new(Inbox::default()));
// Arrivals move into the inbox as they happen and wake whoever waits on it. The forwarder ends with
// the socket loop, which drops its senders when it returns; the loop's result stays the driver's.
let forwarder = {
let inbox = Arc::clone(&inbox);
async move {
while let Some(arrived) = received.next().await {
let mut inbox = lock(&inbox);
inbox.packets.push_back(arrived);
if let Some(waker) = inbox.waker.take() {
waker.wake();
}
}
let mut inbox = lock(&inbox);
inbox.closed = true;
if let Some(waker) = inbox.waker.take() {
waker.wake();
}
}
};
let driver: MessageLoopFuture = Box::pin(async move {
let (result, ()) = futures::join!(driver, forwarder);
result
});
(
Self {
socket,
outgoing,
inbox,
incoming: Reassembler::default(),
},
driver,
)
}
/// A handle that resolves whenever a packet waits in this room.
pub fn incoming(&self) -> Incoming {
Incoming { inbox: Arc::clone(&self.inbox) }
}
fn send_chunks(&mut self, bytes: &[u8], peers: &[TransportPeerId]) {
for frame in frames(bytes) {
for &peer in peers {
// A send only fails once the socket loop has ended, which the loop's own future reports.
if self.outgoing.unbounded_send((peer, frame.clone())).is_err() {
return;
}
}
}
}
}
impl Transport for Room {
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
let bytes = packet.encode()?;
self.send_chunks(&bytes, &[to]);
Ok(())
}
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
let bytes = packet.encode()?;
let peers: Vec<_> = self.socket.connected_peers().filter(|&peer| Some(peer) != excluded).collect();
self.send_chunks(&bytes, &peers);
Ok(())
}
fn poll(&mut self) -> Vec<TransportEvent> {
let mut events = Vec::new();
for (peer, state) in self.socket.update_peers() {
events.push(match state {
PeerState::Connected => TransportEvent::PeerConnected(peer),
PeerState::Disconnected => {
self.incoming.forget(peer);
TransportEvent::PeerDisconnected(peer)
}
});
}
let received: Vec<_> = lock(&self.inbox).packets.drain(..).collect();
for (peer, frame) in received {
let Some(bytes) = self.incoming.accept(peer, &frame) else { continue };
events.push(match SyncPacket::decode(&bytes) {
Ok(packet) => TransportEvent::Packet(peer, packet),
Err(error) => TransportEvent::Malformed(peer, error),
});
}
events
}
fn close(&mut self) {
self.socket.close();
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::FutureExt;
fn peer(byte: u128) -> TransportPeerId {
TransportPeerId(uuid::Uuid::from_u128(byte))
}
/// The inbox handle resolves on an arrival and once more when the loop ends, and is pending otherwise,
/// so a poll driven by it runs on packets rather than on frames.
#[test]
fn the_inbox_wakes_on_arrival_and_reports_the_end() {
let inbox = Arc::new(Mutex::new(Inbox::default()));
let incoming = Incoming { inbox: Arc::clone(&inbox) };
assert_eq!(incoming.wait().now_or_never(), None, "nothing arrived yet");
lock(&inbox).packets.push_back((peer(1), Box::new([FRAME_FINAL, 7])));
assert_eq!(incoming.wait().now_or_never(), Some(true), "an arrival resolves the wait");
assert_eq!(incoming.wait().now_or_never(), Some(true), "and keeps it resolved until the inbox is drained");
lock(&inbox).packets.clear();
assert_eq!(incoming.wait().now_or_never(), None, "drained: pending again");
lock(&inbox).closed = true;
assert_eq!(incoming.wait().now_or_never(), Some(false), "the end of the loop resolves the wait for good");
}
/// Push every frame at a reassembler and collect whatever packets come back out.
fn round_trip(bytes: &[u8]) -> Vec<Vec<u8>> {
let mut incoming = Reassembler::default();
frames(bytes).into_iter().filter_map(|frame| incoming.accept(peer(1), &frame)).collect()
}
/// A packet within one chunk travels as a single final frame.
#[test]
fn a_small_packet_is_one_frame() {
let bytes = b"hello".to_vec();
let framed = frames(&bytes);
assert_eq!(framed.len(), 1);
assert_eq!(framed[0][0], FRAME_FINAL);
assert_eq!(round_trip(&bytes), vec![bytes]);
}
/// Chunking an empty packet yields no chunks at all, so it needs a frame of its own or it would
/// leave no trace on the wire.
#[test]
fn an_empty_packet_still_produces_one_frame() {
let framed = frames(&[]);
assert_eq!(framed.len(), 1, "an empty packet must still be framed");
assert_eq!(framed[0][0], FRAME_FINAL);
assert_eq!(round_trip(&[]), vec![Vec::<u8>::new()]);
}
/// The boundary either side of the SCTP limit: exactly one chunk stays one frame, one byte more
/// splits, and both rebuild byte for byte.
#[test]
fn packets_around_the_chunk_boundary_round_trip() {
for length in [CHUNK_BYTES - 1, CHUNK_BYTES, CHUNK_BYTES + 1, CHUNK_BYTES * 3 + 7] {
let bytes: Vec<u8> = (0..length).map(|index| (index % 251) as u8).collect();
let framed = frames(&bytes);
assert_eq!(framed.len(), length.div_ceil(CHUNK_BYTES), "wrong frame count for {length} bytes");
assert!(framed.iter().all(|frame| frame.len() <= CHUNK_BYTES + 1), "a frame exceeded the SCTP limit");
assert!(framed.iter().rev().skip(1).all(|frame| frame[0] == FRAME_MORE), "only the last frame is final");
assert_eq!(framed.last().expect("at least one frame")[0], FRAME_FINAL);
assert_eq!(round_trip(&bytes), vec![bytes], "{length} bytes did not round trip");
}
}
/// Two peers' chunks interleave on one channel, so reassembly is per peer or one packet would be
/// spliced into the other.
#[test]
fn interleaved_peers_reassemble_separately() {
let (first, second) = (peer(1), peer(2));
let mut incoming = Reassembler::default();
let long: Vec<u8> = (0..CHUNK_BYTES + 32).map(|index| (index % 97) as u8).collect();
let short = b"short".to_vec();
let long_frames = frames(&long);
let short_frames = frames(&short);
assert_eq!(long_frames.len(), 2, "the long packet must span two frames to interleave");
// The short packet arrives whole between the long packet's two chunks.
assert_eq!(incoming.accept(first, &long_frames[0]), None);
assert_eq!(incoming.accept(second, &short_frames[0]), Some(short));
assert_eq!(incoming.accept(first, &long_frames[1]), Some(long));
}
/// A peer that drops mid-packet leaves a partial buffer, which must not be prepended to whatever
/// the next peer to reuse that id sends.
#[test]
fn forgetting_a_peer_discards_its_partial_packet() {
let sender = peer(1);
let mut incoming = Reassembler::default();
let long: Vec<u8> = (0..CHUNK_BYTES + 8).map(|index| (index % 89) as u8).collect();
assert_eq!(incoming.accept(sender, &frames(&long)[0]), None);
incoming.forget(sender);
let fresh = b"fresh".to_vec();
assert_eq!(incoming.accept(sender, &frames(&fresh)[0]), Some(fresh), "the abandoned prefix must be gone");
}
/// A zero-length frame carries no flag byte, so it is ignored rather than read past its end.
#[test]
fn an_empty_frame_is_ignored() {
let mut incoming = Reassembler::default();
assert_eq!(incoming.accept(peer(1), &[]), None);
}
}
-199
View File
@@ -1,199 +0,0 @@
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredHotOps, Rev, Session};
use std::collections::HashSet;
pub type TargetError = Box<dyn std::error::Error>;
/// The document state a `Replica` reads from and applies remote changes to.
pub trait SyncTarget {
fn peer(&self) -> PeerId;
/// The identity of the document this target holds, if it has one; a session token is derived from it.
fn document_id(&self) -> Option<u64> {
None
}
/// Take on the host's document identity after a full sync, so this copy is the same document from now on.
fn adopt_document_id(&mut self, _document_id: u64) -> Result<(), TargetError> {
Ok(())
}
fn head(&self) -> Option<Rev>;
fn retired_registry(&self) -> Registry;
fn hot_log(&self) -> Vec<HotOp>;
fn known_revs(&self) -> Vec<Rev>;
fn contains_rev(&self, rev: Rev) -> bool;
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta>;
/// Highest hot-op counter retired per author.
fn retired_marks(&self) -> RetiredHotOps;
/// Which hot ops were taken back by their authors. See [`Session::retracted_marks`].
fn retracted_marks(&self) -> RetiredHotOps;
/// Take on a peer's retirement marks, dropping any hot op they show as already retired.
fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError>;
/// Take on a peer's retractions, dropping what they cover from the hot log.
fn absorb_retracted_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError>;
/// What people state about the history, users and their names among it, kept beside it and merged
/// last-writer-wins. Empty for a target that keeps none.
fn metadata(&self) -> HistoryMetadata {
HistoryMetadata::default()
}
/// Take on a peer's statements about the history. Returns whether any of them was news.
fn absorb_metadata(&mut self, _remote: &HistoryMetadata) -> Result<bool, TargetError> {
Ok(false)
}
/// Replace all state with the given retired state.
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError>;
/// Must be idempotent on structural ops: a buffered op may already be reflected by the sync.
/// Returns the ops it could not apply, whose referents have not arrived yet; the caller retries
/// them as later ops fill the gaps.
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError>;
/// Take the host's deltas on and follow its head, `head` being where the host is after them (the
/// batch's last delta when `None`). See [`Session::follow`].
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId], head: Option<Rev>) -> Result<(), TargetError>;
/// Host only: take a peer's deltas on, and where its line diverged from this one, join the two heads
/// with a merge delta rather than follow it. Returns what the room has yet to see, the deltas absorbed
/// and the merge, for the host to broadcast so every guest follows to the joined head.
fn merge_divergent(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<Vec<Delta>, TargetError>;
/// A peer took back hot ops of its own: drop them and re-derive what they touched.
fn retract_hot_ops(&mut self, ops: &[HotOpId]) -> Result<(), TargetError>;
/// Host only: drop a retired interaction out of the shared line. See [`Session::drop_interaction`].
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError>;
/// Host only: mint a dropped interaction again on top of the line. See [`Session::restore_interaction`].
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError>;
/// Host only: move the shared head to an ancestor, leaving the line since as a branch. See [`Session::move_head_to`].
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
let _ = rev;
Err("this target cannot move its head".into())
}
/// Follow the host's cursor move. See [`Session::apply_head_move`].
fn apply_head_move(&mut self, moved: &HeadMove) -> Result<(), TargetError>;
/// Make everything applied since the last flush durable. Called once per [`Replica::poll`](crate::Replica::poll),
/// so a target that rewrites whole files can do it once for a batch rather than once per packet.
fn flush(&mut self) -> Result<(), TargetError> {
Ok(())
}
/// Referenced resources whose bytes are not available locally.
fn missing_resources(&self) -> HashSet<ResourceHash> {
HashSet::new()
}
/// `None` when the bytes can't be produced synchronously; the request is then surfaced as an event.
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
let _ = hash;
None
}
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
let _ = (hash, bytes);
Ok(())
}
}
impl SyncTarget for Session {
fn peer(&self) -> PeerId {
Session::peer(self)
}
fn head(&self) -> Option<Rev> {
self.head_rev()
}
fn retired_registry(&self) -> Registry {
Session::retired_registry(self).clone()
}
fn hot_log(&self) -> Vec<HotOp> {
Session::hot_log(self).to_vec()
}
fn known_revs(&self) -> Vec<Rev> {
Session::known_revs(self)
}
fn contains_rev(&self, rev: Rev) -> bool {
self.delta(rev).is_some()
}
fn deltas_unknown_to(&self, known: &[Rev]) -> Vec<Delta> {
Session::deltas_unknown_to(self, known.iter().copied()).into_iter().cloned().collect()
}
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
// Kept across the replace: a sequence this peer already spent must not come round again, or an
// op of its own would be taken for one already retired.
let spent = self.next_hot_sequence();
*self = Session::load(self.peer(), self.user(), registry, history, head, Vec::new(), self.next_node_counter());
self.restore_hot_sequence(spent);
Ok(())
}
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
// Every op gets its turn even if one fails, since the broadcast that carried them is consumed by
// the time this runs. A failure usually means the entity the op names has not arrived here yet,
// so it is handed back to be retried rather than dropped.
let mut deferred = Vec::new();
for hot_op in ops {
if self.replay_hot_op(hot_op.clone()).is_err() {
deferred.push(hot_op);
}
}
Ok(deferred)
}
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId], head: Option<Rev>) -> Result<(), TargetError> {
self.follow(deltas, head)?;
self.discard_hot_ops(retires)?;
Ok(())
}
fn merge_divergent(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<Vec<Delta>, TargetError> {
let mut absorbed: Vec<Delta> = deltas.iter().filter(|delta| !self.contains_rev(delta.id)).cloned().collect();
let outcome = self.merge(deltas)?;
self.discard_hot_ops(retires)?;
if let document_graph_storage::MergeOutcome::Merged(rev) = outcome {
absorbed.extend(self.delta(rev).cloned());
}
Ok(absorbed)
}
fn retired_marks(&self) -> RetiredHotOps {
Session::retired_marks(self).clone()
}
fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError> {
Session::absorb_retired_marks(self, remote)?;
Ok(())
}
fn retracted_marks(&self) -> RetiredHotOps {
Session::retracted_marks(self).clone()
}
fn absorb_retracted_marks(&mut self, remote: &RetiredHotOps) -> Result<(), TargetError> {
Session::absorb_retracted_marks(self, remote);
Ok(())
}
fn retract_hot_ops(&mut self, ops: &[HotOpId]) -> Result<(), TargetError> {
Session::retract_hot_ops(self, ops);
Ok(())
}
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
let (moved, _) = Session::drop_interaction(self, rev)?;
Ok(moved)
}
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError> {
let revs = Session::restore_interaction(self, rev)?;
Ok(revs.into_iter().filter_map(|rev| self.delta(rev).cloned()).collect())
}
fn apply_head_move(&mut self, moved: &HeadMove) -> Result<(), TargetError> {
Session::apply_head_move(self, moved)?;
Ok(())
}
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
Ok(Session::move_head_to(self, rev)?.0)
}
}
-103
View File
@@ -1,103 +0,0 @@
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use std::fmt;
use std::str::FromStr;
/// Identifies the text form as a Graphite session token, like GitLab's `glpat-` tokens.
const PREFIX: &str = "graphite-";
/// Random session ID, used as the matchbox room name. Entropy is supplied by the caller.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SessionToken(pub [u8; 16]);
impl SessionToken {
pub fn signaling_url(&self, signaling_server: &str) -> String {
format!("{}/{}", signaling_server.trim_end_matches('/'), self)
}
}
impl fmt::Display for SessionToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{PREFIX}{}", URL_SAFE_NO_PAD.encode(self.0))
}
}
#[derive(Debug, thiserror::Error)]
#[error("invalid session token")]
pub struct InvalidSessionToken;
impl FromStr for SessionToken {
type Err = InvalidSessionToken;
/// Parses the bare token, or a share link carrying it as the `session` query parameter, so a pasted link
/// works wherever a token does: the editor's join field, the CLI, a URL scheme.
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.trim();
let s = match s.split_once("session=") {
Some((_, rest)) => rest.split(['&', '#', ' ']).next().unwrap_or(""),
None => s,
};
let encoded = s.strip_prefix(PREFIX).ok_or(InvalidSessionToken)?;
let bytes = URL_SAFE_NO_PAD.decode(encoded).map_err(|_| InvalidSessionToken)?;
let bytes = bytes.try_into().map_err(|_| InvalidSessionToken)?;
Ok(Self(bytes))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_through_string() {
let token = SessionToken([7; 16]);
assert_eq!(token.to_string().parse::<SessionToken>().unwrap(), token);
}
#[test]
fn parses_the_token_out_of_a_share_link() {
let token = SessionToken([7; 16]);
let link = format!(" https://editor.graphite.rs/?session={token}#top ");
assert_eq!(link.parse::<SessionToken>().unwrap(), token);
assert_eq!(format!("http://localhost:8080/?debug=1&session={token}").parse::<SessionToken>().unwrap(), token);
}
#[test]
fn rejects_wrong_length_or_missing_prefix() {
assert!("graphite-AAAA".parse::<SessionToken>().is_err());
assert!("BwcHBwcHBwcHBwcHBwcHBw".parse::<SessionToken>().is_err());
}
}
impl SessionToken {
/// The token every copy of one document shares: derived from the document's id, so a copy edited
/// apart reconnects to the same room as the others by opening the same file, with no link to pass
/// around. Document ids are random 64-bit values, so the room is no more guessable than the id; the
/// mixing only spreads the id over the token's width.
pub fn for_document(document_id: u64) -> Self {
fn mix(mut value: u64) -> u64 {
value = value.wrapping_add(0x9E37_79B9_7F4A_7C15);
value = (value ^ (value >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
value = (value ^ (value >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
value ^ (value >> 31)
}
let mut bytes = [0u8; 16];
bytes[..8].copy_from_slice(&mix(document_id).to_le_bytes());
bytes[8..].copy_from_slice(&mix(document_id ^ 0x5A5A_5A5A_5A5A_5A5A).to_le_bytes());
Self(bytes)
}
}
#[cfg(test)]
mod derived_token_tests {
use super::SessionToken;
/// Every copy of a document derives the same token, and different documents different ones.
#[test]
fn a_document_id_derives_one_token() {
assert_eq!(SessionToken::for_document(7), SessionToken::for_document(7));
assert_ne!(SessionToken::for_document(7), SessionToken::for_document(8));
let text = SessionToken::for_document(7).to_string();
assert_eq!(text.parse::<SessionToken>().expect("round trip"), SessionToken::for_document(7));
}
}
-23
View File
@@ -1,23 +0,0 @@
use crate::packet::{PacketError, SyncPacket};
pub use matchbox_socket::PeerId as TransportPeerId;
pub enum TransportEvent {
PeerConnected(TransportPeerId),
PeerDisconnected(TransportPeerId),
Packet(TransportPeerId, SyncPacket),
Malformed(TransportPeerId, PacketError),
}
/// Packet delivery between the peers of one session. Delivery must be reliable and ordered per
/// sender, which is what lets the `Replica` skip acknowledgements and buffering.
pub trait Transport: Send + Sync {
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError>;
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError>;
fn poll(&mut self) -> Vec<TransportEvent>;
fn close(&mut self);
fn broadcast(&mut self, packet: &SyncPacket) -> Result<(), PacketError> {
self.broadcast_except(None, packet)
}
}
Loaded 100 of 632 files, more files were not shown because too many files have changed in this diff. Show more