-
Notifications
You must be signed in to change notification settings - Fork 46
/
GraphQLService.h
1529 lines (1261 loc) · 51.2 KB
/
GraphQLService.h
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.
#pragma once
#ifndef GRAPHQLSERVICE_H
#define GRAPHQLSERVICE_H
// clang-format off
#ifdef GRAPHQL_DLLEXPORTS
#ifdef IMPL_GRAPHQLSERVICE_DLL
#define GRAPHQLSERVICE_EXPORT __declspec(dllexport)
#else // !IMPL_GRAPHQLSERVICE_DLL
#define GRAPHQLSERVICE_EXPORT __declspec(dllimport)
#endif // !IMPL_GRAPHQLSERVICE_DLL
#else // !GRAPHQL_DLLEXPORTS
#define GRAPHQLSERVICE_EXPORT
#endif // !GRAPHQL_DLLEXPORTS
// clang-format on
#include "graphqlservice/GraphQLParse.h"
#include "graphqlservice/GraphQLResponse.h"
#include "graphqlservice/internal/Awaitable.h"
#include "graphqlservice/internal/SortedMap.h"
#include "graphqlservice/internal/Version.h"
#include <chrono>
#include <condition_variable>
#include <functional>
#include <future>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <thread>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
namespace graphql {
namespace schema {
class Schema;
} // namespace schema
namespace service {
// Errors should have a message string, and optional locations and a path.
struct [[nodiscard("unnecessary construction")]] schema_location
{
size_t line = 0;
size_t column = 1;
};
// The implementation details of the error path should be opaque to client code. It is carried along
// with the SelectionSetParams and automatically added to any schema errors or exceptions thrown
// from an accessor as part of error reporting.
using path_segment = std::variant<std::string_view, size_t>;
struct [[nodiscard("unnecessary construction")]] field_path
{
std::optional<std::reference_wrapper<const field_path>> parent;
std::variant<std::string_view, size_t> segment;
};
using error_path = std::vector<path_segment>;
[[nodiscard("unnecessary memory copy")]] GRAPHQLSERVICE_EXPORT error_path buildErrorPath(
const std::optional<field_path>& path);
struct [[nodiscard("unnecessary construction")]] schema_error
{
std::string message;
schema_location location {};
error_path path {};
};
[[nodiscard("unnecessary memory copy")]] GRAPHQLSERVICE_EXPORT response::Value buildErrorValues(
std::list<schema_error>&& structuredErrors);
// This exception bubbles up 1 or more error messages to the JSON results.
class [[nodiscard("unnecessary construction")]] schema_exception : public std::exception
{
public:
GRAPHQLSERVICE_EXPORT explicit schema_exception(std::list<schema_error>&& structuredErrors);
GRAPHQLSERVICE_EXPORT explicit schema_exception(std::vector<std::string>&& messages);
schema_exception() = delete;
[[nodiscard("unnecessary conversion")]] GRAPHQLSERVICE_EXPORT const char* what()
const noexcept override;
[[nodiscard("unnecessary construction")]] GRAPHQLSERVICE_EXPORT std::list<schema_error>
getStructuredErrors() noexcept;
[[nodiscard("unnecessary conversion")]] GRAPHQLSERVICE_EXPORT response::Value getErrors();
private:
[[nodiscard("unnecessary construction")]] static std::list<schema_error> convertMessages(
std::vector<std::string>&& messages) noexcept;
std::list<schema_error> _structuredErrors;
};
// This exception is thrown when an generated stub is called for an unimplemented method.
class [[nodiscard("unnecessary construction")]] unimplemented_method : public std::runtime_error
{
public:
GRAPHQLSERVICE_EXPORT explicit unimplemented_method(std::string_view methodName);
unimplemented_method() = delete;
private:
[[nodiscard("unnecessary construction")]] static std::string getMessage(
std::string_view methodName) noexcept;
};
// The RequestState is nullable, but if you have multiple threads processing requests and there's
// any per-request state that you want to maintain throughout the request (e.g. optimizing or
// batching backend requests), you can inherit from RequestState and pass it to Request::resolve to
// correlate the asynchronous/recursive callbacks and accumulate state in it.
struct [[nodiscard("unnecessary construction")]] RequestState
: std::enable_shared_from_this<RequestState>
{
virtual ~RequestState() = default;
};
inline namespace keywords {
using namespace std::literals;
constexpr std::string_view strData { "data"sv };
constexpr std::string_view strErrors { "errors"sv };
constexpr std::string_view strMessage { "message"sv };
constexpr std::string_view strLocations { "locations"sv };
constexpr std::string_view strLine { "line"sv };
constexpr std::string_view strColumn { "column"sv };
constexpr std::string_view strPath { "path"sv };
constexpr std::string_view strQuery { "query"sv };
constexpr std::string_view strMutation { "mutation"sv };
constexpr std::string_view strSubscription { "subscription"sv };
} // namespace keywords
// Resolvers may be called in multiple different Operation contexts.
enum class [[nodiscard("unnecessary conversion")]] ResolverContext {
// Resolving a Query operation.
Query,
// Resolving a Mutation operation.
Mutation,
// Adding a Subscription. If you need to prepare to send events for this Subsciption
// (e.g. registering an event sink of your own), this is a chance to do that.
NotifySubscribe,
// Resolving a Subscription event.
Subscription,
// Removing a Subscription. If there are no more Subscriptions registered this is an
// opportunity to release resources which are no longer needed.
NotifyUnsubscribe,
};
// Resume coroutine execution on a new worker thread any time co_await is called. This emulates the
// behavior of std::async when passing std::launch::async.
struct [[nodiscard("unnecessary construction")]] await_worker_thread : coro::suspend_always
{
GRAPHQLSERVICE_EXPORT void await_suspend(coro::coroutine_handle<> h) const;
};
// Queue coroutine execution on a single dedicated worker thread any time co_await is called from
// the thread which created it.
struct [[nodiscard("unnecessary construction")]] await_worker_queue : coro::suspend_always
{
GRAPHQLSERVICE_EXPORT await_worker_queue();
GRAPHQLSERVICE_EXPORT ~await_worker_queue();
[[nodiscard("unexpected call")]] GRAPHQLSERVICE_EXPORT bool await_ready() const;
GRAPHQLSERVICE_EXPORT void await_suspend(coro::coroutine_handle<> h);
private:
void resumePending();
const std::thread::id _startId;
std::mutex _mutex {};
std::condition_variable _cv {};
std::list<coro::coroutine_handle<>> _pending {};
bool _shutdown = false;
std::thread _worker;
};
// Type-erased awaitable.
class [[nodiscard("unnecessary construction")]] await_async final
{
private:
struct [[nodiscard("unnecessary construction")]] Concept
{
virtual ~Concept() = default;
[[nodiscard("unexpected call")]] virtual bool await_ready() const = 0;
virtual void await_suspend(coro::coroutine_handle<> h) const = 0;
virtual void await_resume() const = 0;
};
template <class T>
struct [[nodiscard("unnecessary construction")]] Model : Concept
{
explicit Model(std::shared_ptr<T> pimpl) noexcept
: _pimpl { std::move(pimpl) }
{
}
[[nodiscard("unexpected call")]] bool await_ready() const final
{
return _pimpl->await_ready();
}
void await_suspend(coro::coroutine_handle<> h) const final
{
_pimpl->await_suspend(std::move(h));
}
void await_resume() const final
{
_pimpl->await_resume();
}
private:
std::shared_ptr<T> _pimpl;
};
const std::shared_ptr<const Concept> _pimpl;
public:
// Type-erased explicit constructor for a custom awaitable.
template <class T>
explicit await_async(std::shared_ptr<T> pimpl) noexcept
: _pimpl { std::make_shared<Model<T>>(std::move(pimpl)) }
{
}
// Default to immediate synchronous execution.
GRAPHQLSERVICE_EXPORT await_async();
// Implicitly convert a std::launch parameter used with std::async to an awaitable.
GRAPHQLSERVICE_EXPORT await_async(std::launch launch);
[[nodiscard("unexpected call")]] GRAPHQLSERVICE_EXPORT bool await_ready() const;
GRAPHQLSERVICE_EXPORT void await_suspend(coro::coroutine_handle<> h) const;
GRAPHQLSERVICE_EXPORT void await_resume() const;
};
// Directive order matters, and some of them are repeatable. So rather than passing them in a
// response::Value, pass directives in something like the underlying response::MapType which
// preserves the order of the elements without complete uniqueness.
using Directives = std::vector<std::pair<std::string_view, response::Value>>;
// Traversing a fragment spread adds a new set of directives.
using FragmentDefinitionDirectiveStack = std::list<std::reference_wrapper<const Directives>>;
using FragmentSpreadDirectiveStack = std::list<Directives>;
// Pass a common bundle of parameters to all of the generated Object::getField accessors in a
// SelectionSet
struct [[nodiscard("unnecessary construction")]] SelectionSetParams
{
// Context for this selection set.
const ResolverContext resolverContext;
// The lifetime of each of these borrowed references is guaranteed until the future returned
// by the accessor is resolved or destroyed. They are owned by the OperationData shared pointer.
const std::shared_ptr<RequestState>& state;
const Directives& operationDirectives;
const std::shared_ptr<FragmentDefinitionDirectiveStack> fragmentDefinitionDirectives;
// Fragment directives are shared for all fields in that fragment, but they aren't kept alive
// after the call to the last accessor in the fragment. If you need to keep them alive longer,
// you'll need to explicitly copy them into other instances of Directives.
const std::shared_ptr<FragmentSpreadDirectiveStack> fragmentSpreadDirectives;
const std::shared_ptr<FragmentSpreadDirectiveStack> inlineFragmentDirectives;
// Field error path to this selection set.
std::optional<field_path> errorPath;
// Async launch policy for sub-field resolvers.
const await_async launch {};
};
// Pass a common bundle of parameters to all of the generated Object::getField accessors.
struct [[nodiscard("unnecessary construction")]] FieldParams : SelectionSetParams
{
GRAPHQLSERVICE_EXPORT explicit FieldParams(
SelectionSetParams&& selectionSetParams, Directives directives);
// Each field owns its own field-specific directives. Once the accessor returns it will be
// destroyed, but you can move it into another instance of response::Value to keep it alive
// longer.
Directives fieldDirectives;
};
// Field accessors may return either a result of T, an awaitable of T, or a std::future<T>, so at
// runtime the implementer may choose to return by value or defer/parallelize expensive operations
// by returning an async future or an awaitable coroutine.
//
// If the overhead of conversion to response::Value is too expensive, scalar type field accessors
// can store and return a std::shared_ptr<const response::Value> directly.
template <typename T>
class [[nodiscard("unnecessary construction")]] AwaitableScalar
{
public:
template <typename U>
AwaitableScalar(U&& value)
: _value { std::forward<U>(value) }
{
}
struct promise_type
{
[[nodiscard("unnecessary construction")]] AwaitableScalar<T> get_return_object() noexcept
{
return { _promise.get_future() };
}
coro::suspend_never initial_suspend() const noexcept
{
return {};
}
coro::suspend_never final_suspend() const noexcept
{
return {};
}
void return_value(const T& value) noexcept(std::is_nothrow_copy_constructible_v<T>)
{
_promise.set_value(value);
}
void return_value(T&& value) noexcept(std::is_nothrow_move_constructible_v<T>)
{
_promise.set_value(std::move(value));
}
void unhandled_exception() noexcept
{
_promise.set_exception(std::current_exception());
}
private:
std::promise<T> _promise;
};
[[nodiscard("unexpected call")]] bool await_ready() const noexcept
{
return std::visit(
[](const auto& value) noexcept {
using value_type = std::decay_t<decltype(value)>;
if constexpr (std::is_same_v<value_type, T>)
{
return true;
}
else if constexpr (std::is_same_v<value_type, std::future<T>>)
{
using namespace std::literals;
return value.wait_for(0s) != std::future_status::timeout;
}
else if constexpr (std::is_same_v<value_type,
std::shared_ptr<const response::Value>>)
{
return true;
}
},
_value);
}
void await_suspend(coro::coroutine_handle<> h) const
{
std::thread(
[this](coro::coroutine_handle<> h) noexcept {
std::get<std::future<T>>(_value).wait();
h.resume();
},
std::move(h))
.detach();
}
[[nodiscard("unnecessary construction")]] T await_resume()
{
return std::visit(
[](auto&& value) -> T {
using value_type = std::decay_t<decltype(value)>;
if constexpr (std::is_same_v<value_type, T>)
{
return T { std::move(value) };
}
else if constexpr (std::is_same_v<value_type, std::future<T>>)
{
return value.get();
}
else if constexpr (std::is_same_v<value_type,
std::shared_ptr<const response::Value>>)
{
throw std::logic_error("Cannot await std::shared_ptr<const response::Value>");
}
},
std::move(_value));
}
[[nodiscard("unnecessary construction")]] std::shared_ptr<const response::Value>
get_value() noexcept
{
return std::visit(
[](auto&& value) noexcept {
using value_type = std::decay_t<decltype(value)>;
std::shared_ptr<const response::Value> result;
if constexpr (std::is_same_v<value_type, std::shared_ptr<const response::Value>>)
{
result = std::move(value);
}
return result;
},
std::move(_value));
}
private:
std::variant<T, std::future<T>, std::shared_ptr<const response::Value>> _value;
};
// Field accessors may return either a result of T, an awaitable of T, or a std::future<T>, so at
// runtime the implementer may choose to return by value or defer/parallelize expensive operations
// by returning an async future or an awaitable coroutine.
template <typename T>
class [[nodiscard("unnecessary construction")]] AwaitableObject
{
public:
template <typename U>
AwaitableObject(U&& value)
: _value { std::forward<U>(value) }
{
}
struct promise_type
{
[[nodiscard("unnecessary construction")]] AwaitableObject<T> get_return_object() noexcept
{
return { _promise.get_future() };
}
coro::suspend_never initial_suspend() const noexcept
{
return {};
}
coro::suspend_never final_suspend() const noexcept
{
return {};
}
void return_value(const T& value) noexcept(std::is_nothrow_copy_constructible_v<T>)
{
_promise.set_value(value);
}
void return_value(T&& value) noexcept(std::is_nothrow_move_constructible_v<T>)
{
_promise.set_value(std::move(value));
}
void unhandled_exception() noexcept
{
_promise.set_exception(std::current_exception());
}
private:
std::promise<T> _promise;
};
[[nodiscard("unexpected call")]] bool await_ready() const noexcept
{
return std::visit(
[](const auto& value) noexcept {
using value_type = std::decay_t<decltype(value)>;
if constexpr (std::is_same_v<value_type, T>)
{
return true;
}
else if constexpr (std::is_same_v<value_type, std::future<T>>)
{
using namespace std::literals;
return value.wait_for(0s) != std::future_status::timeout;
}
},
_value);
}
void await_suspend(coro::coroutine_handle<> h) const
{
std::thread(
[this](coro::coroutine_handle<> h) noexcept {
std::get<std::future<T>>(_value).wait();
h.resume();
},
std::move(h))
.detach();
}
[[nodiscard("unnecessary construction")]] T await_resume()
{
return std::visit(
[](auto&& value) -> T {
using value_type = std::decay_t<decltype(value)>;
if constexpr (std::is_same_v<value_type, T>)
{
return T { std::move(value) };
}
else if constexpr (std::is_same_v<value_type, std::future<T>>)
{
return value.get();
}
},
std::move(_value));
}
private:
std::variant<T, std::future<T>> _value;
};
// Fragments are referenced by name and have a single type condition (except for inline
// fragments, where the type condition is common but optional). They contain a set of fields
// (with optional aliases and sub-selections) and potentially references to other fragments.
class [[nodiscard("unnecessary construction")]] Fragment
{
public:
explicit Fragment(const peg::ast_node& fragmentDefinition, const response::Value& variables);
[[nodiscard("unnecessary call")]] std::string_view getType() const;
[[nodiscard("unnecessary call")]] const peg::ast_node& getSelection() const;
[[nodiscard("unnecessary call")]] const Directives& getDirectives() const;
private:
std::string_view _type;
Directives _directives;
std::reference_wrapper<const peg::ast_node> _selection;
};
// Resolvers for complex types need to be able to find fragment definitions anywhere in
// the request document by name.
using FragmentMap = internal::string_view_map<Fragment>;
// Resolver functors take a set of arguments encoded as members on a JSON object
// with an optional selection set for complex types and return a JSON value for
// a single field.
struct [[nodiscard("unnecessary construction")]] ResolverParams : SelectionSetParams
{
GRAPHQLSERVICE_EXPORT explicit 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);
[[nodiscard("unnecessary call")]] GRAPHQLSERVICE_EXPORT schema_location getLocation() const;
// These values are different for each resolver.
const peg::ast_node& field;
std::string fieldName;
response::Value arguments { response::Type::Map };
Directives fieldDirectives;
const peg::ast_node* selection;
// These values remain unchanged for the entire operation, but they're passed to each of the
// resolvers recursively through ResolverParams.
const FragmentMap& fragments;
const response::Value& variables;
};
// Propagate data and errors together without bundling them into a response::Value struct until
// we're ready to return from the top level Operation.
struct [[nodiscard("unnecessary construction")]] ResolverResult
{
response::Value data;
std::list<schema_error> errors {};
};
using AwaitableResolver = internal::Awaitable<ResolverResult>;
using Resolver = std::function<AwaitableResolver(ResolverParams&&)>;
using ResolverMap = internal::string_view_map<Resolver>;
// GraphQL types are nullable by default, but they may be wrapped with non-null or list types.
// Since nullability is a more special case in C++, we invert the default and apply that modifier
// instead when the non-null wrapper is not present in that part of the wrapper chain.
enum class [[nodiscard("unnecessary conversion")]] TypeModifier {
None,
Nullable,
List,
};
// Test if there are any non-None modifiers left.
template <TypeModifier... Other>
concept OnlyNoneModifiers = (... && (Other == TypeModifier::None));
// Test if the next modifier is Nullable.
template <TypeModifier Modifier>
concept NullableModifier = Modifier == TypeModifier::Nullable;
// Test if the next modifier is List.
template <TypeModifier Modifier>
concept ListModifier = Modifier == TypeModifier::List;
// Convert arguments and input types with a non-templated static method.
template <typename Type>
struct Argument
{
// Convert a single value to the specified type.
[[nodiscard("unnecessary conversion")]] static Type convert(const response::Value& value);
};
#ifdef GRAPHQL_DLLEXPORTS
// Export all of the built-in converters
template <>
GRAPHQLSERVICE_EXPORT int Argument<int>::convert(const response::Value& value);
template <>
GRAPHQLSERVICE_EXPORT double Argument<double>::convert(const response::Value& value);
template <>
GRAPHQLSERVICE_EXPORT std::string Argument<std::string>::convert(const response::Value& value);
template <>
GRAPHQLSERVICE_EXPORT bool Argument<bool>::convert(const response::Value& value);
template <>
GRAPHQLSERVICE_EXPORT response::IdType Argument<response::IdType>::convert(
const response::Value& value);
template <>
GRAPHQLSERVICE_EXPORT response::Value Argument<response::Value>::convert(
const response::Value& value);
#endif // GRAPHQL_DLLEXPORTS
namespace {
// These types are used as scalar arguments even though they are represented with a class.
template <typename Type>
concept ScalarArgumentClass = std::is_same_v<Type, std::string>
|| std::is_same_v<Type, response::IdType> || std::is_same_v<Type, response::Value>;
// Any non-scalar class used in an argument is a generated INPUT_OBJECT type.
template <typename Type>
concept InputArgumentClass = std::is_class_v<Type> && !ScalarArgumentClass<Type>;
// Special-case an innermost nullable INPUT_OBJECT type.
template <typename Type, TypeModifier... Other>
concept InputArgumentUniquePtr = InputArgumentClass<Type> && OnlyNoneModifiers<Other...>;
// Extract individual arguments with chained type modifiers which add nullable or list wrappers.
// If the argument is not optional, use require and let it throw a schema_exception when the
// argument is missing or not the correct type. If it's optional, use find and check the second
// element in the pair to see if it was found or if you just got the default value for that type.
template <typename Type>
struct ModifiedArgument
{
// Peel off modifiers until we get to the underlying type.
template <typename U, TypeModifier Modifier = TypeModifier::None, TypeModifier... Other>
struct ArgumentTraits
{
// Peel off modifiers until we get to the underlying type.
using type = typename std::conditional_t<TypeModifier::Nullable == Modifier,
typename std::conditional_t<InputArgumentUniquePtr<U, Other...>, std::unique_ptr<U>,
std::optional<typename ArgumentTraits<U, Other...>::type>>,
typename std::conditional_t<TypeModifier::List == Modifier,
std::vector<typename ArgumentTraits<U, Other...>::type>, U>>;
};
template <typename U>
struct ArgumentTraits<U, TypeModifier::None>
{
using type = U;
};
// Call convert on this type without any modifiers.
[[nodiscard("unnecessary call")]] static Type require(
std::string_view name, const response::Value& arguments)
{
try
{
return Argument<Type>::convert(arguments[name]);
}
catch (schema_exception& ex)
{
auto errors = ex.getStructuredErrors();
for (auto& error : errors)
{
std::ostringstream message;
message << "Invalid argument: " << name << " error: " << error.message;
error.message = message.str();
}
throw schema_exception(std::move(errors));
}
}
// Wrap require in a try/catch block.
[[nodiscard("unnecessary call")]] static std::pair<Type, bool> find(
const std::string& name, const response::Value& arguments) noexcept
{
try
{
return { require(name, arguments), true };
}
catch (const std::exception&)
{
return { Type {}, false };
}
}
// Peel off the none modifier. If it's included, it should always be last in the list.
template <TypeModifier Modifier = TypeModifier::None, TypeModifier... Other>
[[nodiscard("unnecessary call")]] static Type require(
std::string_view name, const response::Value& arguments)
requires OnlyNoneModifiers<Modifier, Other...>
{
static_assert(sizeof...(Other) == 0, "None modifier should always be last");
// Just call through to the non-template method without the modifiers.
return require(name, arguments);
}
// Peel off nullable modifiers.
template <TypeModifier Modifier, TypeModifier... Other>
[[nodiscard("unnecessary call")]] static typename ArgumentTraits<Type, Modifier, Other...>::type
require(std::string_view name, const response::Value& arguments)
requires NullableModifier<Modifier>
{
const auto& valueItr = arguments.find(name);
if (valueItr == arguments.get<response::MapType>().cend()
|| valueItr->second.type() == response::Type::Null)
{
return {};
}
auto result = require<Other...>(name, arguments);
if constexpr (InputArgumentUniquePtr<Type, Other...>)
{
return std::make_unique<decltype(result)>(std::move(result));
}
else
{
return std::make_optional<decltype(result)>(std::move(result));
}
}
// Peel off list modifiers.
template <TypeModifier Modifier, TypeModifier... Other>
[[nodiscard("unnecessary call")]] static typename ArgumentTraits<Type, Modifier, Other...>::type
require(std::string_view name, const response::Value& arguments)
requires ListModifier<Modifier>
{
const auto& values = arguments[name];
typename ArgumentTraits<Type, Modifier, Other...>::type result(values.size());
const auto& elements = values.get<response::ListType>();
std::transform(elements.cbegin(),
elements.cend(),
result.begin(),
[name](const response::Value& element) {
response::Value single(response::Type::Map);
single.emplace_back(std::string { name }, response::Value(element));
return require<Other...>(name, single);
});
return result;
}
// Wrap require with modifiers in a try/catch block.
template <TypeModifier Modifier = TypeModifier::None, TypeModifier... Other>
[[nodiscard("unnecessary call")]] static std::pair<
typename ArgumentTraits<Type, Modifier, Other...>::type, bool>
find(std::string_view name, const response::Value& arguments) noexcept
{
try
{
return { require<Modifier, Other...>(name, arguments), true };
}
catch (const std::exception&)
{
return { typename ArgumentTraits<Type, Modifier, Other...>::type {}, false };
}
}
// Peel off the none modifier. If it's included, it should always be last in the list.
template <TypeModifier Modifier = TypeModifier::None, TypeModifier... Other>
[[nodiscard("unnecessary memory copy")]] static Type duplicate(const Type& value)
requires OnlyNoneModifiers<Modifier, Other...>
{
// Just copy the value.
return Type { value };
}
// Peel off nullable modifiers.
template <TypeModifier Modifier, TypeModifier... Other>
[[nodiscard("unnecessary memory copy")]] static
typename ArgumentTraits<Type, Modifier, Other...>::type
duplicate(const typename ArgumentTraits<Type, Modifier, Other...>::type& nullableValue)
requires NullableModifier<Modifier>
{
typename ArgumentTraits<Type, Modifier, Other...>::type result {};
if (nullableValue)
{
if constexpr (InputArgumentUniquePtr<Type, Other...>)
{
// Special case duplicating the std::unique_ptr.
result = std::make_unique<Type>(Type { *nullableValue });
}
else
{
result = duplicate<Other...>(*nullableValue);
}
}
return result;
}
// Peel off list modifiers.
template <TypeModifier Modifier, TypeModifier... Other>
[[nodiscard("unnecessary memory copy")]] static
typename ArgumentTraits<Type, Modifier, Other...>::type
duplicate(const typename ArgumentTraits<Type, Modifier, Other...>::type& listValue)
requires ListModifier<Modifier>
{
typename ArgumentTraits<Type, Modifier, Other...>::type result(listValue.size());
std::transform(listValue.cbegin(), listValue.cend(), result.begin(), duplicate<Other...>);
return result;
}
};
// Convenient type aliases for testing, generated code won't actually use these. These are also
// the specializations which are implemented in the GraphQLService library, other specializations
// for input types should be generated in schemagen.
using IntArgument = ModifiedArgument<int>;
using FloatArgument = ModifiedArgument<double>;
using StringArgument = ModifiedArgument<std::string>;
using BooleanArgument = ModifiedArgument<bool>;
using IdArgument = ModifiedArgument<response::IdType>;
using ScalarArgument = ModifiedArgument<response::Value>;
} // namespace
// Each type should handle fragments with type conditions matching its own
// name and any inheritted interfaces.
using TypeNames = internal::string_view_set;
// Object parses argument values, performs variable lookups, expands fragments, evaluates @include
// and @skip directives, and calls through to the resolver functor for each selected field with
// its arguments. This may be a recursive process for fields which return another complex type,
// in which case it requires its own selection set.
class [[nodiscard("unnecessary construction")]] Object : public std::enable_shared_from_this<Object>
{
public:
GRAPHQLSERVICE_EXPORT explicit Object(TypeNames&& typeNames, ResolverMap&& resolvers) noexcept;
GRAPHQLSERVICE_EXPORT virtual ~Object() = default;
[[nodiscard("unnecessary call")]] GRAPHQLSERVICE_EXPORT AwaitableResolver resolve(
const SelectionSetParams& selectionSetParams, const peg::ast_node& selection,
const FragmentMap& fragments, const response::Value& variables) const;
[[nodiscard("unnecessary call")]] GRAPHQLSERVICE_EXPORT bool matchesType(
std::string_view typeName) const;
protected:
// These callbacks are optional, you may override either, both, or neither of them. The
// implementer can use these to to accumulate state for the entire SelectionSet on this object,
// as well as testing directives which were included at the operation or fragment level. It's up
// to sub-classes to decide if they want to use const_cast, mutable members, or separate storage
// in the RequestState to accumulate state. By default these callbacks should treat the Object
// itself as const.
GRAPHQLSERVICE_EXPORT virtual void beginSelectionSet(const SelectionSetParams& params) const;
GRAPHQLSERVICE_EXPORT virtual void endSelectionSet(const SelectionSetParams& params) const;
mutable std::mutex _resolverMutex {};
private:
TypeNames _typeNames;
ResolverMap _resolvers;
};
// Test if this Type inherits from Object.
template <typename Type>
concept ObjectBaseType = std::is_base_of_v<Object, Type>;
// Convert result types with non-templated static methods.
template <typename Type>
struct Result
{
using future_type = typename std::conditional_t<ObjectBaseType<Type>,
AwaitableObject<std::shared_ptr<const Object>>, AwaitableScalar<Type>>;
// Convert a single value of the specified type to JSON.
[[nodiscard("unnecessary conversion")]] static AwaitableResolver convert(
future_type result, ResolverParams&& params);
// Validate a single scalar value is the expected type.
static void validateScalar(const response::Value& value);
};
#ifdef GRAPHQL_DLLEXPORTS
// Export all of the built-in converters
template <>
GRAPHQLSERVICE_EXPORT AwaitableResolver Result<int>::convert(
AwaitableScalar<int> result, ResolverParams&& params);
template <>
GRAPHQLSERVICE_EXPORT AwaitableResolver Result<double>::convert(
AwaitableScalar<double> result, ResolverParams&& params);
template <>
GRAPHQLSERVICE_EXPORT AwaitableResolver Result<std::string>::convert(
AwaitableScalar<std::string> result, ResolverParams&& params);
template <>
GRAPHQLSERVICE_EXPORT AwaitableResolver Result<bool>::convert(
AwaitableScalar<bool> result, ResolverParams&& params);
template <>
GRAPHQLSERVICE_EXPORT AwaitableResolver Result<response::IdType>::convert(
AwaitableScalar<response::IdType> result, ResolverParams&& params);
template <>
GRAPHQLSERVICE_EXPORT AwaitableResolver Result<response::Value>::convert(
AwaitableScalar<response::Value> result, ResolverParams&& params);
template <>
GRAPHQLSERVICE_EXPORT AwaitableResolver Result<Object>::convert(
AwaitableObject<std::shared_ptr<const Object>> result, ResolverParams&& params);
// Export all of the scalar value validation methods
template <>
GRAPHQLSERVICE_EXPORT void Result<int>::validateScalar(const response::Value& value);
template <>
GRAPHQLSERVICE_EXPORT void Result<double>::validateScalar(const response::Value& value);
template <>
GRAPHQLSERVICE_EXPORT void Result<std::string>::validateScalar(const response::Value& value);
template <>
GRAPHQLSERVICE_EXPORT void Result<bool>::validateScalar(const response::Value& value);
template <>
GRAPHQLSERVICE_EXPORT void Result<response::IdType>::validateScalar(const response::Value& value);
template <>
GRAPHQLSERVICE_EXPORT void Result<response::Value>::validateScalar(const response::Value& value);
#endif // GRAPHQL_DLLEXPORTS
namespace {
// Test if this Type is Object.
template <typename Type>
concept ObjectType = std::is_same_v<Object, Type>;
// Test if this Type inherits from Object but is not Object itself.
template <typename Type>
concept ObjectDerivedType = ObjectBaseType<Type> && !ObjectType<Type>;
// Test if a nullable type is std::shared_ptr<Type> or std::optional<T>.
template <typename Type, TypeModifier... Other>
concept NullableSharedPtr = OnlyNoneModifiers<Other...> && ObjectBaseType<Type>;
// Test if this method should std::static_pointer_cast an ObjectDerivedType to
// std::shared_ptr<const Object>.
template <typename Type, TypeModifier Modifier>
concept NoneObjectDerivedType = OnlyNoneModifiers<Modifier> && ObjectDerivedType<Type>;
// Test all other result types to see if they should call the specialized convert method without
// template parameters.
template <typename Type, TypeModifier Modifier>
concept NoneScalarOrObjectType = OnlyNoneModifiers<Modifier> && !ObjectDerivedType<Type>;
// Test if this method should return a nullable std::shared_ptr<Type>
template <typename Type, TypeModifier Modifier, TypeModifier... Other>
concept NullableResultSharedPtr =
NullableModifier<Modifier> && OnlyNoneModifiers<Other...> && ObjectBaseType<Type>;
// Test if this method should return a nullable std::optional<Type>
template <typename Type, TypeModifier Modifier, TypeModifier... Other>
concept NullableResultOptional =
NullableModifier<Modifier> && !(OnlyNoneModifiers<Other...> && ObjectBaseType<Type>);
// Convert the result of a resolver function with chained type modifiers that add nullable or
// list wrappers. This is the inverse of ModifiedArgument for output types instead of input types.
template <typename Type>