-
Notifications
You must be signed in to change notification settings - Fork 418
Expand file tree
/
Copy pathstate.rs
More file actions
7825 lines (7144 loc) · 272 KB
/
Copy pathstate.rs
File metadata and controls
7825 lines (7144 loc) · 272 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2026 Epic Games, Inc.
// SPDX-License-Identifier: MIT
mod diff;
pub mod dump;
mod sink;
use core::str;
use std::future::Future;
use std::io::Write;
use std::mem::size_of;
use std::pin::Pin;
use std::str::FromStr;
use std::sync::Arc;
use std::sync::Weak;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use bitflags::bitflags;
use bytes::Bytes;
use lore_base::error::InvalidPath;
use lore_base::lore_spawn;
use lore_error_set::prelude::*;
use serde::Deserialize;
use serde::Serialize;
pub use sink::ChangeSink;
pub use sink::OwnedChangeSink;
use tokio::join;
use tokio::task::JoinHandle;
use tokio::task::JoinSet;
use zerocopy::FromZeros;
use zerocopy::Immutable;
use crate::bitflagsops;
use crate::branch;
use crate::change;
use crate::change::FileAction;
use crate::change::NodeChange;
use crate::change::NodeChangeState;
use crate::errors::LinkNotFound;
use crate::errors::NodeNotFound;
use crate::errors::NotFound;
use crate::errors::Oversized;
use crate::errors::StateErrors;
use crate::filter::FilterMode;
use crate::fragment::FragmentFlags;
use crate::hash;
use crate::immutable;
use crate::immutable::ImmutableError;
use crate::immutable::ReadBoxFromImmutable;
use crate::immutable::ReadFromImmutable;
use crate::immutable::WriteToImmutable;
use crate::immutable::read_options_from_repository;
use crate::instance::InstanceId;
use crate::interface::LoreString;
use crate::link::LinkFlags;
use crate::lore::*;
use crate::lore_debug;
use crate::lore_drain_tasks;
use crate::lore_info;
use crate::lore_trace;
use crate::lore_warn;
use crate::metadata;
use crate::metadata::Metadata;
use crate::metadata::MetadataType;
use crate::nametable::NameTable;
use crate::node;
use crate::node::*;
use crate::repository::DOT_LORE;
use crate::repository::DOT_URC;
use crate::repository::RepositoryContext;
use crate::repository::RepositoryWriteToken;
use crate::revision::RevisionMetadata;
use crate::stage::stage_delete;
use crate::state::diff::NodeSearchResult;
use crate::state::diff::get_filtered_node_and_path;
use crate::state::diff::get_node_and_path;
use crate::store::KeyType;
use crate::store::StoreMatch;
use crate::util;
use crate::util::path::RelativePath;
use crate::util::path::RelativePathBuf;
/// Data for an event summarizing a dumped repository state.
#[repr(C)]
#[derive(Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LoreRepositoryStateDumpEventData {
/// Sequence number of the revision.
pub revision_number: u64,
/// Hash of the revision.
pub revision: Hash,
/// Hash of the state's node tree.
pub tree_hash: Hash,
/// Size of the node tree in bytes.
pub tree_size: u64,
}
/// Data for an event describing a single node in a dumped repository state.
#[repr(C)]
#[derive(Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LoreRepositoryStateDumpNodeEventData {
/// Name of the node.
pub name: LoreString,
/// Identifier of the node.
pub id: u32,
/// Identifier of the parent node.
pub parent: u32,
/// Identifier of the next sibling node.
pub sibling: u32,
/// File mode of the node.
pub mode: u16,
/// Size of the node's content in bytes.
pub size: u64,
/// Node flags.
pub flags: u16,
/// Type-specific detail for the node.
pub type_data: LoreString,
}
pub type StateError = StateErrors;
#[derive(Debug)]
pub struct StateNamedNode {
node: NodeID,
name: u64,
}
pub struct StateChildrenNodes {
pub repository: Arc<RepositoryContext>,
pub state: Arc<State>,
pub children: Vec<StateNamedNode>,
}
#[derive(Debug)]
pub struct StateNamedStringNode {
pub node: NodeID,
pub name: u64,
pub name_string: String,
}
pub struct StateNamedChildrenNodes {
pub repository: Arc<RepositoryContext>,
pub state: Arc<State>,
pub children: Vec<StateNamedStringNode>,
}
bitflags! {
#[repr(transparent)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct StateFlags: u32 {
/// No flags
const NoFlags = 0;
/// State is dirty
const Dirty = 0b1;
/// State is in conflict
const Conflict = 0b10;
/// State is merged (branch merge)
const Merge = 0b100;
/// State is cherry-picked
const CherryPick = 0b1000;
/// State is a revert operation
const Revert = 0b10000;
}
}
bitflagsops!(StateFlags, u32);
/// Iterator over child nodes of a directory, loading blocks with nametable.
/// Yields `(NodeID, Node, NodeNameLock)` — the child's ID, node data, and name.
///
/// The yielded [`NodeNameLock`] holds a read lock on the node block (zero-copy
/// name access), not an owned string. Drop it before any call that may take
/// another lock — recursing into this iterator, or a `State` method that loads a
/// block such as `block_with_nametable`, which can *write*-lock the same block to
/// deserialize its nametable. The locks are not reentrant, so holding the name
/// across such a call (especially an `.await`) risks deadlock. Copy it out with
/// [`NodeNameLock::freeze`] first if you need it past that point.
pub struct StateNodeChildrenWithNameIterator {
state: Arc<State>,
repository: Arc<RepositoryContext>,
parent_node_id: NodeID,
current_node_id: Option<NodeID>,
current_block: Option<Arc<NodeBlock>>,
current_iblock: usize,
cycle: SiblingCycleGuard,
}
impl StateNodeChildrenWithNameIterator {
/// Create a new iterator starting from the first child of the given parent node.
/// Loads blocks with nametable for name lookup via `next()`.
pub async fn new(
state: Arc<State>,
repository: Arc<RepositoryContext>,
parent_node_id: NodeID,
) -> Result<Self, StateError> {
if !parent_node_id.is_valid_or_root_node_id() {
return Ok(Self {
state,
repository,
parent_node_id,
current_node_id: None,
current_block: None,
current_iblock: 0,
cycle: SiblingCycleGuard::new(parent_node_id),
});
}
let parent = state.node(repository.clone(), parent_node_id).await?;
let first_child = parent.child();
let (block, iblock) = if let Some(child_id) = first_child {
let iblock = NodeBlock::index(child_id);
let block = state
.block_with_nametable(repository.clone(), iblock)
.await?;
(Some(block), iblock)
} else {
(None, 0)
};
Ok(Self {
state,
repository,
parent_node_id,
current_node_id: first_child,
current_block: block,
current_iblock: iblock,
cycle: SiblingCycleGuard::new(parent_node_id),
})
}
/// Get the next child node with its name.
///
/// The returned [`NodeNameLock`] holds a read lock on the node block. It is
/// `Send`, but drop it before any call that may take another lock (see the
/// type docs) — copy it out with [`NodeNameLock::freeze`] if needed.
pub async fn next(&mut self) -> Result<Option<(NodeID, Node, NodeNameLock)>, StateError> {
loop {
let Some(node_id) = self.current_node_id else {
return Ok(None);
};
let iblock = NodeBlock::index(node_id);
if iblock != self.current_iblock || self.current_block.is_none() {
self.current_iblock = iblock;
self.current_block = Some(
self.state
.block_with_nametable(self.repository.clone(), iblock)
.await?,
);
}
let block = self.current_block.as_ref().unwrap();
let node_index = Node::index(node_id);
let node = block.node(node_index);
node.walk_step(node_id, self.parent_node_id, &mut self.cycle)?;
self.current_node_id = node.sibling();
match block.node_name_ref(node_index) {
Ok(name) => return Ok(Some((node_id, node, name))),
Err(err) => {
lore_warn!("Skipping node {node_id} with invalid name: {err}");
}
}
}
}
}
/// Iterator over child nodes of a directory, loading blocks without nametable.
/// Yields `(NodeID, Node)` — the child's ID and node data, without the name string.
pub struct StateNodeChildrenIterator {
state: Arc<State>,
repository: Arc<RepositoryContext>,
parent_node_id: NodeID,
current_node_id: Option<NodeID>,
current_block: Option<Arc<NodeBlock>>,
current_iblock: usize,
cycle: SiblingCycleGuard,
}
impl StateNodeChildrenIterator {
/// Create a new iterator starting from the first child of the given parent node.
/// Loads blocks without nametable — use when only node data is needed.
pub async fn new(
state: Arc<State>,
repository: Arc<RepositoryContext>,
parent_node_id: NodeID,
) -> Result<Self, StateError> {
if !parent_node_id.is_valid_or_root_node_id() {
return Ok(Self {
state,
repository,
parent_node_id,
current_node_id: None,
current_block: None,
current_iblock: 0,
cycle: SiblingCycleGuard::new(parent_node_id),
});
}
let parent = state.node(repository.clone(), parent_node_id).await?;
let first_child = parent.child();
let (block, iblock) = if let Some(child_id) = first_child {
let iblock = NodeBlock::index(child_id);
let block = state.block(repository.clone(), iblock).await?;
(Some(block), iblock)
} else {
(None, 0)
};
Ok(Self {
state,
repository,
parent_node_id,
current_node_id: first_child,
current_block: block,
current_iblock: iblock,
cycle: SiblingCycleGuard::new(parent_node_id),
})
}
/// Get the next child node.
pub async fn next(&mut self) -> Result<Option<(NodeID, Node)>, StateError> {
let Some(node_id) = self.current_node_id else {
return Ok(None);
};
let iblock = NodeBlock::index(node_id);
if iblock != self.current_iblock || self.current_block.is_none() {
self.current_iblock = iblock;
self.current_block = Some(self.state.block(self.repository.clone(), iblock).await?);
}
let block = self.current_block.as_ref().unwrap();
let node_index = Node::index(node_id);
let node = block.node(node_index);
node.walk_step(node_id, self.parent_node_id, &mut self.cycle)?;
self.current_node_id = node.sibling();
Ok(Some((node_id, node)))
}
}
/// Revision state control structure, internally mutable through r/w locks
pub struct State {
/// Serialized data
data: parking_lot::RwLock<StateData>,
/// Runtime in memory data
runtime: parking_lot::RwLock<StateRuntime>,
/// Deserializing semaphore
deserialize: tokio::sync::Semaphore,
/// Unused node/block semaphore
unused: tokio::sync::Semaphore,
/// Block deserialization semaphore
block_deserialize: tokio::sync::Semaphore,
/// File metadata block deserialization semaphore
metadata_deserialize: tokio::sync::Semaphore,
}
impl std::fmt::Debug for State {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "State({})", self.runtime.read().signature)
}
}
/// Mutable store function for file timestamp
const FILE_MTIME: &str = "file-mtime";
/// Magic identifier
const STATE_MAGIC: u32 = 0xD37A208Eu32;
/// State format version identifiers
#[repr(u32)]
pub enum StateFormat {
/// Initial version
Initial = 1,
/// Node name hash is lower case
LowerCaseHash = 2,
}
#[repr(C)]
#[derive(Copy, Clone, Default, IntoBytes, FromBytes, Immutable)]
pub struct StateData {
/// Magic identifier
magic: u32,
/// Format version
format: u32,
/// State flags
flags: u32,
/// Reserved for future extensions
reserved_header: u32,
/// Reserved for future extensions
reserved_uint32: [u32; 2],
/// Revision number
pub revision_number: u64,
/// Parent state signatures
pub parent: [Hash; 2],
/// Immutable merkle tree fragment
hash_tree: Hash,
/// Immutable metadata fragment
hash_metadata: Hash,
/// Immutable link list
hash_link: Hash,
/// Link merge state (transient, local only — zeroed before commit)
hash_link_merge: Hash,
/// Reserved for future extensions
hash_reserved: Hash,
/// Parent repository in case of merge/integrate from other repository
parent_repository: RepositoryId,
/// Unused (for future extension)
reserved_buffer_first: [u8; 16],
/// Unused (for future extension)
reserved_buffer_second: [u8; 32],
}
#[repr(C)]
#[derive(Copy, Clone, Default, IntoBytes, FromBytes, Immutable)]
pub struct LinkReference {
/// Repository identifier
pub(crate) repository: RepositoryId,
/// Branch identifier
pub(crate) branch: BranchId,
/// Revision signature
pub(crate) signature: Hash,
/// Node containing the link
pub(crate) local_node: u32,
/// Flags
pub(crate) flags: u32,
/// Unused
pub(crate) unused: u32,
}
impl LinkReference {
pub fn resolve_branch(&self, parent_branch: BranchId) -> BranchId {
if self.branch.is_zero() {
parent_branch
} else {
self.branch
}
}
}
/// Tracks a single link's merge state for rollback.
#[repr(C)]
#[derive(Copy, Clone, Default, IntoBytes, FromBytes, Immutable)]
pub struct LinkMergeEntry {
/// Link path node ID (correlates with `LinkReference.local_node`)
pub local_node: u32,
/// Reserved for future use
pub reserved: u32,
/// Pre-merge (base) link reference snapshot for rollback
pub base: LinkReference,
}
/// Header for the serialized link merge state blob.
#[repr(C)]
#[derive(Copy, Clone, Default, IntoBytes, FromBytes, Immutable)]
pub struct LinkMergeState {
/// Number of `LinkMergeEntry` items following this header
pub count: u32,
/// Flags (reserved for future use)
pub flags: u32,
}
const MAX_BLOCK_CACHE: usize = 5000;
struct StateRuntime {
/// Signature state was deserialized from
signature: Hash,
/// Deserialized merkle tree data
tree: Option<Tree>,
/// Memory buffer holding all block addresses
block_address: Bytes,
/// Weak references to each block
block: Vec<Weak<NodeBlock>>,
/// Dirty blocks kept in memory
block_dirty: Vec<(Arc<NodeBlock>, usize)>,
/// Cached blocks kept in memory
block_cache: Vec<Arc<NodeBlock>>,
/// Cache counter
block_cache_counter: AtomicU64,
/// Memory buffer holding all file metadata block addresses
block_file_metadata_address: Bytes,
/// Weak references to each file metadata block
block_file_metadata: Vec<Weak<NodeFileMetadataBlock>>,
/// Dirty blocks kept in memory
block_file_metadata_dirty: Vec<(Arc<NodeFileMetadataBlock>, usize)>,
/// Link list
link_list: Option<Vec<LinkReference>>,
/// Name table (read only, for old data formats)
name_table_deprecated: Option<Arc<NameTable>>,
/// Rehash node names
rehash_node_names: bool,
}
impl StateRuntime {
pub fn new(signature: Hash, rehash_node_names: bool) -> Self {
StateRuntime {
signature,
tree: None,
block_address: Bytes::default(),
block: vec![],
block_dirty: vec![],
block_cache: vec![],
block_cache_counter: AtomicU64::new(0),
block_file_metadata_address: Bytes::default(),
block_file_metadata: vec![],
block_file_metadata_dirty: vec![],
link_list: None,
name_table_deprecated: None,
rehash_node_names,
}
}
}
impl Default for State {
fn default() -> Self {
Self::new()
}
}
impl State {
pub fn new() -> Self {
Self {
data: parking_lot::RwLock::new(StateData::new_zeroed()),
runtime: parking_lot::RwLock::new(StateRuntime::new(Hash::default(), false)),
unused: tokio::sync::Semaphore::new(1),
deserialize: tokio::sync::Semaphore::new(1),
block_deserialize: tokio::sync::Semaphore::new(1),
metadata_deserialize: tokio::sync::Semaphore::new(1),
}
}
/// Load the current state and branch.
pub async fn deserialize_current(
repository: Arc<RepositoryContext>,
) -> Result<(Arc<Self>, BranchId), StateError> {
let (current_revision, branch) = crate::instance::load_current_anchor(&repository)
.await
.internal("Failed to deserialize anchor")?;
Ok((
State::deserialize(repository.clone(), current_revision).await?,
branch,
))
}
/// Load current and optionally staged states, plus the current branch.
///
/// Returns `(current_state, staged_state, branch)` where `staged_state`
/// is `None` when nothing is staged.
pub async fn deserialize_current_and_staged(
repository: Arc<RepositoryContext>,
) -> Result<(Arc<Self>, Option<Arc<Self>>, BranchId), StateError> {
let (current_revision, branch) = crate::instance::load_current_anchor(&repository)
.await
.internal("Failed to deserialize anchor")?;
let state_current = State::deserialize(repository.clone(), current_revision).await?;
let state_staged = match crate::instance::load_staged_revision(&repository)
.await
.ok()
.flatten()
{
Some(staged_revision) if staged_revision != current_revision => {
Some(State::deserialize(repository.clone(), staged_revision).await?)
}
_ => None,
};
Ok((state_current, state_staged, branch))
}
pub async fn deserialize(
repository: Arc<RepositoryContext>,
signature: Hash,
) -> Result<Arc<Self>, StateError> {
if signature.is_zero() {
return Ok(Arc::new(State::new()));
}
let address = Address::zero_context_hash(signature);
let options = read_options_from_repository(&repository);
let mut data = match StateData::read_from_immutable(repository, address, options).await {
Ok(data) => data,
Err(ref e) if e.is_address_not_found() || e.is_payload_not_found() => {
return Err(NotFound.into());
}
Err(ImmutableError::SlowDown(traced)) => return Err(StateError::SlowDown(traced)),
Err(_err) => return Err(StateError::internal("Failed to read state data")),
};
if data.magic != STATE_MAGIC {
Err(StateError::internal("Corrupt header"))
} else if data.format == 0 || data.format > StateFormat::LowerCaseHash as u32 {
if data.format > StateFormat::LowerCaseHash as u32 && data.format < 0xFFF {
Err(StateError::internal(format!(
"Upgrade format: {}",
data.format
)))
} else {
Err(StateError::internal(format!(
"Invalid format: {}",
data.format
)))
}
} else {
// If old version, set rehash flag
let rehash_node_names = data.format < StateFormat::LowerCaseHash as u32;
// Clean flags
data.flags &= !StateFlags::Dirty;
Ok(Arc::new(State {
data: parking_lot::RwLock::new(data),
runtime: parking_lot::RwLock::new(StateRuntime::new(signature, rehash_node_names)),
unused: tokio::sync::Semaphore::new(1),
deserialize: tokio::sync::Semaphore::new(1),
block_deserialize: tokio::sync::Semaphore::new(1),
metadata_deserialize: tokio::sync::Semaphore::new(1),
}))
}
}
pub async fn serialize(
&self,
repository: Arc<RepositoryContext>,
_token: &RepositoryWriteToken,
) -> Result<Hash, StateError> {
let is_dirty = self.is_dirty();
if !is_dirty {
lore_trace!(
"State not dirtied, return previously serialized signature {}",
self.revision()
);
return Ok(self.revision());
}
if self.runtime.read().rehash_node_names {
// Deserialize all blocks to force update the node name hashes, as state format
// requires all blocks to have same format
lore_info!("Updating all state block name hashes");
let mut tasks = JoinSet::new();
let mut result = Ok(());
let static_self = unsafe { extend_lifetime(self) };
let block_count = self.block_count();
for block_index in 0..block_count {
let repository = repository.clone();
lore_spawn!(tasks, async move {
lore_trace!(" block {}/{}", block_index + 1, block_count);
let block = static_self.block(repository, block_index).await?;
{
block.write().mark_dirty();
}
static_self.block_modified(block, block_index);
Ok(())
});
if let Some(task_result) = tasks.try_join_next() {
match task_result {
Ok(inner_result) => {
if result.is_ok() {
result = inner_result;
}
}
Err(err) => {
result = Err(StateError::internal_with_context(err, "Task failure"));
}
}
}
}
while let Some(task_result) = tasks.join_next().await {
match task_result {
Ok(inner_result) => {
if result.is_ok() {
result = inner_result;
}
}
Err(err) => {
result = Err(StateError::internal_with_context(err, "Task failure"));
}
}
}
result?;
}
let (block_dirty, block_file_metadata_dirty) = {
let lock = self.runtime.read();
(
lock.block_dirty.clone(),
lock.block_file_metadata_dirty.clone(),
)
};
let mut tree = self.tree(repository.clone()).await?;
let block_count = tree.block_count as usize;
if !block_dirty.is_empty() {
lore_debug!("Serializing {} dirty blocks", block_dirty.len());
let mut tasks: JoinSet<Result<(Address, usize), StateError>> = JoinSet::new();
for (block, block_index) in block_dirty.iter() {
let block = block.clone();
let block_index = *block_index;
if block.read().raw().flags & NodeBlockFlags::FirstUnusedNode != 0 {
let block_unused_next = tree.block_unused_first;
tree.block_unused_first = block_index as u32;
block.write().node_block().block_unused_next = block_unused_next;
}
lore_trace!("Queue serialization of dirty node block {}", block_index);
let repository = repository.clone();
lore_spawn!(tasks, async move {
// TODO(mjansson): Figure out a way to write the node block without having to copy
// it out of the lock first. Writing from the locked ref will not work as the immutable
// write makes the lock held over an await point
lore_trace!("Serializing dirty node block {}", block_index);
let mut node_block = {
block.deserialize_nametable(repository.clone()).await?;
block.node_name_repack();
if block.is_nametable_deserialized() {
lore_trace!("Serializing dirty node block {} name table", block_index);
let name_table = block.read().clone_name_table();
let (name_table, _) = if !name_table.is_empty() {
immutable::write(
repository.clone(),
Context::default(),
name_table,
immutable::write_options_from_repository(repository.clone())
.with_local_cache_priority()
.with_max_size_chunk(),
)
.await
.internal("Failed to serialize node block")?
} else {
(Address::default(), Fragment::default())
};
{
let mut writer = block.write();
writer.node_block().name_table = name_table.hash;
}
}
block.read().node_block().clone_on_heap()
};
node_block.flags &= !NodeBlockFlags::Dirty;
node_block.flags &= !NodeBlockFlags::UpgradeGeneratedNametable;
node_block.flags &= !NodeBlockFlags::FirstUnusedNode;
let (address, _) = node_block
.write_to_immutable(
repository.clone(),
Context::default(),
immutable::write_options_from_repository(repository.clone())
.with_local_cache_priority()
.with_max_size_chunk(),
)
.await
.internal("Failed to serialize node block")?;
Ok((address, block_index))
});
}
let mut block_hash_bytes = {
let lock = self.runtime.read();
// Resize buffer with empty hashes if needed
lock.block_address
.clone_and_resize_zeroed::<Hash>(block_count)
};
{
let block_hash = block_hash_bytes.as_type_slice_mut();
let mut final_error = Ok(());
let mut task_error = Ok(());
while let Some(task) = tasks.join_next().await {
if let Ok(result) = task {
if let Ok((address, block_index)) = result {
block_hash[block_index] = address.hash;
} else {
final_error = Err(result.unwrap_err());
}
} else {
task_error = Err(StateError::internal_with_context(
task.unwrap_err(),
"Failed to serialize node block task",
));
}
}
final_error?;
task_error?;
}
// Write out the block address list
let block_hash_bytes = block_hash_bytes.freeze();
let (list_address, _) = immutable::write(
repository.clone(),
Context::default(),
block_hash_bytes.clone(),
immutable::write_options_from_repository(repository.clone())
.with_local_cache_priority()
.with_max_size_chunk(),
)
.await
.internal("Failed to serialize node block list")?;
// Update the tree node block list address
{
lore_trace!(
"Update tree node block list from {} to {}",
tree.hash_node,
list_address.hash
);
tree.hash_node = list_address.hash;
tree.flags |= TreeFlags::Dirty;
{
let mut lock = self.runtime.write();
lock.tree = Some(tree);
lock.block_address = block_hash_bytes;
}
}
}
if !block_file_metadata_dirty.is_empty() {
lore_trace!(
"Serializing {} dirty file metadata blocks",
block_file_metadata_dirty.len()
);
let mut tasks: JoinSet<Result<(Address, usize), StateError>> = JoinSet::new();
for (block, block_index) in block_file_metadata_dirty.iter() {
let block = block.clone();
let block_index = *block_index;
let repository = repository.clone();
lore_trace!(
"Queue serialization of dirty file metadata node block {}",
block_index
);
lore_spawn!(tasks, async move {
lore_trace!("Serializing dirty file metadata node block {}", block_index);
// TODO(mjansson): Figure out a way to write the node block without having to copy
// it out of the lock first. Writing from the locked ref will not work as the immutable
// write makes the lock held of an await point
let mut node_block = { *block.read().node_block() };
node_block.flags &= !NodeBlockFlags::Dirty;
let (address, _) = node_block
.write_to_immutable(
repository.clone(),
Context::default(),
immutable::write_options_from_repository(repository.clone())
.with_local_cache_priority()
.with_max_size_chunk(),
)
.await
.internal("Failed to serialize file metadata block")?;
Ok((address, block_index))
});
}
let mut block_hash_bytes = {
let lock = self.runtime.read();
// Resize buffer with empty hashes if needed
lock.block_file_metadata_address
.clone_and_resize_zeroed::<Hash>(block_count)
};
{
let block_hash = block_hash_bytes.as_type_slice_mut();
let mut final_error = Ok(());
let mut task_error = Ok(());
while let Some(task) = tasks.join_next().await {
if let Ok(result) = task {
if let Ok((address, block_index)) = result {
block_hash[block_index] = address.hash;
} else {
final_error = Err(result.unwrap_err());
}
} else {
task_error = Err(StateError::internal_with_context(
task.unwrap_err(),
"Failed to serialize file metadata block task",
));
}
}
final_error?;
task_error?;
}
// Write out the block address list
let block_hash_bytes = block_hash_bytes.freeze();
let (list_address, _) = immutable::write(
repository.clone(),
Context::default(),
block_hash_bytes.clone(),
immutable::write_options_from_repository(repository.clone())
.with_local_cache_priority()
.with_max_size_chunk(),
)
.await
.internal("Failed to serialize file metadata block list")?;
// Update the tree file metadata node block list address
{
lore_trace!(
"Update tree file metadata node block list from {} to {}",
tree.hash_file_metadata,
list_address.hash
);
tree.hash_file_metadata = list_address.hash;
tree.flags |= TreeFlags::Dirty;
{
let mut lock = self.runtime.write();
lock.tree = Some(tree);
lock.block_file_metadata_address = block_hash_bytes;
}
}
}
let link_list = { self.runtime.read().link_list.clone() };
if let Some(link_list) = link_list {
let list_hash = hash::hash_slice(link_list.as_bytes());
if list_hash != self.data.read().hash_link {
let rehashed_list = if link_list.is_empty() {
lore_debug!("Link list empty, write default hash");
Hash::default()
} else {
let bytes = Bytes::copy_from_slice(link_list.as_bytes());
let (address, _fragment) = immutable::write(
repository.clone(),
Context::default(),
bytes,
immutable::write_options_from_repository(repository.clone())
.with_local_cache_priority()
.with_max_size_chunk(),
)
.await
.internal("Failed to serialize link list")?;
address.hash
};
lore_debug!("Serialized link list to {rehashed_list}");
let mut data = self.data.write();
data.hash_link = rehashed_list;
data.flags |= StateFlags::Dirty;
}
}
// Serialize the immutable tree
let tree = { self.runtime.read().tree.unwrap_or_default() };
if tree.flags & TreeFlags::Dirty != 0 {
lore_trace!("Serializing dirty tree");
let (address, _fragment) = tree
.write_to_immutable(
repository.clone(),
Context::default(),
immutable::write_options_from_repository(repository.clone())
.with_local_cache_priority()
.with_max_size_chunk(),
)
.await
.internal("Failed to serialize tree")?;
{
lore_trace!("Serialized tree to {}", address.hash);
lore_trace!(" node block {}", tree.hash_node);
lore_trace!(" file metadata block {}", tree.hash_file_metadata);
let mut data = self.data.write();
data.hash_tree = address.hash;
data.flags |= StateFlags::Dirty;
}
}
// Serialize the state
let (address, fragment) = {
let buffer = {
let mut data = self.data.write();
data.flags &= !StateFlags::Dirty;
data.format = StateFormat::LowerCaseHash as u32;
data.magic = STATE_MAGIC;
Bytes::copy_from_slice(data.as_bytes())
};
immutable::write(
repository.clone(),
Context::default(),
buffer,
immutable::write_options_from_repository(repository.clone())
.with_revision_state()
.with_local_cache_priority()
.with_max_size_chunk(),
)
.await
.internal("Failed to serialize state")?
};
{
let mut runtime = self.runtime.write();
runtime.signature = address.hash;
}
lore_trace!(
"Serialized state to {} in repository {}, {} -> {} bytes",
address.hash,
repository.id,
fragment.size_content,
fragment.size_payload
);
Ok(address.hash)
}