-
Notifications
You must be signed in to change notification settings - Fork 499
/
graphql_async_client.go
165 lines (150 loc) · 4.82 KB
/
graphql_async_client.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
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package helper
import (
"context"
"fmt"
"github.com/apache/incubator-devlake/plugins/core"
"github.com/merico-dev/graphql"
"sync"
"time"
)
// GraphqlAsyncClient send graphql one by one
type GraphqlAsyncClient struct {
ctx context.Context
cancel context.CancelFunc
client *graphql.Client
logger core.Logger
mu sync.Mutex
waitGroup sync.WaitGroup
workerErrors []error
rateExhaustCond *sync.Cond
rateRemaining int
getRateRemaining func(context.Context, *graphql.Client, core.Logger) (rateRemaining int, resetAt *time.Time, err error)
getRateCost func(q interface{}) int
}
// CreateAsyncGraphqlClient creates a new GraphqlAsyncClient
func CreateAsyncGraphqlClient(
ctx context.Context,
graphqlClient *graphql.Client,
logger core.Logger,
getRateRemaining func(context.Context, *graphql.Client, core.Logger) (rateRemaining int, resetAt *time.Time, err error),
) *GraphqlAsyncClient {
ctxWithCancel, cancel := context.WithCancel(ctx)
graphqlAsyncClient := &GraphqlAsyncClient{
ctx: ctxWithCancel,
cancel: cancel,
client: graphqlClient,
logger: logger,
rateExhaustCond: sync.NewCond(&sync.Mutex{}),
rateRemaining: 0,
getRateRemaining: getRateRemaining,
}
if getRateRemaining != nil {
rateRemaining, resetAt, err := getRateRemaining(ctx, graphqlClient, logger)
if err != nil {
panic(err)
}
graphqlAsyncClient.updateRateRemaining(rateRemaining, resetAt)
}
return graphqlAsyncClient
}
// updateRateRemaining call getRateRemaining to update rateRemaining periodically
func (apiClient *GraphqlAsyncClient) updateRateRemaining(rateRemaining int, resetAt *time.Time) {
apiClient.rateRemaining = rateRemaining
if rateRemaining > 0 {
apiClient.rateExhaustCond.Signal()
}
go func() {
nextDuring := 3 * time.Minute
if resetAt != nil && resetAt.After(time.Now()) {
nextDuring = resetAt.Sub(time.Now())
}
<-time.After(nextDuring)
newRateRemaining, newResetAt, err := apiClient.getRateRemaining(apiClient.ctx, apiClient.client, apiClient.logger)
if err != nil {
panic(err)
}
apiClient.updateRateRemaining(newRateRemaining, newResetAt)
}()
}
// SetGetRateCost to calculate how many rate cost
// if not set, all query just cost 1
func (apiClient *GraphqlAsyncClient) SetGetRateCost(getRateCost func(q interface{}) int) {
apiClient.getRateCost = getRateCost
}
// Query send a graphql request when get lock
func (apiClient *GraphqlAsyncClient) Query(q interface{}, variables map[string]interface{}) error {
apiClient.waitGroup.Add(1)
defer apiClient.waitGroup.Done()
apiClient.mu.Lock()
defer apiClient.mu.Unlock()
apiClient.rateExhaustCond.L.Lock()
defer apiClient.rateExhaustCond.L.Unlock()
for apiClient.rateRemaining <= 0 {
apiClient.logger.Info(`rate limit remaining exhausted, waiting for next period.`)
apiClient.rateExhaustCond.Wait()
}
select {
case <-apiClient.ctx.Done():
return nil
default:
err := apiClient.client.Query(apiClient.ctx, q, variables)
if err != nil {
return err
}
cost := 1
if apiClient.getRateCost != nil {
cost = apiClient.getRateCost(q)
}
apiClient.rateRemaining -= cost
apiClient.logger.Debug(`query cost %d in %v`, cost, variables)
return nil
}
}
// NextTick to return the NextTick of scheduler
func (apiClient *GraphqlAsyncClient) NextTick(task func() error) {
// to make sure task will be enqueued
apiClient.waitGroup.Add(1)
go func() {
defer apiClient.waitGroup.Done()
select {
case <-apiClient.ctx.Done():
return
default:
go func() {
apiClient.checkError(task())
}()
}
}()
}
// WaitAsync blocks until all async requests were done
func (apiClient *GraphqlAsyncClient) Wait() error {
apiClient.waitGroup.Wait()
if len(apiClient.workerErrors) > 0 {
return fmt.Errorf("%s", apiClient.workerErrors)
}
return nil
}
func (apiClient *GraphqlAsyncClient) checkError(err error) {
if err == nil {
return
}
apiClient.workerErrors = append(apiClient.workerErrors, err)
}
// HasError return if any error occurred
func (apiClient *GraphqlAsyncClient) HasError() bool {
return len(apiClient.workerErrors) > 0
}