-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathGraphQLService.cpp
More file actions
2303 lines (1848 loc) · 58.5 KB
/
GraphQLService.cpp
File metadata and controls
2303 lines (1848 loc) · 58.5 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "graphqlservice/GraphQLService.h"
#include "graphqlservice/internal/Grammar.h"
#include "Validation.h"
#include <algorithm>
#include <array>
#include <iostream>
namespace graphql::service {
void addErrorMessage(std::string&& message, response::Value& error)
{
error.emplace_back(std::string { strMessage }, response::Value(std::move(message)));
}
void addErrorLocation(const schema_location& location, response::Value& error)
{
if (location.line == 0)
{
return;
}
response::Value errorLocation(response::Type::Map);
errorLocation.reserve(2);
errorLocation.emplace_back(std::string { strLine },
response::Value(static_cast<int>(location.line)));
errorLocation.emplace_back(std::string { strColumn },
response::Value(static_cast<int>(location.column)));
response::Value errorLocations(response::Type::List);
errorLocations.reserve(1);
errorLocations.emplace_back(std::move(errorLocation));
error.emplace_back(std::string { strLocations }, std::move(errorLocations));
}
void addErrorPath(const error_path& path, response::Value& error)
{
if (path.empty())
{
return;
}
response::Value errorPath(response::Type::List);
errorPath.reserve(path.size());
for (const auto& segment : path)
{
if (std::holds_alternative<std::string_view>(segment))
{
errorPath.emplace_back(
response::Value { std::string { std::get<std::string_view>(segment) } });
}
else if (std::holds_alternative<size_t>(segment))
{
errorPath.emplace_back(response::Value(static_cast<int>(std::get<size_t>(segment))));
}
}
error.emplace_back(std::string { strPath }, std::move(errorPath));
}
error_path buildErrorPath(const std::optional<field_path>& path)
{
error_path result;
if (path)
{
std::list<std::reference_wrapper<const path_segment>> segments;
for (auto segment = std::make_optional(std::cref(*path)); segment;
segment = segment->get().parent)
{
segments.push_front(std::cref(segment->get().segment));
}
result.reserve(segments.size());
std::transform(segments.cbegin(),
segments.cend(),
std::back_inserter(result),
[](const auto& segment) noexcept {
return segment.get();
});
}
return result;
}
response::Value buildErrorValues(std::list<schema_error>&& structuredErrors)
{
response::Value errors(response::Type::List);
errors.reserve(structuredErrors.size());
for (auto& error : structuredErrors)
{
response::Value entry(response::Type::Map);
entry.reserve(3);
addErrorMessage(std::move(error.message), entry);
addErrorLocation(error.location, entry);
addErrorPath(error.path, entry);
errors.emplace_back(std::move(entry));
}
return errors;
}
schema_exception::schema_exception(std::list<schema_error>&& structuredErrors)
: _structuredErrors(std::move(structuredErrors))
{
}
schema_exception::schema_exception(std::vector<std::string>&& messages)
: schema_exception(convertMessages(std::move(messages)))
{
}
std::list<schema_error> schema_exception::convertMessages(
std::vector<std::string>&& messages) noexcept
{
std::list<schema_error> errors;
std::transform(messages.begin(),
messages.end(),
std::back_inserter(errors),
[](std::string& message) noexcept {
return schema_error { std::move(message) };
});
return errors;
}
const char* schema_exception::what() const noexcept
{
const char* message = nullptr;
if (!_structuredErrors.empty())
{
message = _structuredErrors.front().message.c_str();
}
return (message == nullptr) ? "Unknown schema error" : message;
}
std::list<schema_error> schema_exception::getStructuredErrors() noexcept
{
auto structuredErrors = std::move(_structuredErrors);
return structuredErrors;
}
response::Value schema_exception::getErrors()
{
return buildErrorValues(std::move(_structuredErrors));
}
unimplemented_method::unimplemented_method(std::string_view methodName)
: std::runtime_error { getMessage(methodName) }
{
}
std::string unimplemented_method::getMessage(std::string_view methodName) noexcept
{
using namespace std::literals;
std::ostringstream oss;
oss << methodName << R"ex( is not implemented)ex"sv;
return oss.str();
}
void await_worker_thread::await_suspend(coro::coroutine_handle<> h) const
{
std::thread(
[](coro::coroutine_handle<>&& h) {
h.resume();
},
std::move(h))
.detach();
}
await_worker_queue::await_worker_queue()
: _startId { std::this_thread::get_id() }
, _worker { [this]() {
resumePending();
} }
{
}
await_worker_queue::~await_worker_queue()
{
std::unique_lock lock { _mutex };
_shutdown = true;
lock.unlock();
_cv.notify_one();
_worker.join();
}
bool await_worker_queue::await_ready() const
{
return std::this_thread::get_id() != _startId;
}
void await_worker_queue::await_suspend(coro::coroutine_handle<> h)
{
std::unique_lock lock { _mutex };
_pending.push_back(std::move(h));
lock.unlock();
_cv.notify_one();
}
void await_worker_queue::resumePending()
{
std::unique_lock lock { _mutex };
while (!_shutdown)
{
_cv.wait(lock, [this]() {
return _shutdown || !_pending.empty();
});
std::list<coro::coroutine_handle<>> pending;
std::swap(pending, _pending);
lock.unlock();
for (auto h : pending)
{
h.resume();
}
lock.lock();
}
}
// Default to immediate synchronous execution.
await_async::await_async()
: _pimpl { std::static_pointer_cast<const Concept>(
std::make_shared<Model<coro::suspend_never>>(std::make_shared<coro::suspend_never>())) }
{
}
// Implicitly convert a std::launch parameter used with std::async to an awaitable.
await_async::await_async(std::launch launch)
: _pimpl { ((launch & std::launch::async) == std::launch::async)
? std::static_pointer_cast<const Concept>(std::make_shared<Model<await_worker_thread>>(
std::make_shared<await_worker_thread>()))
: std::static_pointer_cast<const Concept>(std::make_shared<Model<coro::suspend_never>>(
std::make_shared<coro::suspend_never>())) }
{
}
bool await_async::await_ready() const
{
return _pimpl->await_ready();
}
void await_async::await_suspend(coro::coroutine_handle<> h) const
{
_pimpl->await_suspend(std::move(h));
}
void await_async::await_resume() const
{
_pimpl->await_resume();
}
FieldParams::FieldParams(SelectionSetParams&& selectionSetParams, Directives directives)
: SelectionSetParams(std::move(selectionSetParams))
, fieldDirectives(std::move(directives))
{
}
// ValueVisitor visits the AST and builds a response::Value representation of any value
// hardcoded or referencing a variable in an operation.
class ValueVisitor
{
public:
ValueVisitor(const response::Value& variables);
void visit(const peg::ast_node& value);
response::Value getValue();
private:
void visitVariable(const peg::ast_node& variable);
void visitIntValue(const peg::ast_node& intValue);
void visitFloatValue(const peg::ast_node& floatValue);
void visitStringValue(const peg::ast_node& stringValue);
void visitBooleanValue(const peg::ast_node& booleanValue);
void visitNullValue(const peg::ast_node& nullValue);
void visitEnumValue(const peg::ast_node& enumValue);
void visitListValue(const peg::ast_node& listValue);
void visitObjectValue(const peg::ast_node& objectValue);
const response::Value& _variables;
response::Value _value;
};
ValueVisitor::ValueVisitor(const response::Value& variables)
: _variables(variables)
{
}
response::Value ValueVisitor::getValue()
{
auto result = std::move(_value);
return result;
}
void ValueVisitor::visit(const peg::ast_node& value)
{
if (value.is_type<peg::variable_value>())
{
visitVariable(value);
}
else if (value.is_type<peg::integer_value>())
{
visitIntValue(value);
}
else if (value.is_type<peg::float_value>())
{
visitFloatValue(value);
}
else if (value.is_type<peg::string_value>())
{
visitStringValue(value);
}
else if (value.is_type<peg::true_keyword>() || value.is_type<peg::false_keyword>())
{
visitBooleanValue(value);
}
else if (value.is_type<peg::null_keyword>())
{
visitNullValue(value);
}
else if (value.is_type<peg::enum_value>())
{
visitEnumValue(value);
}
else if (value.is_type<peg::list_value>())
{
visitListValue(value);
}
else if (value.is_type<peg::object_value>())
{
visitObjectValue(value);
}
}
void ValueVisitor::visitVariable(const peg::ast_node& variable)
{
const auto name = variable.string_view().substr(1);
auto itr = _variables.find(name);
if (itr == _variables.get<response::MapType>().cend())
{
auto position = variable.begin();
std::ostringstream error;
error << "Unknown variable name: " << name;
throw schema_exception {
{ schema_error { error.str(), { position.line, position.column } } }
};
}
_value = response::Value(itr->second);
}
void ValueVisitor::visitIntValue(const peg::ast_node& intValue)
{
_value = response::Value(std::atoi(intValue.string().c_str()));
}
void ValueVisitor::visitFloatValue(const peg::ast_node& floatValue)
{
_value = response::Value(std::atof(floatValue.string().c_str()));
}
void ValueVisitor::visitStringValue(const peg::ast_node& stringValue)
{
_value = response::Value(std::string { stringValue.unescaped_view() }).from_input();
}
void ValueVisitor::visitBooleanValue(const peg::ast_node& booleanValue)
{
_value = response::Value(booleanValue.is_type<peg::true_keyword>());
}
void ValueVisitor::visitNullValue(const peg::ast_node& /*nullValue*/)
{
_value = {};
}
void ValueVisitor::visitEnumValue(const peg::ast_node& enumValue)
{
_value = response::Value(response::Type::EnumValue);
_value.set<std::string>(enumValue.string());
}
void ValueVisitor::visitListValue(const peg::ast_node& listValue)
{
_value = response::Value(response::Type::List);
_value.reserve(listValue.children.size());
ValueVisitor visitor(_variables);
for (const auto& child : listValue.children)
{
visitor.visit(*child);
_value.emplace_back(visitor.getValue());
}
}
void ValueVisitor::visitObjectValue(const peg::ast_node& objectValue)
{
_value = response::Value(response::Type::Map);
_value.reserve(objectValue.children.size());
ValueVisitor visitor(_variables);
for (const auto& field : objectValue.children)
{
visitor.visit(*field->children.back());
_value.emplace_back(field->children.front()->string(), visitor.getValue());
}
}
// DirectiveVisitor visits the AST and builds a 2-level map of directive names to argument
// name/value pairs.
class DirectiveVisitor
{
public:
explicit DirectiveVisitor(const response::Value& variables);
void visit(const peg::ast_node& directives);
bool shouldSkip() const;
Directives getDirectives();
private:
const response::Value& _variables;
Directives _directives;
};
DirectiveVisitor::DirectiveVisitor(const response::Value& variables)
: _variables(variables)
{
}
void DirectiveVisitor::visit(const peg::ast_node& directives)
{
Directives result;
for (const auto& directive : directives.children)
{
std::string_view directiveName;
peg::on_first_child<peg::directive_name>(*directive,
[&directiveName](const peg::ast_node& child) {
directiveName = child.string_view();
});
if (directiveName.empty())
{
continue;
}
response::Value directiveArguments(response::Type::Map);
peg::on_first_child<peg::arguments>(*directive,
[this, &directiveArguments](const peg::ast_node& child) {
ValueVisitor visitor(_variables);
for (auto& argument : child.children)
{
visitor.visit(*argument->children.back());
directiveArguments.emplace_back(argument->children.front()->string(),
visitor.getValue());
}
});
result.emplace_back(directiveName, std::move(directiveArguments));
}
_directives = std::move(result);
}
Directives DirectiveVisitor::getDirectives()
{
auto result = std::move(_directives);
return result;
}
bool DirectiveVisitor::shouldSkip() const
{
constexpr std::array<std::pair<bool, std::string_view>, 2> c_skippedDirectives = {
std::make_pair(true, R"gql(skip)gql"sv),
std::make_pair(false, R"gql(include)gql"sv),
};
for (const auto& [skip, directiveName] : c_skippedDirectives)
{
auto itrDirective = std::find_if(_directives.cbegin(),
_directives.cend(),
[directiveName = directiveName](const auto& directive) noexcept {
return directive.first == directiveName;
});
if (itrDirective == _directives.end())
{
continue;
}
auto& arguments = itrDirective->second;
if (arguments.type() != response::Type::Map)
{
std::ostringstream error;
error << "Invalid arguments to directive: " << directiveName;
throw schema_exception { { error.str() } };
}
bool argumentTrue = false;
bool argumentFalse = false;
for (auto& [argumentName, argumentValue] : arguments)
{
if (argumentTrue || argumentFalse || argumentValue.type() != response::Type::Boolean
|| argumentName != "if")
{
std::ostringstream error;
error << "Invalid argument to directive: " << directiveName
<< " name: " << argumentName;
throw schema_exception { { error.str() } };
}
argumentTrue = argumentValue.get<bool>();
argumentFalse = !argumentTrue;
}
if (argumentTrue)
{
return skip;
}
else if (argumentFalse)
{
return !skip;
}
else
{
std::ostringstream error;
error << "Missing argument directive: " << directiveName << " name: if";
throw schema_exception { { error.str() } };
}
}
return false;
}
Fragment::Fragment(const peg::ast_node& fragmentDefinition, const response::Value& variables)
: _type(fragmentDefinition.children[1]->children.front()->string_view())
, _selection(*(fragmentDefinition.children.back()))
{
peg::on_first_child<peg::directives>(fragmentDefinition,
[this, &variables](const peg::ast_node& child) {
DirectiveVisitor directiveVisitor(variables);
directiveVisitor.visit(child);
_directives = directiveVisitor.getDirectives();
});
}
std::string_view Fragment::getType() const
{
return _type;
}
const peg::ast_node& Fragment::getSelection() const
{
return _selection.get();
}
const Directives& Fragment::getDirectives() const
{
return _directives;
}
ResolverParams::ResolverParams(const SelectionSetParams& selectionSetParams,
const peg::ast_node& field, std::string&& fieldName, response::Value arguments,
Directives fieldDirectives, const peg::ast_node* selection, const FragmentMap& fragments,
const response::Value& variables)
: SelectionSetParams(selectionSetParams)
, field(field)
, fieldName(std::move(fieldName))
, arguments(std::move(arguments))
, fieldDirectives(std::move(fieldDirectives))
, selection(selection)
, fragments(fragments)
, variables(variables)
{
}
schema_location ResolverParams::getLocation() const
{
auto position = field.begin();
return { position.line, position.column };
}
template <>
int Argument<int>::convert(const response::Value& value)
{
if (value.type() != response::Type::Int)
{
throw schema_exception { { "not an integer" } };
}
return value.get<int>();
}
template <>
double Argument<double>::convert(const response::Value& value)
{
if (value.type() != response::Type::Float && value.type() != response::Type::Int)
{
throw schema_exception { { "not a float" } };
}
return value.get<double>();
}
template <>
std::string Argument<std::string>::convert(const response::Value& value)
{
if (value.type() != response::Type::String)
{
throw schema_exception { { "not a string" } };
}
return value.get<std::string>();
}
template <>
bool Argument<bool>::convert(const response::Value& value)
{
if (value.type() != response::Type::Boolean)
{
throw schema_exception { { "not a boolean" } };
}
return value.get<bool>();
}
template <>
response::Value Argument<response::Value>::convert(const response::Value& value)
{
return response::Value(value);
}
template <>
response::IdType Argument<response::IdType>::convert(const response::Value& value)
{
if (!value.maybe_id())
{
throw schema_exception { { "not an ID" } };
}
return response::Value { value }.release<response::IdType>();
}
void blockSubFields(const ResolverParams& params)
{
// https://spec.graphql.org/October2021/#sec-Leaf-Field-Selections
if (params.selection != nullptr)
{
auto position = params.selection->begin();
std::ostringstream error;
error << "Field may not have sub-fields name: " << params.fieldName;
throw schema_exception { { schema_error { error.str(),
{ position.line, position.column },
buildErrorPath(params.errorPath) } } };
}
}
template <>
AwaitableResolver Result<int>::convert(AwaitableScalar<int> result, ResolverParams&& params)
{
blockSubFields(params);
return ModifiedResult<int>::resolve(std::move(result),
std::move(params),
[](int&& value, const ResolverParams&) {
return response::Value(value);
});
}
template <>
AwaitableResolver Result<double>::convert(AwaitableScalar<double> result, ResolverParams&& params)
{
blockSubFields(params);
return ModifiedResult<double>::resolve(std::move(result),
std::move(params),
[](double&& value, const ResolverParams&) {
return response::Value(value);
});
}
template <>
AwaitableResolver Result<std::string>::convert(
AwaitableScalar<std::string> result, ResolverParams&& params)
{
blockSubFields(params);
return ModifiedResult<std::string>::resolve(std::move(result),
std::move(params),
[](std::string&& value, const ResolverParams&) {
return response::Value(std::move(value));
});
}
template <>
AwaitableResolver Result<bool>::convert(AwaitableScalar<bool> result, ResolverParams&& params)
{
blockSubFields(params);
return ModifiedResult<bool>::resolve(std::move(result),
std::move(params),
[](bool&& value, const ResolverParams&) {
return response::Value(value);
});
}
template <>
AwaitableResolver Result<response::Value>::convert(
AwaitableScalar<response::Value> result, ResolverParams&& params)
{
blockSubFields(params);
return ModifiedResult<response::Value>::resolve(std::move(result),
std::move(params),
[](response::Value&& value, const ResolverParams&) {
return response::Value(std::move(value));
});
}
template <>
AwaitableResolver Result<response::IdType>::convert(
AwaitableScalar<response::IdType> result, ResolverParams&& params)
{
blockSubFields(params);
return ModifiedResult<response::IdType>::resolve(std::move(result),
std::move(params),
[](response::IdType&& value, const ResolverParams&) {
return response::Value(std::move(value));
});
}
void requireSubFields(const ResolverParams& params)
{
// https://spec.graphql.org/October2021/#sec-Leaf-Field-Selections
if (params.selection == nullptr)
{
auto position = params.field.begin();
std::ostringstream error;
error << "Field must have sub-fields name: " << params.fieldName;
throw schema_exception { { schema_error { error.str(),
{ position.line, position.column },
buildErrorPath(params.errorPath) } } };
}
}
template <>
AwaitableResolver Result<Object>::convert(
AwaitableObject<std::shared_ptr<const Object>> result, ResolverParams&& paramsArg)
{
requireSubFields(paramsArg);
// Move the paramsArg into a local variable before the first suspension point.
auto params = std::move(paramsArg);
co_await params.launch;
auto awaitedResult = co_await std::move(result);
if (!awaitedResult)
{
co_return ResolverResult {};
}
auto document = co_await awaitedResult->resolve(params,
*params.selection,
params.fragments,
params.variables);
co_return std::move(document);
}
template <>
void Result<int>::validateScalar(const response::Value& value)
{
if (value.type() != response::Type::Int)
{
throw schema_exception { { R"ex(not a valid Int value)ex" } };
}
}
template <>
void Result<double>::validateScalar(const response::Value& value)
{
if (value.type() != response::Type::Float)
{
throw schema_exception { { R"ex(not a valid Float value)ex" } };
}
}
template <>
void Result<std::string>::validateScalar(const response::Value& value)
{
if (value.type() != response::Type::String)
{
throw schema_exception { { R"ex(not a valid String value)ex" } };
}
}
template <>
void Result<bool>::validateScalar(const response::Value& value)
{
if (value.type() != response::Type::Boolean)
{
throw schema_exception { { R"ex(not a valid Boolean value)ex" } };
}
}
template <>
void Result<response::IdType>::validateScalar(const response::Value& value)
{
if (!value.maybe_id())
{
throw schema_exception { { R"ex(not a valid ID value)ex" } };
}
}
template <>
void Result<response::Value>::validateScalar(const response::Value&)
{
// Any response::Value is valid for a custom scalar type.
}
// SelectionVisitor visits the AST and resolves a field or fragment, unless it's skipped by
// a directive or type condition.
class SelectionVisitor
{
public:
explicit SelectionVisitor(const SelectionSetParams& selectionSetParams,
const FragmentMap& fragments, const response::Value& variables, const TypeNames& typeNames,
const ResolverMap& resolvers, size_t count);
void visit(const peg::ast_node& selection);
struct VisitorValue
{
std::string_view name;
std::optional<schema_location> location;
AwaitableResolver result;
};
std::vector<VisitorValue> getValues();
private:
void visitField(const peg::ast_node& field);
void visitFragmentSpread(const peg::ast_node& fragmentSpread);
void visitInlineFragment(const peg::ast_node& inlineFragment);
const ResolverContext _resolverContext;
const std::shared_ptr<RequestState>& _state;
const Directives& _operationDirectives;
const std::optional<std::reference_wrapper<const field_path>> _path;
const await_async _launch;
const FragmentMap& _fragments;
const response::Value& _variables;
const TypeNames& _typeNames;
const ResolverMap& _resolvers;
std::shared_ptr<FragmentDefinitionDirectiveStack> _fragmentDefinitionDirectives;
std::shared_ptr<FragmentSpreadDirectiveStack> _fragmentSpreadDirectives;
std::shared_ptr<FragmentSpreadDirectiveStack> _inlineFragmentDirectives;
internal::string_view_set _names;
std::vector<VisitorValue> _values;
};
SelectionVisitor::SelectionVisitor(const SelectionSetParams& selectionSetParams,
const FragmentMap& fragments, const response::Value& variables, const TypeNames& typeNames,
const ResolverMap& resolvers, size_t count)
: _resolverContext(selectionSetParams.resolverContext)
, _state(selectionSetParams.state)
, _operationDirectives(selectionSetParams.operationDirectives)
, _path(selectionSetParams.errorPath
? std::make_optional(std::cref(*selectionSetParams.errorPath))
: std::nullopt)
, _launch(selectionSetParams.launch)
, _fragments(fragments)
, _variables(variables)
, _typeNames(typeNames)
, _resolvers(resolvers)
, _fragmentDefinitionDirectives { selectionSetParams.fragmentDefinitionDirectives }
, _fragmentSpreadDirectives { selectionSetParams.fragmentSpreadDirectives }
, _inlineFragmentDirectives { selectionSetParams.inlineFragmentDirectives }
{
static const Directives s_emptyFragmentDefinitionDirectives;
// Traversing a SelectionSet from an Object type field should start tracking new fragment
// directives. The outer fragment directives are still there in the FragmentSpreadDirectiveStack
// if the field accessors want to inspect them.
_fragmentDefinitionDirectives->push_front(std::cref(s_emptyFragmentDefinitionDirectives));
_fragmentSpreadDirectives->push_front({});
_inlineFragmentDirectives->push_front({});
_names.reserve(count);
_values.reserve(count);
}
std::vector<SelectionVisitor::VisitorValue> SelectionVisitor::getValues()
{
auto values = std::move(_values);
return values;
}
void SelectionVisitor::visit(const peg::ast_node& selection)
{
if (selection.is_type<peg::field>())
{
visitField(selection);
}
else if (selection.is_type<peg::fragment_spread>())
{
visitFragmentSpread(selection);
}
else if (selection.is_type<peg::inline_fragment>())
{
visitInlineFragment(selection);
}
}
void SelectionVisitor::visitField(const peg::ast_node& field)
{
std::string_view name;
peg::on_first_child<peg::field_name>(field, [&name](const peg::ast_node& child) {
name = child.string_view();
});
std::string_view alias;
peg::on_first_child<peg::alias_name>(field, [&alias](const peg::ast_node& child) {
alias = child.string_view();
});
if (alias.empty())
{
alias = name;
}
if (!_names.emplace(alias).second)
{
// Skip resolving fields which map to the same response name as a field we've already
// resolved. Validation should handle merging multiple references to the same field or
// to compatible fields.