summaryrefslogtreecommitdiff
path: root/src/other_tools/root_maps/content_git_map.cpp
blob: 652f4a25cf34e61996110c3380405adbdfea3e3d (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
// Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "src/other_tools/root_maps/content_git_map.hpp"

#include "fmt/core.h"
#include "src/buildtool/file_system/file_root.hpp"
#include "src/buildtool/file_system/file_storage.hpp"
#include "src/buildtool/file_system/symlinks_map/pragma_special.hpp"
#include "src/buildtool/multithreading/async_map_utils.hpp"
#include "src/buildtool/multithreading/task_system.hpp"
#include "src/buildtool/storage/fs_utils.hpp"
#include "src/other_tools/root_maps/root_utils.hpp"
#include "src/other_tools/utils/content.hpp"
#include "src/utils/archive/archive_ops.hpp"

namespace {

/// \brief Extracts the archive of given type into the destination directory
/// provided. Returns nullopt on success, or error string on failure.
[[nodiscard]] auto ExtractArchive(std::filesystem::path const& archive,
                                  std::string const& repo_type,
                                  std::filesystem::path const& dst_dir) noexcept
    -> std::optional<std::string> {
    if (repo_type == "archive") {
        return ArchiveOps::ExtractArchive(
            ArchiveType::TarAuto, archive, dst_dir);
    }
    if (repo_type == "zip") {
        return ArchiveOps::ExtractArchive(
            ArchiveType::ZipAuto, archive, dst_dir);
    }
    return "unrecognized repository type";
}

/// \brief Helper function for ensuring the serve endpoint, if given, has the
/// root if it was marked absent.
/// It guarantees the logger is called exactly once with fatal on failure, and
/// the setter on success.
void EnsureRootAsAbsent(
    std::string const& tree_id,
    ArchiveRepoInfo const& key,
    ServeApi const* serve,
    gsl::not_null<StorageConfig const*> const& storage_config,
    IExecutionApi const* remote_api,
    bool is_cache_hit,
    ContentGitMap::SetterPtr const& ws_setter,
    ContentGitMap::LoggerPtr const& logger) {
    // this is an absent root
    if (serve != nullptr) {
        // check if the serve endpoint has this root
        auto has_tree = CheckServeHasAbsentRoot(*serve, tree_id, logger);
        if (not has_tree) {
            return;
        }
        if (not *has_tree) {
            // try to see if serve endpoint has the information to prepare the
            // root itself; this is redundant if root is not already cached
            if (is_cache_hit) {
                auto serve_result =
                    serve->RetrieveTreeFromArchive(key.archive.content,
                                                   key.repo_type,
                                                   key.subdir,
                                                   key.pragma_special,
                                                   /*sync_tree=*/false);
                if (serve_result) {
                    // if serve has set up the tree, it must match what we
                    // expect
                    auto const& served_tree_id = *serve_result;
                    if (tree_id != served_tree_id) {
                        (*logger)(fmt::format("Mismatch in served root tree "
                                              "id:\nexpected {}, but got {}",
                                              tree_id,
                                              served_tree_id),
                                  /*fatal=*/true);
                        return;
                    }
                }
                else {
                    // check if serve failure was due to archive content not
                    // being found or it is otherwise fatal
                    if (serve_result.error() == GitLookupError::Fatal) {
                        (*logger)(
                            fmt::format("Serve endpoint failed to set up "
                                        "root from known archive content {}",
                                        key.archive.content),
                            /*fatal=*/true);
                        return;
                    }
                    if (remote_api == nullptr) {
                        (*logger)(
                            fmt::format(
                                "Missing or incompatible remote-execution "
                                "endpoint needed to sync workspace root {} "
                                "with the serve endpoint.",
                                tree_id),
                            /*fatal=*/true);
                        return;
                    }
                    // the tree is known locally, so we can upload it to remote
                    // CAS for the serve endpoint to retrieve it and set up the
                    // root
                    if (not EnsureAbsentRootOnServe(
                            *serve,
                            tree_id,
                            storage_config->GitRoot(),
                            remote_api,
                            logger,
                            /*no_sync_is_fatal=*/true)) {
                        return;
                    }
                }
            }
            else {
                // the tree is known locally, so we can upload it to remote CAS
                // for the serve endpoint to retrieve it and set up the root
                if (remote_api == nullptr) {
                    (*logger)(
                        fmt::format("Missing or incompatible remote-execution "
                                    "endpoint needed to sync workspace root {} "
                                    "with the serve endpoint.",
                                    tree_id),
                        /*fatal=*/true);
                    return;
                }
                // the tree is known locally, so we can upload it to remote
                // CAS for the serve endpoint to retrieve it and set up the
                // root
                if (not EnsureAbsentRootOnServe(*serve,
                                                tree_id,
                                                storage_config->GitRoot(),
                                                remote_api,
                                                logger,
                                                /*no_sync_is_fatal=*/true)) {
                    return;
                }
            }
        }
    }
    else {
        // give warning
        (*logger)(fmt::format("Workspace root {} marked absent but no suitable "
                              "serve endpoint provided.",
                              tree_id),
                  /*fatal=*/false);
    }
    // set root as absent
    (*ws_setter)(
        std::pair(nlohmann::json::array({FileRoot::kGitTreeMarker, tree_id}),
                  /*is_cache_hit=*/is_cache_hit));
}

/// \brief Called to get the resolved root (with respect to symlinks) from
/// an unresolved tree. It guarantees the logger is called exactly once with
/// fatal on failure, and the setter on success.
void ResolveContentTree(
    ArchiveRepoInfo const& key,
    std::string const& tree_hash,
    GitCASPtr const& just_git_cas,
    bool is_cache_hit,
    bool is_absent,
    ServeApi const* serve,
    gsl::not_null<StorageConfig const*> const& storage_config,
    IExecutionApi const* remote_api,
    gsl::not_null<CriticalGitOpMap*> const& critical_git_op_map,
    gsl::not_null<ResolveSymlinksMap*> const& resolve_symlinks_map,
    gsl::not_null<TaskSystem*> const& ts,
    ContentGitMap::SetterPtr const& ws_setter,
    ContentGitMap::LoggerPtr const& logger) {
    if (key.pragma_special) {
        // get the resolved tree
        auto tree_id_file = StorageUtils::GetResolvedTreeIDFile(
            *storage_config, tree_hash, *key.pragma_special);
        if (FileSystemManager::Exists(tree_id_file)) {
            // read resolved tree id
            auto resolved_tree_id = FileSystemManager::ReadFile(tree_id_file);
            if (not resolved_tree_id) {
                (*logger)(fmt::format("Failed to read resolved tree id "
                                      "from file {}",
                                      tree_id_file.string()),
                          /*fatal=*/true);
                return;
            }
            // set the workspace root
            if (is_absent) {
                EnsureRootAsAbsent(*resolved_tree_id,
                                   key,
                                   serve,
                                   storage_config,
                                   remote_api,
                                   is_cache_hit,
                                   ws_setter,
                                   logger);
            }
            else {
                (*ws_setter)(std::pair(
                    nlohmann::json::array({FileRoot::kGitTreeMarker,
                                           *resolved_tree_id,
                                           storage_config->GitRoot().string()}),
                    /*is_cache_hit=*/is_cache_hit));
            }
        }
        else {
            // resolve tree; both source and target repos are the Git cache
            resolve_symlinks_map->ConsumeAfterKeysReady(
                ts,
                {GitObjectToResolve(tree_hash,
                                    ".",
                                    *key.pragma_special,
                                    /*known_info=*/std::nullopt,
                                    just_git_cas,
                                    just_git_cas)},
                [resolve_symlinks_map,
                 critical_git_op_map,
                 tree_hash,
                 tree_id_file,
                 is_cache_hit,
                 key,
                 is_absent,
                 serve,
                 storage_config,
                 remote_api,
                 ts,
                 ws_setter,
                 logger](auto const& hashes) {
                    if (not hashes[0]) {
                        // check for cycles
                        if (auto error = DetectAndReportCycle(
                                fmt::format("resolving Git tree {}", tree_hash),
                                *resolve_symlinks_map,
                                kGitObjectToResolvePrinter)) {
                            (*logger)(fmt::format("Failed to resolve symlinks "
                                                  "in tree {}:\n{}",
                                                  tree_hash,
                                                  *error),
                                      /*fatal=*/true);
                            return;
                        }
                        (*logger)(fmt::format("Unknown error in resolving "
                                              "symlinks in tree {}",
                                              tree_hash),
                                  /*fatal=*/true);
                        return;
                    }
                    auto const& resolved_tree_id = hashes[0]->id;
                    // keep tree alive in Git cache via a tagged commit
                    GitOpKey op_key = {
                        .params =
                            {
                                storage_config->GitRoot(),    // target_path
                                resolved_tree_id,             // git_hash
                                "",                           // branch
                                "Keep referenced tree alive"  // message
                            },
                        .op_type = GitOpType::KEEP_TREE};
                    critical_git_op_map->ConsumeAfterKeysReady(
                        ts,
                        {std::move(op_key)},
                        [resolved_tree_id,
                         key,
                         tree_id_file,
                         is_absent,
                         serve,
                         storage_config,
                         remote_api,
                         is_cache_hit,
                         ws_setter,
                         logger](auto const& values) {
                            GitOpValue op_result = *values[0];
                            // check flag
                            if (not op_result.result) {
                                (*logger)("Keep tree failed",
                                          /*fatal=*/true);
                                return;
                            }
                            // cache the resolved tree in the CAS map
                            if (not StorageUtils::WriteTreeIDFile(
                                    tree_id_file, resolved_tree_id)) {
                                (*logger)(
                                    fmt::format("Failed to write resolved tree "
                                                "id to file {}",
                                                tree_id_file.string()),
                                    /*fatal=*/true);
                                return;
                            }
                            // set the workspace root
                            if (is_absent) {
                                EnsureRootAsAbsent(resolved_tree_id,
                                                   key,
                                                   serve,
                                                   storage_config,
                                                   remote_api,
                                                   is_cache_hit,
                                                   ws_setter,
                                                   logger);
                            }
                            else {
                                (*ws_setter)(std::pair(
                                    nlohmann::json::array(
                                        {FileRoot::kGitTreeMarker,
                                         resolved_tree_id,
                                         storage_config->GitRoot().string()}),
                                    /*is_cache_hit=*/is_cache_hit));
                            }
                        },
                        [logger, target_path = storage_config->GitRoot()](
                            auto const& msg, bool fatal) {
                            (*logger)(
                                fmt::format("While running critical Git op "
                                            "KEEP_TREE for target {}:\n{}",
                                            target_path.string(),
                                            msg),
                                fatal);
                        });
                },
                [logger, content = key.archive.content](auto const& msg,
                                                        bool fatal) {
                    (*logger)(fmt::format("While resolving symlinks for "
                                          "content {}:\n{}",
                                          content,
                                          msg),
                              fatal);
                });
        }
    }
    else {
        // set the workspace root as-is
        if (is_absent) {
            EnsureRootAsAbsent(tree_hash,
                               key,
                               serve,
                               storage_config,
                               remote_api,
                               is_cache_hit,
                               ws_setter,
                               logger);
        }
        else {
            (*ws_setter)(std::pair(
                nlohmann::json::array({FileRoot::kGitTreeMarker,
                                       tree_hash,
                                       storage_config->GitRoot().string()}),
                /*is_cache_hit=*/is_cache_hit));
        }
    }
}

/// \brief Called to store the file association and then set the root.
/// It guarantees the logger is called exactly once with fatal on failure,
/// and the setter on success.
void WriteIdFileAndSetWSRoot(
    ArchiveRepoInfo const& key,
    std::string const& archive_tree_id,
    GitCASPtr const& just_git_cas,
    std::filesystem::path const& archive_tree_id_file,
    bool is_absent,
    ServeApi const* serve,
    gsl::not_null<StorageConfig const*> const& storage_config,
    IExecutionApi const* remote_api,
    gsl::not_null<CriticalGitOpMap*> const& critical_git_op_map,
    gsl::not_null<ResolveSymlinksMap*> const& resolve_symlinks_map,
    gsl::not_null<TaskSystem*> const& ts,
    ContentGitMap::SetterPtr const& setter,
    ContentGitMap::LoggerPtr const& logger) {
    // write to tree id file
    if (not StorageUtils::WriteTreeIDFile(archive_tree_id_file,
                                          archive_tree_id)) {
        (*logger)(fmt::format("Failed to write tree id to file {}",
                              archive_tree_id_file.string()),
                  /*fatal=*/true);
        return;
    }
    // we look for subtree in Git cache
    auto just_git_repo = GitRepoRemote::Open(just_git_cas);
    if (not just_git_repo) {
        (*logger)("Could not open Git cache repository!",
                  /*fatal=*/true);
        return;
    }
    // setup wrapped logger
    auto wrapped_logger = std::make_shared<AsyncMapConsumerLogger>(
        [&logger, subdir = key.subdir, tree = archive_tree_id](auto const& msg,
                                                               bool fatal) {
            (*logger)(fmt::format("While getting subdir {} from tree {}:\n{}",
                                  subdir,
                                  tree,
                                  msg),
                      fatal);
        });
    // get subtree id
    auto subtree_hash = just_git_repo->GetSubtreeFromTree(
        archive_tree_id, key.subdir, wrapped_logger);
    if (not subtree_hash) {
        return;
    }
    // resolve tree and set workspace root
    ResolveContentTree(key,
                       *subtree_hash,
                       just_git_cas,
                       false, /*is_cache_hit*/
                       is_absent,
                       serve,
                       storage_config,
                       remote_api,
                       critical_git_op_map,
                       resolve_symlinks_map,
                       ts,
                       setter,
                       logger);
}

/// \brief Called when archive is in local CAS. Performs the import-to-git
/// and follow-up processing. It guarantees the logger is called exactly
/// once with fatal on failure, and the setter on success.
void ExtractAndImportToGit(
    ArchiveRepoInfo const& key,
    std::filesystem::path const& content_cas_path,
    std::filesystem::path const& archive_tree_id_file,
    bool is_absent,
    ServeApi const* serve,
    gsl::not_null<StorageConfig const*> const& storage_config,
    IExecutionApi const* remote_api,
    gsl::not_null<CriticalGitOpMap*> const& critical_git_op_map,
    gsl::not_null<ImportToGitMap*> const& import_to_git_map,
    gsl::not_null<ResolveSymlinksMap*> const& resolve_symlinks_map,
    gsl::not_null<TaskSystem*> const& ts,
    ContentGitMap::SetterPtr const& setter,
    ContentGitMap::LoggerPtr const& logger) {
    // extract archive
    auto tmp_dir = storage_config->CreateTypedTmpDir(key.repo_type);
    if (not tmp_dir) {
        (*logger)(fmt::format("Failed to create tmp path for {} target {}",
                              key.repo_type,
                              key.archive.content),
                  /*fatal=*/true);
        return;
    }
    auto res =
        ExtractArchive(content_cas_path, key.repo_type, tmp_dir->GetPath());
    if (res != std::nullopt) {
        (*logger)(fmt::format("Failed to extract archive {} from CAS with "
                              "error:\n{}",
                              content_cas_path.string(),
                              *res),
                  /*fatal=*/true);
        return;
    }
    // import to git
    CommitInfo c_info{tmp_dir->GetPath(), key.repo_type, key.archive.content};
    import_to_git_map->ConsumeAfterKeysReady(
        ts,
        {std::move(c_info)},
        [tmp_dir,  // keep tmp_dir alive
         archive_tree_id_file,
         key,
         is_absent,
         serve,
         storage_config,
         remote_api,
         critical_git_op_map,
         resolve_symlinks_map,
         ts,
         setter,
         logger](auto const& values) {
            // check for errors
            if (not values[0]->second) {
                (*logger)("Importing to git failed",
                          /*fatal=*/true);
                return;
            }
            // only tree id is needed
            std::string archive_tree_id = values[0]->first;
            // write to id file and process subdir tree
            WriteIdFileAndSetWSRoot(key,
                                    archive_tree_id,
                                    values[0]->second, /*just_git_cas*/
                                    archive_tree_id_file,
                                    is_absent,
                                    serve,
                                    storage_config,
                                    remote_api,
                                    critical_git_op_map,
                                    resolve_symlinks_map,
                                    ts,
                                    setter,
                                    logger);
        },
        [logger, target_path = tmp_dir->GetPath()](auto const& msg,
                                                   bool fatal) {
            (*logger)(fmt::format("While importing target {} to Git:\n{}",
                                  target_path.string(),
                                  msg),
                      fatal);
        });
}

auto IdFileExistsInOlderGeneration(
    gsl::not_null<StorageConfig const*> const& storage_config,
    ArchiveRepoInfo const& key) -> std::optional<std::size_t> {
    for (std::size_t generation = 1;
         generation < storage_config->num_generations;
         generation++) {
        auto archive_tree_id_file = StorageUtils::GetArchiveTreeIDFile(
            *storage_config, key.repo_type, key.archive.content, generation);
        if (FileSystemManager::Exists(archive_tree_id_file)) {
            return generation;
        }
    }
    return std::nullopt;
}

void HandleLocallyKnownTree(
    ArchiveRepoInfo const& key,
    std::filesystem::path const& archive_tree_id_file,
    bool fetch_absent,
    ServeApi const* serve,
    gsl::not_null<StorageConfig const*> const& storage_config,
    gsl::not_null<ResolveSymlinksMap*> const& resolve_symlinks_map,
    gsl::not_null<CriticalGitOpMap*> const& critical_git_op_map,
    IExecutionApi const* remote_api,
    gsl::not_null<TaskSystem*> const& ts,
    ContentGitMap::SetterPtr const& setter,
    ContentGitMap::LoggerPtr const& logger) {
    // read archive_tree_id from file tree_id_file
    auto archive_tree_id = FileSystemManager::ReadFile(archive_tree_id_file);
    if (not archive_tree_id) {
        (*logger)(fmt::format("Failed to read tree id from file {}",
                              archive_tree_id_file.string()),
                  /*fatal=*/true);
        return;
    }
    // ensure Git cache
    // define Git operation to be done
    GitOpKey op_key = {.params =
                           {
                               storage_config->GitRoot(),  // target_path
                               "",                         // git_hash
                               "",                         // branch
                               std::nullopt,               // message
                               true                        // init_bare
                           },
                       .op_type = GitOpType::ENSURE_INIT};
    critical_git_op_map->ConsumeAfterKeysReady(
        ts,
        {std::move(op_key)},
        [archive_tree_id = *archive_tree_id,
         key,
         fetch_absent,
         serve,
         storage_config,
         remote_api,
         critical_git_op_map,
         resolve_symlinks_map,
         ts,
         setter,
         logger](auto const& values) {
            GitOpValue op_result = *values[0];
            // check flag
            if (not op_result.result) {
                (*logger)("Git init failed",
                          /*fatal=*/true);
                return;
            }
            // open fake repo wrap for GitCAS
            auto just_git_repo = GitRepoRemote::Open(op_result.git_cas);
            if (not just_git_repo) {
                (*logger)("Could not open Git cache repository!",
                          /*fatal=*/true);
                return;
            }
            // setup wrapped logger
            auto wrapped_logger = std::make_shared<AsyncMapConsumerLogger>(
                [&logger](auto const& msg, bool fatal) {
                    (*logger)(fmt::format("While getting subtree from "
                                          "tree:\n{}",
                                          msg),
                              fatal);
                });
            // get subtree id
            auto subtree_hash = just_git_repo->GetSubtreeFromTree(
                archive_tree_id, key.subdir, wrapped_logger);
            if (not subtree_hash) {
                return;
            }
            // resolve tree and set workspace root (present or absent)
            ResolveContentTree(
                key,
                *subtree_hash,
                op_result.git_cas,
                /*is_cache_hit = */ true,
                /*is_absent = */ (key.absent and not fetch_absent),
                serve,
                storage_config,
                remote_api,
                critical_git_op_map,
                resolve_symlinks_map,
                ts,
                setter,
                logger);
        },
        [logger, target_path = storage_config->GitRoot()](auto const& msg,
                                                          bool fatal) {
            (*logger)(fmt::format("While running critical Git "
                                  "op ENSURE_INIT for "
                                  "target {}:\n{}",
                                  target_path.string(),
                                  msg),
                      fatal);
        });
}

void HandleKnownInOlderGenerationAfterImport(
    ArchiveRepoInfo const& key,
    const std::string& tree_id,
    bool fetch_absent,
    ServeApi const* serve,
    gsl::not_null<StorageConfig const*> const& storage_config,
    gsl::not_null<ResolveSymlinksMap*> const& resolve_symlinks_map,
    gsl::not_null<CriticalGitOpMap*> const& critical_git_op_map,
    IExecutionApi const* remote_api,
    gsl::not_null<TaskSystem*> const& ts,
    ContentGitMap::SetterPtr const& setter,
    ContentGitMap::LoggerPtr const& logger) {
    // Now that we have the tree persisted in the git repository of the youngest
    // generation; hence we can write the map-entry.
    auto archive_tree_id_file = StorageUtils::GetArchiveTreeIDFile(
        *storage_config, key.repo_type, key.archive.content);
    if (not StorageUtils::WriteTreeIDFile(archive_tree_id_file, tree_id)) {
        (*logger)(fmt::format("Failed to write tree id to file {}",
                              archive_tree_id_file.string()),
                  /*fatal=*/true);
    }
    // Now that we also have the the ID-file written, we're in the situation
    // as if we had a cache hit in the first place.
    HandleLocallyKnownTree(key,
                           archive_tree_id_file,
                           fetch_absent,
                           serve,
                           storage_config,
                           resolve_symlinks_map,
                           critical_git_op_map,
                           remote_api,
                           ts,
                           setter,
                           logger);
}

void HandleKnownInOlderGenerationAfterTaggingAndInit(
    ArchiveRepoInfo const& key,
    std::string tree_id,
    std::string tag,
    GitCASPtr const& git_cas,
    std::filesystem::path const& source,
    bool fetch_absent,
    ServeApi const* serve,
    gsl::not_null<StorageConfig const*> const& storage_config,
    gsl::not_null<Storage const*> const& storage,
    gsl::not_null<ResolveSymlinksMap*> const& resolve_symlinks_map,
    gsl::not_null<CriticalGitOpMap*> const& critical_git_op_map,
    IExecutionApi const* remote_api,
    gsl::not_null<TaskSystem*> const& ts,
    ContentGitMap::SetterPtr const& setter,
    ContentGitMap::LoggerPtr const& logger) {
    auto git_repo = GitRepoRemote::Open(git_cas);
    if (not git_repo) {
        (*logger)("Could not open just initialized repository {}",
                  /*fatal=*/true);
        return;
    }
    auto fetch_logger = std::make_shared<AsyncMapConsumerLogger>(
        [logger, tag, source](auto const& msg, bool fatal) {
            (*logger)(fmt::format("While fetching {} from {}:\n{}",
                                  tag,
                                  source.string(),
                                  msg),
                      fatal);
        });
    if (not git_repo->LocalFetchViaTmpRepo(
            *storage_config, source, tag, fetch_logger)) {
        return;
    }
    GitOpKey op_key = {.params =
                           {
                               storage_config->GitRoot(),    // target_path
                               tree_id,                      // git_hash
                               "",                           // branch
                               "Keep referenced tree alive"  // message
                           },
                       .op_type = GitOpType::KEEP_TREE};
    critical_git_op_map->ConsumeAfterKeysReady(
        ts,
        {std::move(op_key)},
        [key,
         tree_id,
         git_cas,
         fetch_absent,
         serve,
         storage_config,
         storage,
         resolve_symlinks_map,
         critical_git_op_map,
         remote_api,
         ts,
         setter,
         logger](auto const& values) {
            GitOpValue op_result = *values[0];
            // check flag
            if (not op_result.result) {
                (*logger)("Keep tag failed",
                          /*fatal=*/true);
                return;
            }
            HandleKnownInOlderGenerationAfterImport(key,
                                                    tree_id,
                                                    fetch_absent,
                                                    serve,
                                                    storage_config,
                                                    resolve_symlinks_map,
                                                    critical_git_op_map,
                                                    remote_api,
                                                    ts,
                                                    setter,
                                                    logger);
        },
        [logger, tree_id](auto const& msg, bool fatal) {
            (*logger)(
                fmt::format(
                    "While tagging to keep tree {} alive:\n{}", tree_id, msg),
                fatal);
        });
}

void HandleKnownInOlderGenerationAfterTagging(
    ArchiveRepoInfo const& key,
    const std::string& tree_id,
    const std::string& tag,
    std::filesystem::path const& source,
    bool fetch_absent,
    ServeApi const* serve,
    gsl::not_null<StorageConfig const*> const& storage_config,
    gsl::not_null<Storage const*> const& storage,
    gsl::not_null<ResolveSymlinksMap*> const& resolve_symlinks_map,
    gsl::not_null<CriticalGitOpMap*> const& critical_git_op_map,
    IExecutionApi const* remote_api,
    gsl::not_null<TaskSystem*> const& ts,
    ContentGitMap::SetterPtr const& setter,
    ContentGitMap::LoggerPtr const& logger) {
    GitOpKey op_key = {.params =
                           {
                               storage_config->GitRoot(),  // target_path
                               "",                         // git_hash
                               "",                         // branch
                               std::nullopt,               // message
                               true                        // init_bare
                           },
                       .op_type = GitOpType::ENSURE_INIT};
    critical_git_op_map->ConsumeAfterKeysReady(
        ts,
        {std::move(op_key)},
        [key,
         tree_id,
         tag,
         source,
         fetch_absent,
         serve,
         storage_config,
         storage,
         resolve_symlinks_map,
         critical_git_op_map,
         remote_api,
         ts,
         setter,
         logger](auto const& values) {
            GitOpValue op_result = *values[0];
            if (not op_result.result) {
                (*logger)("Git init failed",
                          /*fatal=*/true);
                return;
            }
            HandleKnownInOlderGenerationAfterTaggingAndInit(
                key,
                tree_id,
                tag,
                op_result.git_cas,
                source,
                fetch_absent,
                serve,
                storage_config,
                storage,
                resolve_symlinks_map,
                critical_git_op_map,
                remote_api,
                ts,
                setter,
                logger);
        },
        [logger, target_path = storage_config->GitRoot()](auto const& msg,
                                                          bool fatal) {
            (*logger)(fmt::format("While running critical Git op "
                                  "ENSURE_INIT for target {}:\n{}",
                                  target_path.string(),
                                  msg),
                      fatal);
        });
}

void HandleKnownInOlderGeneration(
    ArchiveRepoInfo const& key,
    std::size_t generation,
    bool fetch_absent,
    ServeApi const* serve,
    gsl::not_null<StorageConfig const*> const& storage_config,
    gsl::not_null<Storage const*> const& storage,
    gsl::not_null<ResolveSymlinksMap*> const& resolve_symlinks_map,
    gsl::not_null<CriticalGitOpMap*> const& critical_git_op_map,
    IExecutionApi const* remote_api,
    gsl::not_null<TaskSystem*> const& ts,
    ContentGitMap::SetterPtr const& setter,
    ContentGitMap::LoggerPtr const& logger) {
    auto archive_tree_id_file = StorageUtils::GetArchiveTreeIDFile(
        *storage_config, key.repo_type, key.archive.content, generation);
    auto archive_tree_id = FileSystemManager::ReadFile(archive_tree_id_file);
    if (not archive_tree_id) {
        (*logger)(fmt::format("Failed to read tree id from file {}",
                              archive_tree_id_file.string()),
                  /*fatal=*/true);
        return;
    }
    auto source = storage_config->GitGenerationRoot(generation);

    GitOpKey op_key = {.params =
                           {
                               source,                    // target_path
                               *archive_tree_id,          // git_hash
                               "",                        // branch
                               "Tag commit for fetching"  // message
                           },
                       .op_type = GitOpType::KEEP_TREE};
    critical_git_op_map->ConsumeAfterKeysReady(
        ts,
        {std::move(op_key)},
        [key,
         tree_id = *archive_tree_id,
         source,
         fetch_absent,
         serve,
         storage_config,
         storage,
         resolve_symlinks_map,
         critical_git_op_map,
         remote_api,
         ts,
         setter,
         logger](auto const& values) {
            GitOpValue op_result = *values[0];
            if (not op_result.result) {
                (*logger)("Keep tag failed", /*fatal=*/true);
                return;
            }
            auto tag = *op_result.result;
            HandleKnownInOlderGenerationAfterTagging(key,
                                                     tree_id,
                                                     tag,
                                                     source,
                                                     fetch_absent,
                                                     serve,
                                                     storage_config,
                                                     storage,
                                                     resolve_symlinks_map,
                                                     critical_git_op_map,
                                                     remote_api,
                                                     ts,
                                                     setter,
                                                     logger);
        },
        [logger, source, hash = *archive_tree_id](auto const& msg, bool fatal) {
            (*logger)(
                fmt::format("While tagging tree {} in {} for fetching:\n{}",
                            source.string(),
                            hash,
                            msg),
                fatal);
        });
}

}  // namespace

auto CreateContentGitMap(
    gsl::not_null<ContentCASMap*> const& content_cas_map,
    gsl::not_null<ImportToGitMap*> const& import_to_git_map,
    LocalPathsPtr const& just_mr_paths,
    MirrorsPtr const& additional_mirrors,
    CAInfoPtr const& ca_info,
    gsl::not_null<ResolveSymlinksMap*> const& resolve_symlinks_map,
    gsl::not_null<CriticalGitOpMap*> const& critical_git_op_map,
    ServeApi const* serve,
    gsl::not_null<StorageConfig const*> const& storage_config,
    gsl::not_null<Storage const*> const& storage,
    IExecutionApi const* remote_api,
    bool fetch_absent,
    gsl::not_null<JustMRProgress*> const& progress,
    std::size_t jobs) -> ContentGitMap {
    auto gitify_content = [content_cas_map,
                           import_to_git_map,
                           resolve_symlinks_map,
                           critical_git_op_map,
                           just_mr_paths,
                           additional_mirrors,
                           ca_info,
                           serve,
                           storage,
                           storage_config,
                           remote_api,
                           fetch_absent,
                           progress](auto ts,
                                     auto setter,
                                     auto logger,
                                     auto /* unused */,
                                     auto const& key) {
        auto archive_tree_id_file = StorageUtils::GetArchiveTreeIDFile(
            *storage_config, key.repo_type, key.archive.content);
        if (FileSystemManager::Exists(archive_tree_id_file)) {
            HandleLocallyKnownTree(key,
                                   archive_tree_id_file,
                                   fetch_absent,
                                   serve,
                                   storage_config,
                                   resolve_symlinks_map,
                                   critical_git_op_map,
                                   remote_api,
                                   ts,
                                   setter,
                                   logger);
        }
        else if (auto generation =
                     IdFileExistsInOlderGeneration(storage_config, key)) {
            HandleKnownInOlderGeneration(key,
                                         *generation,
                                         fetch_absent,
                                         serve,
                                         storage_config,
                                         storage,
                                         resolve_symlinks_map,
                                         critical_git_op_map,
                                         remote_api,
                                         ts,
                                         setter,
                                         logger);
        }
        else {
            // separate logic between absent and present roots
            if (key.absent and not fetch_absent) {
                // request the resolved subdir tree from the serve endpoint, if
                // given
                if (serve != nullptr) {
                    auto serve_result =
                        serve->RetrieveTreeFromArchive(key.archive.content,
                                                       key.repo_type,
                                                       key.subdir,
                                                       key.pragma_special,
                                                       /*sync_tree = */ false);
                    if (serve_result) {
                        // set the workspace root as absent
                        progress->TaskTracker().Stop(key.archive.origin);
                        (*setter)(std::pair(
                            nlohmann::json::array(
                                {FileRoot::kGitTreeMarker, *serve_result}),
                            /*is_cache_hit = */ false));
                        return;
                    }
                    // check if serve failure was due to archive content
                    // not being found or it is otherwise fatal
                    if (serve_result.error() == GitLookupError::Fatal) {
                        (*logger)(
                            fmt::format("Serve endpoint failed to set up root "
                                        "from known archive content {}",
                                        key.archive.content),
                            /*fatal=*/true);
                        return;
                    }
                }
                // if serve endpoint cannot set up the root, we might still be
                // able to set up the absent root with local information, and if
                // a serve endpoint exists we can upload it the root ourselves;

                // check if content already in CAS
                auto const& cas = storage->CAS();
                auto digest = ArtifactDigest(key.archive.content, 0, false);
                if (auto content_cas_path =
                        cas.BlobPath(digest, /*is_executable=*/false)) {
                    ExtractAndImportToGit(key,
                                          *content_cas_path,
                                          archive_tree_id_file,
                                          /*is_absent = */ true,
                                          serve,
                                          storage_config,
                                          remote_api,
                                          critical_git_op_map,
                                          import_to_git_map,
                                          resolve_symlinks_map,
                                          ts,
                                          setter,
                                          logger);
                    // done
                    return;
                }

                // check if content is in Git cache;
                // ensure Git cache
                GitOpKey op_key = {
                    .params =
                        {
                            storage_config->GitRoot(),  // target_path
                            "",                         // git_hash
                            "",                         // branch
                            std::nullopt,               // message
                            true                        // init_bare
                        },
                    .op_type = GitOpType::ENSURE_INIT};
                critical_git_op_map->ConsumeAfterKeysReady(
                    ts,
                    {std::move(op_key)},
                    [key,
                     digest,
                     archive_tree_id_file,
                     critical_git_op_map,
                     import_to_git_map,
                     resolve_symlinks_map,
                     just_mr_paths,
                     additional_mirrors,
                     ca_info,
                     serve,
                     storage,
                     storage_config,
                     remote_api,
                     progress,
                     ts,
                     setter,
                     logger](auto const& values) {
                        GitOpValue op_result = *values[0];
                        // check flag
                        if (not op_result.result) {
                            (*logger)("Git init failed",
                                      /*fatal=*/true);
                            return;
                        }
                        auto const just_git_cas = op_result.git_cas;
                        // open fake repo wrap for GitCAS
                        auto just_git_repo = GitRepoRemote::Open(just_git_cas);
                        if (not just_git_repo) {
                            (*logger)("Could not open Git cache repository!",
                                      /*fatal=*/true);
                            return;
                        }
                        // verify if local Git knows content blob
                        auto wrapped_logger =
                            std::make_shared<AsyncMapConsumerLogger>(
                                [&logger, blob = key.archive.content](
                                    auto const& msg, bool fatal) {
                                    (*logger)(
                                        fmt::format("While verifying presence "
                                                    "of blob {}:\n{}",
                                                    blob,
                                                    msg),
                                        fatal);
                                });
                        auto res = just_git_repo->TryReadBlob(
                            key.archive.content, wrapped_logger);
                        if (not res.first) {
                            // blob check failed
                            return;
                        }
                        auto const& cas = storage->CAS();
                        if (res.second) {
                            // blob found; add it to CAS
                            if (not cas.StoreBlob(*res.second,
                                                  /*is_executable=*/false)) {
                                (*logger)(fmt::format("Failed to store content "
                                                      "{} to local CAS",
                                                      key.archive.content),
                                          /*fatal=*/true);
                                return;
                            }
                            if (auto content_cas_path = cas.BlobPath(
                                    digest, /*is_executable=*/false)) {
                                ExtractAndImportToGit(key,
                                                      *content_cas_path,
                                                      archive_tree_id_file,
                                                      /*is_absent=*/true,
                                                      serve,
                                                      storage_config,
                                                      remote_api,
                                                      critical_git_op_map,
                                                      import_to_git_map,
                                                      resolve_symlinks_map,
                                                      ts,
                                                      setter,
                                                      logger);
                                // done
                                return;
                            }
                            // this should normally never be reached unless
                            // something went really wrong
                            (*logger)(fmt::format("Failed to retrieve blob {} "
                                                  "from local CAS",
                                                  digest.hash()),
                                      /*fatal=*/true);
                            return;
                        }
                        progress->TaskTracker().Start(key.archive.origin);
                        // add distfile to CAS
                        auto repo_distfile =
                            (key.archive.distfile
                                 ? key.archive.distfile.value()
                                 : std::filesystem::path(key.archive.fetch_url)
                                       .filename()
                                       .string());
                        StorageUtils::AddDistfileToCAS(
                            *storage, repo_distfile, just_mr_paths);
                        // check if content is in CAS now
                        if (auto content_cas_path =
                                cas.BlobPath(digest, /*is_executable=*/false)) {
                            progress->TaskTracker().Stop(key.archive.origin);
                            ExtractAndImportToGit(key,
                                                  *content_cas_path,
                                                  archive_tree_id_file,
                                                  /*is_absent=*/true,
                                                  serve,
                                                  storage_config,
                                                  remote_api,
                                                  critical_git_op_map,
                                                  import_to_git_map,
                                                  resolve_symlinks_map,
                                                  ts,
                                                  setter,
                                                  logger);
                            // done
                            return;
                        }
                        // report not being able to set up this root as absent
                        (*logger)(fmt::format("Cannot create workspace root as "
                                              "absent for content {}.",
                                              key.archive.content),
                                  /*fatal=*/true);
                    },
                    [logger, target_path = storage_config->GitRoot()](
                        auto const& msg, bool fatal) {
                        (*logger)(fmt::format("While running critical Git op "
                                              "ENSURE_INIT for target {}:\n{}",
                                              target_path.string(),
                                              msg),
                                  fatal);
                    });
            }
            else {
                // for a present root we need the archive to be present too
                content_cas_map->ConsumeAfterKeysReady(
                    ts,
                    {key.archive},
                    [archive_tree_id_file,
                     key,
                     storage,
                     storage_config,
                     critical_git_op_map,
                     import_to_git_map,
                     resolve_symlinks_map,
                     ts,
                     setter,
                     logger]([[maybe_unused]] auto const& values) {
                        // content is in local CAS now
                        auto const& cas = storage->CAS();
                        auto content_cas_path =
                            cas.BlobPath(ArtifactDigest(
                                             key.archive.content, 0, false),
                                         /*is_executable=*/false)
                                .value();
                        // root can only be present, so default all arguments
                        // that refer to a serve endpoint
                        ExtractAndImportToGit(key,
                                              content_cas_path,
                                              archive_tree_id_file,
                                              /*is_absent=*/false,
                                              /*serve=*/nullptr,
                                              storage_config,
                                              /*remote_api=*/nullptr,
                                              critical_git_op_map,
                                              import_to_git_map,
                                              resolve_symlinks_map,
                                              ts,
                                              setter,
                                              logger);
                    },
                    [logger, content = key.archive.content](auto const& msg,
                                                            bool fatal) {
                        (*logger)(fmt::format("While ensuring content {} is in "
                                              "CAS:\n{}",
                                              content,
                                              msg),
                                  fatal);
                    });
            }
        }
    };
    return AsyncMapConsumer<ArchiveRepoInfo, std::pair<nlohmann::json, bool>>(
        gitify_content, jobs);
}