File: context.go

package info (click to toggle)
golang-github-graph-gophers-graphql-go 1.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,516 kB
  • sloc: sh: 373; javascript: 21; makefile: 5
file content (276 lines) | stat: -rw-r--r-- 7,242 bytes parent folder | download
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
// Package selections is for internal use to share selection context between
// the execution engine and the public graphql package without creating an
// import cycle.
//
// The execution layer stores the flattened child selection set for the field
// currently being resolved. The public API converts this into user-friendly
// helpers (SelectedFieldNames, etc.).
package selections

import (
	"context"
	"fmt"
	"reflect"
	"strings"
	"sync"

	"github.com/graph-gophers/graphql-go/decode"
	"github.com/graph-gophers/graphql-go/internal/exec/packer"
	"github.com/graph-gophers/graphql-go/internal/exec/selected"
)

type ctxKey struct{}

// Lazy holds raw selections and computes the flattened, deduped name list once on demand.
type Lazy struct {
	raw     []selected.Selection
	once    sync.Once
	names   []string
	set     map[string]struct{}
	decoded map[string]map[reflect.Type]reflect.Value // path -> type -> value copy
}

// Args returns the argument map for the first occurrence of the provided
// dot-delimited field path under the current resolver. The boolean reports
// if a matching field was found. The returned map MUST NOT be mutated by
// callers (it is the internal map). Paths follow the same format produced by
// SelectedFieldNames (e.g. "books", "books.reviews").
func (l *Lazy) Args(path string) (map[string]interface{}, bool) {
	if l == nil || len(path) == 0 {
		return nil, false
	}
	// Fast path: ensure raw exists.
	for _, sel := range l.raw {
		if m, ok := matchArgsRecursive(sel, path, ""); ok {
			return m, true
		}
	}
	return nil, false
}

func matchArgsRecursive(sel selected.Selection, want, prefix string) (map[string]interface{}, bool) {
	switch s := sel.(type) {
	case *selected.SchemaField:
		name := s.Name
		if len(name) >= 2 && name[:2] == "__" { // skip meta
			return nil, false
		}
		cur := name
		if prefix != "" {
			cur = prefix + "." + name
		}
		if cur == want {
			return s.Args, true
		}
		for _, child := range s.Sels {
			if m, ok := matchArgsRecursive(child, want, cur); ok {
				return m, true
			}
		}
	case *selected.TypeAssertion:
		for _, child := range s.Sels {
			if m, ok := matchArgsRecursive(child, want, prefix); ok {
				return m, true
			}
		}
	case *selected.TypenameField:
		return nil, false
	}
	return nil, false
}

// Names returns the deduplicated child field names computing them once.
func (l *Lazy) Names() []string {
	if l == nil {
		return nil
	}
	l.once.Do(func() {
		seen := make(map[string]struct{}, len(l.raw))
		ordered := make([]string, 0, len(l.raw))
		collectNestedPaths(&ordered, seen, "", l.raw)
		l.names = ordered
		l.set = seen
	})
	out := make([]string, len(l.names))
	copy(out, l.names)
	return out
}

// Has reports if a field name is in the selection list.
func (l *Lazy) Has(name string) bool {
	if l == nil {
		return false
	}
	if l.set == nil { // ensure computed
		_ = l.Names()
	}
	_, ok := l.set[name]
	return ok
}

func collectNestedPaths(dst *[]string, seen map[string]struct{}, prefix string, sels []selected.Selection) {
	for _, sel := range sels {
		switch s := sel.(type) {
		case *selected.SchemaField:
			name := s.Name
			if len(name) >= 2 && name[:2] == "__" {
				continue
			}
			path := name
			if prefix != "" {
				path = prefix + "." + name
			}
			if _, ok := seen[path]; !ok {
				seen[path] = struct{}{}
				*dst = append(*dst, path)
			}
			if len(s.Sels) > 0 {
				collectNestedPaths(dst, seen, path, s.Sels)
			}
		case *selected.TypeAssertion:
			collectNestedPaths(dst, seen, prefix, s.Sels)
		case *selected.TypenameField:
			continue
		}
	}
}

// With stores a lazy wrapper for selections in the context.
func With(ctx context.Context, sels []selected.Selection) context.Context {
	if len(sels) == 0 {
		return ctx
	}
	return context.WithValue(ctx, ctxKey{}, &Lazy{raw: sels})
}

// FromContext retrieves the lazy wrapper (may be nil).
func FromContext(ctx context.Context) *Lazy {
	v, _ := ctx.Value(ctxKey{}).(*Lazy)
	return v
}

// DecodeArgsInto decodes the argument map for the dot path into dst (pointer to struct).
// Returns (true,nil) if decoded, (false,nil) if path missing. Caches per path+type.
func (l *Lazy) DecodeArgsInto(path string, dst interface{}) (bool, error) {
	if l == nil || dst == nil {
		return false, nil
	}
	args, ok := l.Args(path)
	if !ok || len(args) == 0 {
		return false, nil
	}
	rv := reflect.ValueOf(dst)
	if rv.Kind() != reflect.Ptr || rv.IsNil() {
		return false, fmt.Errorf("destination must be non-nil pointer")
	}
	rv = rv.Elem()
	if rv.Kind() != reflect.Struct {
		return false, fmt.Errorf("destination must point to struct")
	}
	rt := rv.Type()
	if l.decoded == nil {
		l.decoded = make(map[string]map[reflect.Type]reflect.Value)
	}
	if m := l.decoded[path]; m != nil {
		if cached, ok := m[rt]; ok {
			rv.Set(cached)
			return true, nil
		}
	}
	// decode
	for i := 0; i < rt.NumField(); i++ {
		sf := rt.Field(i)
		if sf.PkgPath != "" { // unexported
			continue
		}
		name := sf.Tag.Get("graphql")
		if name == "" {
			name = lowerFirst(sf.Name)
		}
		raw, present := args[name]
		if !present || raw == nil {
			continue
		}
		if err := assignArg(rv.Field(i), raw); err != nil {
			return false, fmt.Errorf("arg %s: %w", name, err)
		}
	}
	if l.decoded[path] == nil {
		l.decoded[path] = make(map[reflect.Type]reflect.Value)
	}
	// create a copy to cache so future mutations to dst by caller don't taint cache
	copyVal := reflect.New(rt).Elem()
	copyVal.Set(rv)
	l.decoded[path][rt] = copyVal
	return true, nil
}

func assignArg(dst reflect.Value, src interface{}) error {
	if !dst.IsValid() {
		return nil
	}
	// Support custom scalars implementing decode.Unmarshaler (pointer receiver).
	if dst.CanAddr() {
		if um, ok := dst.Addr().Interface().(decode.Unmarshaler); ok {
			if err := um.UnmarshalGraphQL(src); err != nil {
				return err
			}
			return nil
		}
	}
	switch dst.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.String, reflect.Bool, reflect.Float32, reflect.Float64:
		coerced, err := packer.UnmarshalInput(dst.Type(), src)
		if err != nil {
			return err
		}
		dst.Set(reflect.ValueOf(coerced))
	case reflect.Struct:
		m, ok := src.(map[string]interface{})
		if !ok {
			return fmt.Errorf("expected map for struct, got %T", src)
		}
		for i := 0; i < dst.NumField(); i++ {
			sf := dst.Type().Field(i)
			if sf.PkgPath != "" { // unexported
				continue
			}
			name := sf.Tag.Get("graphql")
			if name == "" {
				name = lowerFirst(sf.Name)
			}
			if v, ok2 := m[name]; ok2 {
				if err := assignArg(dst.Field(i), v); err != nil {
					return err
				}
			}
		}
	case reflect.Slice:
		sv := reflect.ValueOf(src)
		if sv.Kind() != reflect.Slice {
			return fmt.Errorf("cannot convert %T to slice", src)
		}
		out := reflect.MakeSlice(dst.Type(), sv.Len(), sv.Len())
		for i := 0; i < sv.Len(); i++ {
			if err := assignArg(out.Index(i), sv.Index(i).Interface()); err != nil {
				return err
			}
		}
		dst.Set(out)
	case reflect.Ptr:
		if dst.IsNil() {
			dst.Set(reflect.New(dst.Type().Elem()))
		}
		return assignArg(dst.Elem(), src)
	default:
		// silently ignore unsupported kinds
	}
	return nil
}

func lowerFirst(s string) string {
	if s == "" {
		return s
	}
	return strings.ToLower(s[:1]) + s[1:]
}