-
Notifications
You must be signed in to change notification settings - Fork 86
/
client.go
256 lines (220 loc) · 6.7 KB
/
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
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
/*
* Copyright (C) 2023 Dgraph Labs, Inc. and Contributors
*
* Licensed 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 dgo
import (
"context"
"crypto/x509"
"errors"
"fmt"
"math/rand"
"net/url"
"strings"
"sync"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"github.com/dgraph-io/dgo/v240/protos/api"
)
const (
cloudPort = "443"
)
// Dgraph is a transaction aware client to a set of Dgraph server instances.
type Dgraph struct {
jwtMutex sync.RWMutex
jwt api.Jwt
dc []api.DgraphClient
}
type authCreds struct {
token string
}
func (a *authCreds) GetRequestMetadata(ctx context.Context, uri ...string) (
map[string]string, error) {
return map[string]string{"Authorization": a.token}, nil
}
func (a *authCreds) RequireTransportSecurity() bool {
return true
}
// NewDgraphClient creates a new Dgraph (client) for interacting with Alphas.
// The client is backed by multiple connections to the same or different
// servers in a cluster.
//
// A single Dgraph (client) is thread safe for sharing with multiple goroutines.
func NewDgraphClient(clients ...api.DgraphClient) *Dgraph {
dg := &Dgraph{
dc: clients,
}
return dg
}
// DialCloud creates a new TLS connection to a Dgraph Cloud backend
//
// It requires the backend endpoint as well as the api token
// Usage:
// conn, err := grpc.DialCloud("CLOUD_ENDPOINT","API_TOKEN")
// if err != nil {
// log.Fatal(err)
// }
// defer conn.Close()
// dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))
func DialCloud(endpoint, key string) (*grpc.ClientConn, error) {
var grpcHost string
switch {
case strings.Contains(endpoint, ".grpc.") && strings.Contains(endpoint, ":"+cloudPort):
// if we already have the grpc URL with the port, we don't need to do anything
grpcHost = endpoint
case strings.Contains(endpoint, ".grpc.") && !strings.Contains(endpoint, ":"+cloudPort):
// if we have the grpc URL without the port, just add the port
grpcHost = endpoint + ":" + cloudPort
default:
// otherwise, parse the non-grpc URL and add ".grpc." along with port to it.
if !strings.HasPrefix(endpoint, "http") {
endpoint = "https://" + endpoint
}
u, err := url.Parse(endpoint)
if err != nil {
return nil, err
}
urlParts := strings.SplitN(u.Host, ".", 2)
if len(urlParts) < 2 {
return nil, errors.New("invalid URL to Dgraph Cloud")
}
grpcHost = urlParts[0] + ".grpc." + urlParts[1] + ":" + cloudPort
}
pool, err := x509.SystemCertPool()
if err != nil {
return nil, err
}
creds := credentials.NewClientTLSFromCert(pool, "")
return grpc.NewClient(
grpcHost,
grpc.WithTransportCredentials(creds),
grpc.WithPerRPCCredentials(&authCreds{key}),
)
}
func (d *Dgraph) login(ctx context.Context, userid string, password string,
namespace uint64) error {
d.jwtMutex.Lock()
defer d.jwtMutex.Unlock()
dc := d.anyClient()
loginRequest := &api.LoginRequest{
Userid: userid,
Password: password,
Namespace: namespace,
}
resp, err := dc.Login(ctx, loginRequest)
if err != nil {
return err
}
return d.jwt.Unmarshal(resp.Json)
}
// GetJwt returns back the JWT for the dgraph client.
func (d *Dgraph) GetJwt() api.Jwt {
d.jwtMutex.RLock()
defer d.jwtMutex.RUnlock()
return d.jwt
}
// Login logs in the current client using the provided credentials into
// default namespace (0). Valid for the duration the client is alive.
func (d *Dgraph) Login(ctx context.Context, userid string, password string) error {
return d.login(ctx, userid, password, 0)
}
// LoginIntoNamespace logs in the current client using the provided credentials.
// Valid for the duration the client is alive.
func (d *Dgraph) LoginIntoNamespace(ctx context.Context,
userid string, password string, namespace uint64) error {
return d.login(ctx, userid, password, namespace)
}
// Alter can be used to do the following by setting various fields of api.Operation:
// 1. Modify the schema.
// 2. Drop a predicate.
// 3. Drop the database.
func (d *Dgraph) Alter(ctx context.Context, op *api.Operation) error {
dc := d.anyClient()
ctx = d.getContext(ctx)
_, err := dc.Alter(ctx, op)
if isJwtExpired(err) {
err = d.retryLogin(ctx)
if err != nil {
return err
}
ctx = d.getContext(ctx)
_, err = dc.Alter(ctx, op)
}
return err
}
// Relogin relogin the current client using the refresh token. This can be used when the
// access-token gets expired.
func (d *Dgraph) Relogin(ctx context.Context) error {
return d.retryLogin(ctx)
}
func (d *Dgraph) retryLogin(ctx context.Context) error {
d.jwtMutex.Lock()
defer d.jwtMutex.Unlock()
if len(d.jwt.RefreshJwt) == 0 {
return fmt.Errorf("refresh jwt should not be empty")
}
dc := d.anyClient()
loginRequest := &api.LoginRequest{
RefreshToken: d.jwt.RefreshJwt,
}
resp, err := dc.Login(ctx, loginRequest)
if err != nil {
return err
}
return d.jwt.Unmarshal(resp.Json)
}
func (d *Dgraph) getContext(ctx context.Context) context.Context {
d.jwtMutex.RLock()
defer d.jwtMutex.RUnlock()
if len(d.jwt.AccessJwt) > 0 {
md, ok := metadata.FromOutgoingContext(ctx)
if !ok {
// no metadata key is in the context, add one
md = metadata.New(nil)
}
md.Set("accessJwt", d.jwt.AccessJwt)
return metadata.NewOutgoingContext(ctx, md)
}
return ctx
}
// isJwtExpired returns true if the error indicates that the jwt has expired.
func isJwtExpired(err error) bool {
if err == nil {
return false
}
st, ok := status.FromError(err)
return ok && st.Code() == codes.Unauthenticated &&
strings.Contains(err.Error(), "Token is expired")
}
func (d *Dgraph) anyClient() api.DgraphClient {
//nolint:gosec
return d.dc[rand.Intn(len(d.dc))]
}
// DeleteEdges sets the edges corresponding to predicates
// on the node with the given uid for deletion.
// This helper function doesn't run the mutation on the server.
// Txn needs to be committed in order to execute the mutation.
func DeleteEdges(mu *api.Mutation, uid string, predicates ...string) {
for _, predicate := range predicates {
mu.Del = append(mu.Del, &api.NQuad{
Subject: uid,
Predicate: predicate,
// _STAR_ALL is defined as x.Star in x package.
ObjectValue: &api.Value{Val: &api.Value_DefaultVal{DefaultVal: "_STAR_ALL"}},
})
}
}