-
Notifications
You must be signed in to change notification settings - Fork 25
/
sub-resolver.go
195 lines (176 loc) · 5.3 KB
/
sub-resolver.go
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
package gqlserver
import (
"maps"
"reflect"
"time"
"github.com/graphql-go/graphql"
"github.com/usnistgov/ndn-dpdk/core/nnduration"
"github.com/usnistgov/ndn-dpdk/core/subtract"
)
// PublishChan publishes a channel in reply to GraphQL subscription.
//
// f is a callback function that sends its results into a channel.
// It should not close the channel - the channel will be closed by the caller when f returns.
func PublishChan(f func(updates chan<- any)) (any, error) {
updates := make(chan any)
go func() {
defer close(updates)
f(updates)
}()
return updates, nil
}
var (
subArgInterval = graphql.FieldConfigArgument{
"interval": &graphql.ArgumentConfig{
Description: "Interval between updates.",
Type: nnduration.GqlNanoseconds,
DefaultValue: nnduration.Nanoseconds(time.Second),
},
}
subArgDiff = graphql.FieldConfigArgument{
"diff": &graphql.ArgumentConfig{
Description: "Report value difference since last update instead of accumulative total.",
Type: graphql.Boolean,
DefaultValue: false,
},
}
)
// PublishInterval publishes results at an interval in reply to GraphQL subscription.
//
// read is a callback function that returns a single result.
// enders are channels that indicate the subscription should be canceled, when a value is received or the channel is closed.
func PublishInterval(p graphql.ResolveParams, read graphql.FieldResolveFn, enders ...any) (results any, e error) {
interval := p.Args["interval"].(nnduration.Nanoseconds).Duration()
diff := false
var prev any
if diffB, ok := p.Args["diff"].(bool); ok && diffB {
diff = true
if prev, e = read(p); e != nil || prev == nil {
return nil, e
}
}
return PublishChan(func(updates chan<- any) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
cont := true
doUpdate := func() {
value, e := read(p)
switch {
case e != nil, value == nil:
cont = false
case diff:
updates <- subtract.Sub(value, prev)
prev = value
case !diff:
updates <- value
}
}
if len(enders) == 0 {
for cont {
select {
case <-ticker.C:
doUpdate()
case <-p.Context.Done():
return
}
}
}
cases := []reflect.SelectCase{
{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ticker.C)},
{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(p.Context.Done())},
}
for _, ender := range enders {
cases = append(cases, reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ender)})
}
for cont {
if i, _, _ := reflect.Select(cases); i != 0 {
return
}
doUpdate()
}
})
}
func init() {
AddSubscription(&graphql.Field{
Name: "tick",
Description: "time.Ticker subscription for testing subscription implementations.",
Type: NonNullInt,
Args: subArgInterval,
Subscribe: func(p graphql.ResolveParams) (any, error) {
n := 0
return PublishInterval(p, func(graphql.ResolveParams) (any, error) {
n++
return n, nil
})
},
})
}
// CountersConfig contains options to publish a counters-like type.
type CountersConfig struct {
Description string
// Parent is the parent object to define a query field.
// If nil, no query field is defined.
Parent *graphql.Object
// Name is the field name to be defined in Parent.
// If empty, no query field is defined.
Name string
// Subscription is the field name to be defined as subscription.
// If empty, no subscription is defined.
Subscription string
// NoDiff indicates diff=true is not supported.
// This should be set if some fields are lazily-injected with FieldResolveFn, as subtract algorithm cannot see them.
NoDiff bool
// FindArgs declares GraphQL arguments for finding the source object.
FindArgs graphql.FieldConfigArgument
// Find finds source object from FindArgs in a subscription.
// p.Source is unspecified.
// p.Args contains arguments declared in both Args and FindArgs.
// enders: see PublishInterval.
Find func(p graphql.ResolveParams) (source any, enders []any, e error)
// Type declares GraphQL return type.
Type graphql.Output
// Args declares GraphQL arguments for customizing counters.
Args graphql.FieldConfigArgument
// Read retrieves counters from p.Source.
// p.Source is a value from Parent or a return value from Find.
// p.Args contains arguments declared in Args.
Read graphql.FieldResolveFn
}
func (cfg CountersConfig) subscribe(p graphql.ResolveParams) (any, error) {
source, enders, e := cfg.Find(p)
if e != nil {
return nil, e
}
if val := reflect.ValueOf(source); !val.IsValid() || val.IsZero() {
return nil, nil
}
p.Source = source
return PublishInterval(p, cfg.Read, enders...)
}
// AddCounters defines a counters-like field as both a query field and a subscription.
func AddCounters(cfg *CountersConfig) {
if cfg.Parent != nil && cfg.Name != "" {
cfg.Parent.AddFieldConfig(cfg.Name, &graphql.Field{
Description: cfg.Description,
Args: cfg.Args,
Type: cfg.Type,
Resolve: cfg.Read,
})
}
if cfg.Subscription != "" {
args := graphql.FieldConfigArgument{}
maps.Copy(args, cfg.Args)
maps.Copy(args, cfg.FindArgs)
maps.Copy(args, subArgInterval)
if !cfg.NoDiff {
maps.Copy(args, subArgDiff)
}
AddSubscription(&graphql.Field{
Name: cfg.Subscription,
Description: cfg.Description,
Args: args,
Type: cfg.Type,
Subscribe: cfg.subscribe,
})
}
}