Repository navigation
Expand file tree
/
Copy pathcsv_host.cpp
More file actions
1709 lines (1617 loc) · 80.4 KB
/
Copy pathcsv_host.cpp
File metadata and controls
1709 lines (1617 loc) · 80.4 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
#include "csv_host.h"
#include "photo_studio.h"
#include "windowless_runtime.h"
#include "codec_record.bindings.h"
#include "codec_mapped.bindings.h"
#include "csv_contract.host.h"
#include "exporters/export_contract.host.h"
#include "services/import_status.bindings.h"
#include <huxerui/pluginkit.h>
#include <nlohmann/json.hpp>
#include <algorithm>
#include <array>
#include <atomic>
#include <charconv>
#include <condition_variable>
#include <cstring>
#include <random>
#include <iomanip>
#include <fstream>
#include <iostream>
#include <limits>
#include <mutex>
#include <sstream>
#include <thread>
#include <type_traits>
#if defined(_WIN32)
#include <process.h>
#include <windows.h>
#else
#include <csignal>
#include <unistd.h>
#endif
namespace {
namespace fs = std::filesystem;
using Json = nlohmann::json;
using huxerui::File;
using huxerui::AsyncInputStream;
using huxerui::AsyncOutputStream;
using huxerui::IoResult;
using huxerui::AwaitCallback;
using huxerui::Delay;
using huxerui::Task;
using huxerui::UseApplicationTaskScope;
using namespace huxerui::pluginkit;
using huxerui::pluginkit::detail::WindowlessRoot;
using huxerui::pluginkit::detail::WindowlessRuntime;
static_assert(!std::is_copy_constructible_v<PluginManager>);
static_assert(!std::is_copy_assignable_v<PluginManager>);
using csv_import::Exporters;
using csv_import::Importers;
constexpr char CommandHelp[] =
"inspect <package>, install <package> <digest> <in_process|worker_process> [status], list, "
"upgrade <package> <installed-digest> <approved-digest> [status], uninstall <id> <digest> [delete-data], "
"settings <id> [locale], set-settings <id> <revision> <overrides-file>, "
"enable <id>, disable <id>, status, import <file> [plugin-id] [timeout-ms], "
"round-trip <csv-file> <ssv-file> <plugin-id>, convert <sync|async> <ssv-file> <csv-file> <plugin-id> [chunk-kib], "
"convert-pair <sync|async> <first-input> <first-output> <second-input> <second-output> <plugin-id>, quit";
void CheckContractCodecs() {
using namespace csv_import::codec_check;
using huxerui::Bytes;
using huxerui::pluginkit::Contract;
using huxerui::pluginkit::detail::Decode;
using huxerui::pluginkit::detail::Encode;
static_assert(Contract<RecordColumns>::Info.id == Contract<ReorderedColumns>::Info.id);
static_assert(Contract<RecordColumns>::Info.fingerprint != Contract<ReorderedColumns>::Info.fingerprint);
const ColumnCounts counts{ColumnCount{19}};
const auto record = Encode<RecordColumns>(counts);
const auto mapped = Encode<MappedColumns>(counts);
// The same nested value is a CBOR record in one contract and a scalar in the other.
if (record != Bytes{std::byte{0x81}, std::byte{0x81}, std::byte{0x81}, std::byte{19}} ||
mapped != Bytes{std::byte{0x81}, std::byte{0x81}, std::byte{19}} ||
Decode<ColumnCounts, RecordColumns>(record).at(0).value().value != 19 ||
Decode<ColumnCounts, MappedColumns>(mapped).at(0).value().value != 19) {
throw Error(ErrorCode::PluginFailed, "The generated contracts did not retain their wire representations");
}
constexpr double scale = 1.25;
if (Decode<double, MappedColumns>(Encode<MappedColumns>(scale)) != scale) {
throw Error(ErrorCode::PluginFailed, "The explicit scalar mapping did not round-trip");
}
}
void RegisterPoints(PluginManager& manager) {
manager.RegisterExtensionPoint(Importers);
manager.RegisterExtensionPoint(Exporters);
}
std::uint32_t ProcessId() {
#if defined(_WIN32)
return static_cast<std::uint32_t>(::_getpid());
#else
return static_cast<std::uint32_t>(::getpid());
#endif
}
class PreviewImportStatus final : public csv_import::ImportStatus {
public:
explicit PreviewImportStatus(PluginManager& manager) : manager_(manager) {}
std::uint32_t ImportedRows() const override { return rows.value_or(0); }
Task<bool> SetImportedRows(csv_import::SetImportedRowsRequest request) override {
co_await Delay(std::chrono::milliseconds::zero());
if (std::this_thread::get_id() != owner_) {
throw Error(ErrorCode::PluginFailed, "Import status must be updated on the preview thread");
}
if (manager_.ListPlugins().empty() || manager_.ListExtensions(Importers).empty()) {
throw Error(ErrorCode::PluginFailed, "The host callback could not read the plugin catalog");
}
if (request.rows == UINT32_MAX) co_await manager_.SetEnabled("example.csv-faults", false);
rows = request.rows;
co_return true;
}
std::optional<std::uint32_t> rows;
private:
PluginManager& manager_;
const std::thread::id owner_ = std::this_thread::get_id();
};
class PreviewProgress final : public csv_import::ImportProgress {
public:
Task<void> OnRows(std::uint32_t count, std::uint64_t) override {
const auto value = co_await huxerui::RunWorker([](std::uint32_t rows) { return rows; }, count);
if (std::this_thread::get_id() != owner_) {
throw Error(ErrorCode::PluginFailed, "Import progress must be handled on the preview thread");
}
rows = value;
}
std::optional<std::uint32_t> rows;
private:
const std::thread::id owner_ = std::this_thread::get_id();
};
struct ProgressGate {
std::optional<huxerui::CallbackCompletion<std::uint32_t>> complete;
bool started = false;
bool cancelled = false;
std::uint32_t rows = 0;
};
class HeldProgress final : public csv_import::ImportProgress {
public:
explicit HeldProgress(std::shared_ptr<ProgressGate> gate) : gate_(std::move(gate)) {}
Task<void> OnRows(std::uint32_t, std::uint64_t) override {
gate_->rows = co_await AwaitCallback<std::uint32_t>([gate = gate_](auto resolve) {
gate->complete = std::move(resolve);
gate->started = true;
return [gate] { gate->cancelled = true; };
});
}
private:
std::shared_ptr<ProgressGate> gate_;
};
template<class Predicate>
Task<void> WaitFor(Predicate ready) {
const auto deadline = std::chrono::steady_clock::now() + DefaultTimeout;
while (!ready()) {
if (std::chrono::steady_clock::now() >= deadline) throw Error(ErrorCode::PluginFailed, "CSV fixture timed out");
co_await Delay(std::chrono::milliseconds(1));
}
}
struct CallOutcome {
bool done = false;
std::exception_ptr error;
};
PluginEventSubscription RecordPluginEvents(PluginManager& manager, std::string_view plugin,
std::vector<PluginEvent>& events) {
return manager.SubscribeEvents([id = std::string(plugin), &events](const PluginEvent& event) {
if (event.package.id == id) events.push_back(event);
});
}
template<class T>
Task<void> ObserveCall(Task<T> call, std::shared_ptr<CallOutcome> outcome) {
try {
(void)co_await std::move(call);
} catch (...) {
outcome->error = std::current_exception();
}
outcome->done = true;
}
std::string Utf8(const fs::path& path) {
const auto text = path.u8string();
return {text.begin(), text.end()};
}
template<class T>
T RequireIo(huxerui::IoResult<T> result) {
if (!result.Succeeded()) throw Error(ErrorCode::Io, result.Error().message);
return std::move(result).Value();
}
huxerui::AsyncInputStream StringInput(std::string text) {
return huxerui::AsyncInputStream::FromReader(
[text = std::move(text), offset = std::size_t{}](std::stop_token, std::size_t count) mutable
-> Task<huxerui::IoResult<huxerui::Bytes>> {
const auto chunk = std::string_view(text).substr(offset, count);
offset += chunk.size();
huxerui::Bytes bytes(chunk.size());
if (!chunk.empty()) std::memcpy(bytes.data(), chunk.data(), chunk.size());
co_return huxerui::IoResult<huxerui::Bytes>(std::move(bytes));
});
}
class ConversionProgress final : public csv_import::ImportProgress {
public:
Task<void> OnRows(std::uint32_t count, std::uint64_t bytes) override {
rows = count;
input_bytes = bytes;
before_eof = before_eof || !eof;
co_return;
}
std::uint32_t rows = 0;
std::uint64_t input_bytes = 0;
bool before_eof = false;
bool eof = false;
};
// Keep the staging directory alive through the last SDK or PluginKit I/O lease.
struct StagedOutput {
File directory;
File file;
explicit StagedOutput(File dir) : directory(std::move(dir)), file(directory.Child("output.csv")) {}
~StagedOutput() {
(void)file.Delete();
(void)directory.Delete();
}
};
std::shared_ptr<StagedOutput> StageOutput(const File& destination) {
std::random_device random;
const auto parent = destination.Parent().value_or(File("."));
for (unsigned attempt = 0; attempt < 8; ++attempt) {
auto directory = parent.Child(".csv-export-" + std::to_string(random()) + "-" + std::to_string(random()));
std::error_code error;
const auto path = directory.Path();
if (fs::create_directory(fs::path(std::u8string(path.begin(), path.end())), error)) {
return std::make_shared<StagedOutput>(std::move(directory));
}
if (error && error != std::errc::file_exists) {
throw Error(ErrorCode::Io, "Cannot create a staging directory for the CSV output");
}
}
throw Error(ErrorCode::Io, "Cannot create a staging directory for the CSV output");
}
struct StagedWriter {
// The SDK stream must be released before its staging directory.
std::shared_ptr<StagedOutput> stage;
huxerui::OutputStream output;
};
huxerui::OutputStream OpenStaged(const std::shared_ptr<StagedOutput>& stage) {
const auto writer = std::make_shared<StagedWriter>(StagedWriter{stage, RequireIo(stage->file.OpenWrite())});
return huxerui::OutputStream::FromWriter(
[writer](std::span<const std::byte> bytes) { return writer->output.Write(bytes); },
[writer] { return writer->output.Close(); });
}
AsyncOutputStream OpenStagedAsync(const std::shared_ptr<StagedOutput>& stage, std::string_view fault) {
const auto writer = std::make_shared<StagedWriter>(StagedWriter{stage, RequireIo(stage->file.OpenWrite())});
return AsyncOutputStream::FromWriter(
[writer, fail = fault == "write"](std::stop_token, huxerui::Bytes bytes) -> Task<IoResult<void>> {
auto result = co_await huxerui::RunWorker([writer, bytes = std::move(bytes)] { return writer->output.Write(bytes); });
if (fail && result.Succeeded()) co_return IoResult<void>::Failure({huxerui::IoErrorCode::NoSpace, "Fixture write error"});
co_return result;
},
[writer, fail = fault == "close"](std::stop_token) -> Task<IoResult<void>> {
if (fail) co_return IoResult<void>::Failure({huxerui::IoErrorCode::Io, "Fixture close error"});
co_return co_await huxerui::RunWorker([writer] { return writer->output.Close(); });
});
}
Json DescribeSettingText(const SettingText& text) {
if (const auto resource = std::get_if<huxerui::StringResource>(&text)) return {{"resource", resource->ToString()}};
return std::get<std::string>(text);
}
Json DescribeSettingValue(const SettingValue& value) {
return std::visit([](const auto& item) -> Json { return item; }, value);
}
Json DescribeSettingsSchema(const std::vector<SettingDefinition>& schema) {
constexpr std::array<std::string_view, 4> types{"boolean", "integer", "string", "enum"};
auto described = Json::array();
for (const auto& setting : schema) {
Json entry{{"key", setting.key}, {"type", types.at(static_cast<std::size_t>(setting.type))},
{"title", DescribeSettingText(setting.title)}, {"default", DescribeSettingValue(setting.default_value)}};
if (setting.description) entry["description"] = DescribeSettingText(*setting.description);
if (setting.minimum) entry["minimum"] = *setting.minimum;
if (setting.maximum) entry["maximum"] = *setting.maximum;
if (!setting.options.empty()) {
auto options = Json::array();
for (const auto& choice : setting.options) {
options.push_back({{"value", choice.value}, {"title", DescribeSettingText(choice.title)}});
}
entry["options"] = std::move(options);
}
described.push_back(std::move(entry));
}
return described;
}
Json DescribeSettings(const SettingsSnapshot& settings) {
const auto values = [](const SettingValues& source) {
auto result = Json::object();
for (const auto& [key, value] : source) result[key] = DescribeSettingValue(value);
return result;
};
return {{"schema", DescribeSettingsSchema(settings.schema)}, {"effective", values(settings.effective)},
{"overrides", values(settings.overrides)}, {"revision", settings.revision},
{"active_revision", settings.active_revision ? Json(*settings.active_revision) : Json(nullptr)}};
}
SettingValues ReadSettingEdits(const File& file) try {
const auto overrides = Json::parse(RequireIo(file.ReadString()));
if (!overrides.is_object()) throw Error(ErrorCode::InvalidArgument, "Setting overrides must be a JSON object");
SettingValues result;
for (const auto& [key, value] : overrides.items()) {
if (value.is_boolean()) result.emplace(key, value.get<bool>());
else if (value.is_string()) result.emplace(key, value.get<std::string>());
else if (value.is_number_integer() && (!value.is_number_unsigned() ||
value.get<std::uint64_t>() <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))) {
result.emplace(key, value.get<std::int64_t>());
} else {
throw Error(ErrorCode::InvalidArgument, "Expected a boolean, signed 64-bit integer, or string at " + key);
}
}
return result;
} catch (const Json::exception& error) {
throw Error(ErrorCode::InvalidArgument, "Cannot parse setting overrides: " + std::string(error.what()));
}
Json Describe(const PackageInfo& package) {
auto extensions = Json::array();
for (const auto& extension : package.extensions) {
auto entry = Json{{"point", extension.Point()}};
if (extension.metadata_json) entry["metadata"] = Json::parse(*extension.metadata_json);
extensions.push_back(std::move(entry));
}
return {{"id", package.id}, {"version", package.version}, {"digest", package.digest},
{"extensions", std::move(extensions)}, {"settings_schema", DescribeSettingsSchema(package.settings_schema)}};
}
Json List(PluginManager& manager) {
auto plugins = Json::array();
for (const auto& plugin : manager.ListPlugins()) {
auto record = Describe(plugin.package);
record["enabled"] = plugin.enabled;
record["mode"] = plugin.mode == ExecutionMode::InProcess ? "in_process" : "worker_process";
record["worker_pid"] = plugin.worker_pid ? Json(*plugin.worker_pid) : Json(nullptr);
record["pending_upgrade"] = plugin.pending_upgrade ? Describe(*plugin.pending_upgrade) : Json(nullptr);
plugins.push_back(std::move(record));
}
const auto describe = [&manager](auto point) {
auto result = Json::array();
for (const auto& extension : manager.ListExtensions(point)) {
auto entry = Json{{"plugin", extension.PluginId()}};
if (extension.metadata_json) entry["metadata"] = Json::parse(*extension.metadata_json);
result.push_back(std::move(entry));
}
return result;
};
return {{"plugins", std::move(plugins)}, {"importers", describe(Importers)}, {"exporters", describe(Exporters)}};
}
char LowercaseAscii(char character) {
if (character >= 'A' && character <= 'Z') return static_cast<char>(character - 'A' + 'a');
return character;
}
bool MatchesSuffix(const ExtensionInfo& candidate, std::string_view suffix) {
if (suffix.empty() || !candidate.metadata_json) return false;
const auto metadata = Json::parse(*candidate.metadata_json);
const auto extensions = metadata.find("extensions");
if (extensions == metadata.end() || !extensions->is_array() || extensions->size() > 32) return false;
// A malformed suffix list makes the candidate ineligible for file-based selection.
bool matches = false;
for (const auto& item : *extensions) {
const auto* value = item.get_ptr<const std::string*>();
if (!value || value->size() < 2 || !value->starts_with('.') ||
value->find_first_of("/\\") != std::string::npos || value->find('\0') != std::string::npos) return false;
if (std::ranges::equal(*value, suffix, {}, LowercaseAscii, LowercaseAscii)) matches = true;
}
return matches;
}
Task<Json> Import(PluginManager& manager, const std::vector<std::string>& args) {
const File path(args[1]);
const auto suffix = path.Extension();
std::optional<ExtensionInfo> selected;
for (const auto& extension : manager.ListExtensions(Importers)) {
if (args.size() >= 3 && extension.PluginId() != args[2]) continue;
if (!MatchesSuffix(extension, suffix)) continue;
if (selected) throw Error(ErrorCode::Ambiguous, "Several importers match this file");
selected = extension;
}
if (!selected) throw Error(ErrorCode::NotFound, "No enabled importer matches the file");
auto timeout = DefaultTimeout;
if (args.size() == 4) {
std::uint32_t milliseconds = 0;
const auto end = args[3].data() + args[3].size();
const auto result = std::from_chars(args[3].data(), end, milliseconds);
if (result.ec != std::errc{} || result.ptr != end || milliseconds == 0 ||
std::chrono::milliseconds(milliseconds) > std::chrono::hours(24)) {
throw Error(ErrorCode::InvalidArgument, "Invalid timeout in milliseconds");
}
timeout = std::chrono::milliseconds(milliseconds);
}
const auto info = RequireIo(path.Stat());
if (info.size > csv_import::MaxImportBytes) {
throw Error(ErrorCode::PayloadTooLarge, "CSV input exceeds the example limit");
}
auto input = RequireIo(co_await path.OpenReadAsync());
auto importer = manager.CreateExtension(Importers, *selected, timeout);
auto progress = std::make_shared<PreviewProgress>();
const auto delimiter = importer->Delimiter();
const auto plugin_pid = importer->ProcessId();
auto imported = co_await importer->Import(std::move(input), progress);
auto issues = Json::array();
for (const auto& issue : imported.issues) {
issues.push_back({{"code", issue.code}, {"row", issue.row}, {"column", issue.column}, {"message", issue.message}});
}
Json table = nullptr;
if (imported.table) table = {{"header", imported.table->header}, {"rows", imported.table->rows}};
co_return Json{{"table", std::move(table)}, {"issues", std::move(issues)}, {"delimiter", delimiter},
{"plugin_pid", plugin_pid},
{"progress_rows", progress->rows ? Json(*progress->rows) : Json(nullptr)}};
}
Task<Json> RoundTrip(PluginManager& manager, const std::vector<std::string>& args) {
const auto& plugin = args[3];
const auto all_importers = manager.CreateExtensions(Importers).size();
auto importers = manager.CreateExtensions(Importers, plugin);
if (importers.size() != 2 || importers[0]->Delimiter() != "," || importers[1]->Delimiter() != ";") {
throw Error(ErrorCode::PluginFailed, "Expected comma and semicolon importers in manifest order");
}
try {
(void)manager.CreateExtension(Importers, plugin);
throw Error(ErrorCode::PluginFailed, "A plugin ID unexpectedly selected one of several factories");
} catch (const Error& error) {
if (error.Code() != ErrorCode::Ambiguous) throw;
}
const auto candidates = manager.ListExtensions(Importers);
const auto candidate = std::ranges::find_if(candidates, [&](const auto& entry) {
return entry.PluginId() == plugin && MatchesSuffix(entry, ".ssv");
});
if (candidate == candidates.end()) throw Error(ErrorCode::NotFound, "No semicolon importer for this package");
auto exporter = manager.CreateExtension(Exporters, plugin);
const auto pid = importers[0]->ProcessId();
if (importers[1]->ProcessId() != pid || exporter->ProcessId() != pid) {
throw Error(ErrorCode::PluginFailed, "Factories from the same package must share a process");
}
const auto parse = [](auto& importer, huxerui::AsyncInputStream input) -> Task<csv_import::Table> {
auto result = co_await importer->Import(std::move(input), nullptr);
if (!result.table) throw Error(ErrorCode::PluginFailed, "Cannot parse the round-trip input");
co_return std::move(*result.table);
};
const auto table = co_await parse(importers[0], RequireIo(co_await File(args[1]).OpenReadAsync()));
{
auto semicolon = manager.CreateExtension(Importers, *candidate);
if (semicolon->Delimiter() != ";" || semicolon->ProcessId() != pid) {
throw Error(ErrorCode::PluginFailed, "The candidate did not select the semicolon importer");
}
const auto other = co_await parse(semicolon, RequireIo(co_await File(args[2]).OpenReadAsync()));
if (table.header != other.header || table.rows != other.rows) {
throw Error(ErrorCode::PluginFailed, "CSV and semicolon input did not produce the same table");
}
}
const csv_import::ExportRequest request{table.header, table.rows};
std::string exported;
auto output = huxerui::AsyncOutputStream::FromWriter(
[&exported](std::stop_token, huxerui::Bytes bytes) -> Task<huxerui::IoResult<void>> {
exported.append(reinterpret_cast<const char*>(bytes.data()), bytes.size());
co_return huxerui::IoResult<void>::Success();
});
co_await exporter->Export(request, std::move(output));
const auto round_trip = co_await parse(importers[0], StringInput(exported));
if (table.header != round_trip.header || table.rows != round_trip.rows) {
throw Error(ErrorCode::PluginFailed, "The exported CSV did not preserve the input table");
}
co_return Json{{"all_importers", all_importers}, {"package_importers", importers.size()},
{"format", exporter->Format()}, {"plugin_pid", pid}, {"csv", std::move(exported)}};
}
Task<Json> Convert(PluginManager& manager, const std::vector<std::string>& args) {
const bool synchronous = args[1] == "sync";
if (!synchronous && args[1] != "async") throw Error(ErrorCode::InvalidArgument, "Expected sync or async conversion");
const File source(args[2]), destination(args[3]);
auto exporter = manager.CreateExtension(Exporters, args[4], std::chrono::seconds(30));
const auto fault = args.front() == "check-output-failure" ? std::string_view(args[5]) : std::string_view{};
csv_import::ConversionOptions options;
if (args.front() == "convert" && args.size() == 6) {
std::uint32_t kib = 0;
const auto& value = args[5];
const auto end = value.data() + value.size();
const auto result = std::from_chars(value.data(), end, kib);
if (result.ec != std::errc{} || result.ptr != end || !kib || kib > HPK_MAX_STREAM_CHUNK / 1024) {
throw Error(ErrorCode::InvalidArgument, "Expected a chunk size between 1 and 1024 KiB");
}
options.read_bytes = kib * 1024;
}
const auto pid = exporter->ProcessId();
auto stage = StageOutput(destination);
csv_import::CsvSummary summary{};
auto progress = std::make_shared<ConversionProgress>();
if (synchronous) {
auto input = RequireIo(source.OpenRead());
auto output = OpenStaged(stage);
summary = exporter->Convert(options, std::move(input), std::move(output));
} else {
auto original = std::make_shared<AsyncInputStream>(RequireIo(co_await source.OpenReadAsync()));
auto input = AsyncInputStream::FromReader(
[original, progress](std::stop_token, std::size_t count) -> Task<IoResult<huxerui::Bytes>> {
auto result = co_await original->ReadAsync(count);
if (result.Succeeded()) progress->eof = result.Value().empty();
co_return result;
});
auto output = OpenStagedAsync(stage, fault);
summary = co_await exporter->ConvertAsync(options, std::move(input), std::move(output), progress);
}
if (!(co_await stage->file.MoveToAsync(destination, true))) {
throw Error(ErrorCode::Io, "Cannot publish CSV output");
}
co_return Json{{"rows", summary.rows}, {"input_bytes", summary.input_bytes}, {"output_bytes", summary.output_bytes},
{"plugin_pid", pid}, {"progress_before_eof", progress->before_eof}, {"progress_rows", progress->rows}};
}
Task<Json> ConvertPair(PluginManager& manager, const std::vector<std::string>& args) {
const bool synchronous = args[1] == "sync";
if (!synchronous && args[1] != "async") throw Error(ErrorCode::InvalidArgument, "Expected sync or async conversion");
const File first_source(args[2]), first_destination(args[3]), second_source(args[4]), second_destination(args[5]);
const auto option = args.size() == 8 ? std::string_view(args[7]) : std::string_view{};
auto exporter = manager.CreateExtension(Exporters, args[6], std::chrono::seconds(30));
auto first_stage = StageOutput(first_destination);
auto second_stage = StageOutput(second_destination);
constexpr std::uint32_t read_bytes = 512 * 1024;
auto first_progress = !synchronous && option != "omit-first" ? std::make_shared<ConversionProgress>() : nullptr;
auto second_progress = !synchronous && option != "omit-second" ? std::make_shared<ConversionProgress>() : nullptr;
const auto pid = exporter->ProcessId();
std::optional<csv_import::PairSummary> summary;
if (synchronous) {
auto first = RequireIo(first_source.OpenRead());
auto second = RequireIo(second_source.OpenRead());
summary.emplace(exporter->ConvertPair(std::move(first), csv_import::Separator(";"), OpenStaged(first_stage),
read_bytes, OpenStaged(second_stage), std::move(second)));
} else {
auto first = RequireIo(co_await first_source.OpenReadAsync());
auto second = RequireIo(co_await second_source.OpenReadAsync());
const auto fault = option == "write-second" ? std::string_view("write") : std::string_view{};
summary.emplace(co_await exporter->ConvertPairAsync(
std::move(first), csv_import::Separator(";"), first_progress, OpenStagedAsync(first_stage, {}), read_bytes,
OpenStagedAsync(second_stage, fault), second_progress, std::move(second)));
}
// Both staged outputs have closed successfully before the host begins either publication.
if (!(co_await first_stage->file.MoveToAsync(first_destination, true)) ||
!(co_await second_stage->file.MoveToAsync(second_destination, true))) {
throw Error(ErrorCode::Io, "Cannot publish CSV output");
}
const auto counts = [](const csv_import::CsvSummary& converted, const std::shared_ptr<ConversionProgress>& progress) {
return Json{{"rows", converted.rows}, {"input_bytes", converted.input_bytes}, {"output_bytes", converted.output_bytes},
{"progress_rows", progress ? Json(progress->rows) : Json(nullptr)},
{"progress_bytes", progress ? Json(progress->input_bytes) : Json(nullptr)}};
};
co_return Json{{"first", counts(summary->first, first_progress)}, {"second", counts(summary->second, second_progress)},
{"separator", summary->separator.Text()}, {"plugin_pid", pid}};
}
struct HeldStreamOperation {
template<class T>
Task<IoResult<T>> Hold(std::stop_token token) {
std::stop_callback on_stop(token, [this] { stop_requested = true; });
co_return co_await AwaitCallback<IoResult<T>>([this](auto reply) {
late = [reply] { reply.Fail(std::make_exception_ptr(std::runtime_error("Late stream completion"))); };
started = true;
return [this] { cancelled = true; };
});
}
std::function<void()> late;
bool started = false;
bool cancelled = false;
bool stop_requested = false;
};
Task<Json> CheckStreamInterruption(PluginManager& manager, std::string_view plugin, bool writing, bool deadline) {
auto exporter = manager.CreateExtension(Exporters, plugin, deadline ? std::chrono::milliseconds(750) : DefaultTimeout);
(void)exporter->ProcessId();
auto gate = std::make_shared<HeldStreamOperation>();
auto input = writing ? StringInput("name;city\nAlice;Paris\n") : AsyncInputStream::FromReader(
[gate](std::stop_token stop, std::size_t) { return gate->Hold<huxerui::Bytes>(stop); });
auto output = AsyncOutputStream::FromWriter(
[gate, writing](std::stop_token stop, huxerui::Bytes) -> Task<IoResult<void>> {
if (writing) co_return co_await gate->Hold<void>(stop);
co_return IoResult<void>::Success();
});
auto first_output = AsyncOutputStream::FromWriter(
[](std::stop_token, huxerui::Bytes) -> Task<IoResult<void>> { co_return IoResult<void>::Success(); });
auto first_progress = std::make_shared<ConversionProgress>();
auto second_progress = std::make_shared<ConversionProgress>();
const std::weak_ptr<ConversionProgress> first_callback = first_progress;
const std::weak_ptr<ConversionProgress> second_callback = second_progress;
auto outcome = std::make_shared<CallOutcome>();
const auto handle = UseApplicationTaskScope().Launch(ObserveCall(
exporter->ConvertPairAsync(StringInput("x;y\n1;2\n"), csv_import::Separator(";"), std::move(first_progress),
std::move(first_output), 512 * 1024, std::move(output), std::move(second_progress), std::move(input)), outcome));
co_await WaitFor([gate] { return gate->started; });
if (!deadline) handle.Cancel();
co_await WaitFor([&] { return gate->cancelled && first_callback.expired() && second_callback.expired(); });
gate->late();
if (deadline) {
co_await WaitFor([outcome] { return outcome->done; });
if (!outcome->error) throw Error(ErrorCode::PluginFailed, "The invocation ignored its deadline");
try {
std::rethrow_exception(outcome->error);
} catch (const Error& error) {
if (error.Code() != ErrorCode::DeadlineExceeded) throw;
}
} else if (outcome->done) {
throw Error(ErrorCode::PluginFailed, "A cancelled stream invocation delivered a result");
}
co_return Json{{"cancelled", gate->cancelled}, {"stop_requested", gate->stop_requested}, {"deadline", deadline}};
}
Task<Json> CheckLocalStreamReentry(PluginManager& manager, std::string_view plugin, bool synchronous) {
auto exporter = manager.CreateExtension(Exporters, plugin);
if (exporter->ProcessId() != ProcessId()) throw Error(ErrorCode::InvalidArgument, "Expected an in-process exporter");
constexpr std::string_view sample = "name;city\nAlice;Paris\n";
struct Checked {
bool read = false;
bool write = false;
bool close = false;
};
auto checked = std::make_shared<Checked>();
if (synchronous) {
const auto check = [&exporter] {
try {
(void)exporter->ProcessId();
} catch (const Error& error) {
if (error.Code() == ErrorCode::ReentrantCall) return;
throw;
}
throw Error(ErrorCode::PluginFailed, "The synchronous stream callback reentered PluginKit");
};
auto input = huxerui::InputStream::FromReader(
[check, checked, source = sample](std::span<std::byte> buffer) mutable {
check();
checked->read = true;
const auto count = std::min(source.size(), buffer.size());
if (count) std::memcpy(buffer.data(), source.data(), count);
source.remove_prefix(count);
return IoResult<std::size_t>(count);
});
auto output = huxerui::OutputStream::FromWriter(
[check, checked](std::span<const std::byte>) {
check();
checked->write = true;
return IoResult<void>::Success();
},
[check, checked] {
check();
checked->close = true;
return IoResult<void>::Success();
});
(void)exporter->Convert({}, std::move(input), std::move(output));
} else {
const auto check = [&manager, id = std::string(plugin)]() -> Task<void> {
co_await Delay(std::chrono::milliseconds(1));
try {
co_await manager.SetEnabled(id, true);
} catch (const Error& error) {
if (error.Code() == ErrorCode::ReentrantCall) co_return;
throw;
}
throw Error(ErrorCode::PluginFailed, "The asynchronous stream callback reentered PluginKit");
};
auto input = AsyncInputStream::FromReader(
[check, checked, source = std::make_shared<AsyncInputStream>(StringInput(std::string(sample)))]
(std::stop_token, std::size_t count) -> Task<IoResult<huxerui::Bytes>> {
co_await check();
checked->read = true;
co_return co_await source->ReadAsync(count);
});
auto output = AsyncOutputStream::FromWriter(
[check, checked](std::stop_token, huxerui::Bytes) -> Task<IoResult<void>> {
co_await check();
checked->write = true;
co_return IoResult<void>::Success();
},
[check, checked](std::stop_token) -> Task<IoResult<void>> {
co_await check();
checked->close = true;
co_return IoResult<void>::Success();
});
(void)co_await exporter->ConvertAsync({}, std::move(input), std::move(output), nullptr);
}
co_return Json{{"read", checked->read}, {"write", checked->write}, {"close", checked->close}};
}
void TerminateFixtureWorker(std::uint32_t pid) {
#if defined(_WIN32)
const auto process = ::OpenProcess(PROCESS_TERMINATE, FALSE, pid);
if (process) {
const auto terminated = ::TerminateProcess(process, 1);
::CloseHandle(process);
if (terminated) return;
}
#else
if (::kill(static_cast<pid_t>(pid), SIGKILL) == 0) return;
#endif
throw Error(ErrorCode::PluginFailed, "Cannot terminate the CSV fixture worker");
}
Task<void> CheckWorkerExitDuringCallback(PluginManager& manager, std::string_view plugin, bool during_receiver) {
// Leave a longer invocation deadline than the fixture's wait for a worker-exit response.
auto exporter = manager.CreateExtension(Exporters, plugin, DefaultTimeout * 3);
const auto pid = exporter->ProcessId();
const auto plugins = manager.ListPlugins();
if (!pid || pid == ProcessId() || !std::ranges::any_of(plugins, [&](const auto& entry) {
return entry.package.id == plugin && entry.worker_pid == pid;
})) {
throw Error(ErrorCode::InvalidArgument, "Expected a worker exporter");
}
auto stream = std::make_shared<HeldStreamOperation>();
auto progress = std::make_shared<ProgressGate>();
auto receiver = std::make_shared<HeldProgress>(progress);
const std::weak_ptr<HeldProgress> receiver_lifetime = receiver;
auto input = during_receiver ? StringInput("name;city\nAlice;Paris\n") : AsyncInputStream::FromReader(
[stream](std::stop_token stop, std::size_t) { return stream->Hold<huxerui::Bytes>(stop); });
auto written = std::make_shared<std::size_t>(0);
const std::weak_ptr<std::size_t> output_lifetime = written;
const auto make_output = [&written] {
return AsyncOutputStream::FromWriter(
[written](std::stop_token, huxerui::Bytes bytes) -> Task<IoResult<void>> {
*written += bytes.size();
co_return IoResult<void>::Success();
});
};
auto first_output = make_output();
auto output = make_output();
written.reset();
auto first_progress = std::make_shared<ConversionProgress>();
const std::weak_ptr<ConversionProgress> first_lifetime = first_progress;
const auto outcome = std::make_shared<CallOutcome>();
(void)UseApplicationTaskScope().Launch(ObserveCall(
exporter->ConvertPairAsync(StringInput("x;y\n1;2\n"), csv_import::Separator(";"), std::move(first_progress),
std::move(first_output), 512 * 1024, std::move(output), std::move(receiver), std::move(input)), outcome));
co_await WaitFor([&] { return during_receiver ? progress->started : stream->started; });
TerminateFixtureWorker(pid);
co_await WaitFor([&] {
const bool cancelled = during_receiver ? progress->cancelled : stream->cancelled && stream->stop_requested;
return cancelled && outcome->done && first_lifetime.expired() && receiver_lifetime.expired() && output_lifetime.expired();
});
if (during_receiver) progress->complete->Complete(9);
else stream->late();
if (!outcome->error) throw Error(ErrorCode::PluginFailed, "The exited worker returned a conversion result");
try {
std::rethrow_exception(outcome->error);
} catch (const Error& error) {
if (error.Code() != ErrorCode::WorkerExited) throw;
}
}
Task<Json> CheckWorkerEvents(PluginManager& manager, const std::vector<std::string>& args) {
const auto& plugin = args[1];
const bool idle = args[2] == "idle";
auto other = manager.CreateExtension(Exporters, args[3]);
const auto other_pid = other->ProcessId();
std::vector<PluginEvent> events;
std::optional<PluginDiagnostics> faulted;
std::optional<ExtensionHandle<csv_import::TableExporter>> recovered;
std::exception_ptr callback_error;
auto subscription = manager.SubscribeEvents([&](const PluginEvent& event) {
if (event.package.id != plugin) return;
events.push_back(event);
if (event.kind != PluginEventKind::WorkerExited) return;
try {
faulted = manager.Diagnostics(plugin);
const auto catalog = manager.ListPlugins();
const auto listed = std::ranges::find_if(catalog, [&](const auto& entry) { return entry.package.id == plugin; });
if (listed == catalog.end() || listed->worker_pid) {
throw Error(ErrorCode::PluginFailed, "The exited worker is still listed");
}
recovered.emplace(manager.CreateExtension(Exporters, plugin));
(void)(*recovered)->ProcessId();
} catch (...) {
callback_error = std::current_exception();
}
});
auto exporter = manager.CreateExtension(Exporters, plugin);
const auto pid = exporter->ProcessId();
if (!pid || pid == ProcessId()) throw Error(ErrorCode::InvalidArgument, "Expected a CSV worker");
co_await WaitFor([&] { return !events.empty(); });
if (idle) TerminateFixtureWorker(pid);
else co_await CheckWorkerExitDuringCallback(manager, plugin, args[2] == "receiver");
co_await WaitFor([&] { return events.size() >= 2; });
if (callback_error) std::rethrow_exception(callback_error);
if (events[0].kind != PluginEventKind::Activated ||
!events[0].generation || events[1].kind != PluginEventKind::WorkerExited ||
events[1].generation != events[0].generation || events[1].worker_pid != pid ||
!events[1].failure || events[1].failure->code != ErrorCode::WorkerExited ||
(!events[1].failure->exit_code && !events[1].failure->signal) ||
!faulted || !faulted->plugin.enabled || faulted->plugin.worker_pid ||
faulted->state != PluginRuntimeState::Faulted || !faulted->last_failure ||
faulted->last_failure->sequence != events[1].sequence || other->ProcessId() != other_pid) {
throw Error(ErrorCode::PluginFailed, "Unexpected worker exit diagnostics");
}
auto output = AsyncOutputStream::FromWriter([](std::stop_token, huxerui::Bytes) -> Task<IoResult<void>> {
co_return IoResult<void>::Success();
});
const auto summary = co_await (*recovered)->ConvertAsync({}, StringInput("name;city\nAlice;Paris\n"),
std::move(output), nullptr);
co_await WaitFor([&] { return events.size() >= 3; });
const auto active = manager.Diagnostics(plugin);
if (summary.rows != 1 || events.size() != 3 || events[2].kind != PluginEventKind::Activated ||
events[2].generation <= events[0].generation || !active || active->state != PluginRuntimeState::Active ||
active->generation != events[2].generation || !active->last_failure ||
active->last_failure->sequence != events[1].sequence) {
throw Error(ErrorCode::PluginFailed, "Worker recovery did not preserve the last failure");
}
co_return Json{{"recovered", true}};
}
Task<Json> CheckCatalogEvents(PluginManager& manager, const std::string& plugin) {
std::vector<PluginEvent> events;
bool valid = true;
const auto thread = std::this_thread::get_id();
auto throwing = manager.SubscribeEvents([](const PluginEvent&) { throw std::runtime_error("Observer fixture"); });
auto subscription = manager.SubscribeEvents([&](const PluginEvent& event) {
if (event.package.id != plugin) return;
valid = valid && std::this_thread::get_id() == thread &&
(events.empty() || event.sequence > events.back().sequence);
events.push_back(event);
if (event.change == PluginCatalogChange::Disabled) {
const auto diagnostic = manager.Diagnostics(plugin);
const auto candidates = manager.ListExtensions(Exporters);
valid = valid && diagnostic && !diagnostic->plugin.enabled &&
std::ranges::find(candidates, plugin, &ExtensionInfo::PluginId) == candidates.end();
}
});
PluginEventSubscription once;
unsigned once_calls = 0;
once = manager.SubscribeEvents([&](const PluginEvent&) {
++once_calls;
once = {};
});
unsigned released_calls = 0;
auto exporter = manager.CreateExtension(Exporters, plugin);
{
auto released = manager.SubscribeEvents([&](const PluginEvent&) { ++released_calls; });
(void)exporter->ProcessId();
}
unsigned later_calls = 0;
auto later = manager.SubscribeEvents([&](const PluginEvent&) { ++later_calls; });
if (!events.empty()) throw Error(ErrorCode::PluginFailed, "A plugin event was delivered inline");
co_await WaitFor([&] { return !events.empty(); });
if (later_calls) throw Error(ErrorCode::PluginFailed, "An event was replayed to a new subscriber");
co_await manager.SetEnabled(plugin, false);
co_await manager.SetEnabled(plugin, false);
co_await manager.SetEnabled(plugin, true);
co_await WaitFor([&] { return !events.empty() && events.back().change == PluginCatalogChange::Enabled; });
if (!valid || once_calls != 1 || released_calls || later_calls != 3 || events.size() != 4 ||
events[0].kind != PluginEventKind::Activated || events[1].change != PluginCatalogChange::Disabled ||
events[2].kind != PluginEventKind::Stopped || events[2].stop_reason != PluginStopReason::Disabled ||
events[2].generation != events[0].generation || events[2].failure) {
throw Error(ErrorCode::PluginFailed, "Unexpected catalog events or subscription lifetime");
}
co_return Json{{"catalog_events", true}};
}
Task<Json> CheckStaleStream(PluginManager& manager, std::string_view plugin) {
auto exporter = manager.CreateExtension(Exporters, plugin);
int reads = 0;
const auto source = [&reads] {
return AsyncInputStream::FromReader([&reads](std::stop_token, std::size_t) -> Task<IoResult<huxerui::Bytes>> {
++reads;
co_return IoResult<huxerui::Bytes>(huxerui::Bytes{std::byte{'x'}});
});
};
const auto sink = [] {
return AsyncOutputStream::FromWriter([](std::stop_token, huxerui::Bytes) -> Task<IoResult<void>> {
co_return IoResult<void>::Success();
});
};
(void)co_await exporter->ConvertAsync({}, source(), sink(), nullptr);
try {
(void)co_await exporter->ConvertAsync({}, source(), sink(), nullptr);
throw Error(ErrorCode::PluginFailed, "The stale stream was not rejected");
} catch (const Error& error) {
if (error.Code() != ErrorCode::Closed) throw;
}
co_return Json{{"old_source_reads", reads}};
}
Task<Json> CheckSynchronousStreamDeadline(PluginManager& manager, std::string_view plugin, bool writing) {
using namespace std::chrono_literals;
auto exporter = manager.CreateExtension(Exporters, plugin, 400ms);
(void)exporter->ProcessId();
struct Pending {
std::mutex mutex;
std::condition_variable release;
bool started = false;
bool finished = false;
};
auto pending = std::make_shared<Pending>();
const auto hold = [pending] {
std::unique_lock lock(pending->mutex);
pending->started = true;
pending->release.wait_for(lock, 3s, [&] { return pending->finished; });
};
auto completed = std::make_shared<std::atomic_bool>(false);
auto input = huxerui::InputStream::FromReader(
[hold, writing, completed, sent = false](std::span<std::byte> bytes) mutable -> IoResult<std::size_t> {
if (!writing) {
hold();
*completed = true;
return IoResult<std::size_t>(0);
}
if (std::exchange(sent, true)) return IoResult<std::size_t>(0);
constexpr std::string_view source = "name;city\nAlice;Paris\n";
std::memcpy(bytes.data(), source.data(), source.size());
return IoResult<std::size_t>(source.size());
});
auto output = huxerui::OutputStream::FromWriter([hold, writing, completed](std::span<const std::byte>) {
if (writing) {
hold();
*completed = true;
}
return IoResult<void>::Success();
});
const auto error = [&]() -> std::optional<ErrorCode> {
try {
(void)exporter->Convert({}, std::move(input), std::move(output));
return std::nullopt;
} catch (const Error& failure) {
return failure.Code();
}
}();
bool still_running;
{
std::lock_guard lock(pending->mutex);
still_running = pending->started && !completed->load();
pending->finished = true;
}
pending->release.notify_one();
if (error != ErrorCode::DeadlineExceeded || !still_running) {
throw Error(ErrorCode::PluginFailed, "The synchronous stream did not time out independently of its I/O");
}
co_await WaitFor([completed] { return completed->load(); });
co_return Json{{"deadline_while_io_pending", true}};
}
Task<Json> CheckReceiverLifetime(PluginManager& manager, std::string plugin) {
for (const auto& extension : manager.ListExtensions(Importers)) {
if (extension.PluginId() != plugin) continue;
const auto tasks = UseApplicationTaskScope();
auto importer = manager.CreateExtension(Importers, extension);
auto first = std::make_shared<PreviewProgress>();
auto second = std::make_shared<PreviewProgress>();
(void)co_await importer->Import(StringInput("remember"), first);
try {
(void)co_await importer->Import(StringInput("stale"), second);
throw Error(ErrorCode::PluginFailed, "An expired receiver was accepted");
} catch (const Error& error) {
if (error.Code() != ErrorCode::ReceiverClosed) throw;
}
auto held = std::make_shared<ProgressGate>();
auto running = std::make_shared<CallOutcome>();
(void)tasks.Launch(ObserveCall(importer->Import(StringInput("remember"), std::make_shared<HeldProgress>(held)), running));
co_await WaitFor([held] { return held->started; });
// The receiver is still suspended when this independent task reads the catalog.
auto catalog_during_callback = List(manager);
auto queued = std::make_shared<CallOutcome>();