-
-
Notifications
You must be signed in to change notification settings - Fork 179
/
api.go
263 lines (216 loc) · 5.86 KB
/
api.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
257
258
259
260
261
262
263
// Package core provides the primary API to include and use GraphJin with your own code.
// For detailed documentation visit https://graphjin.com
//
// Example usage:
/*
package main
import (
"database/sql"
"fmt"
"time"
"github.com/dosco/graphjin/core"
_ "github.com/jackc/pgx/v4/stdlib"
)
func main() {
db, err := sql.Open("pgx", "postgres://postgrs:@localhost:5432/example_db")
if err != nil {
log.Fatal(err)
}
gj, err := core.NewGraphJin(nil, db)
if err != nil {
log.Fatal(err)
}
query := `
query {
posts {
id
title
}
}`
ctx = context.WithValue(ctx, core.UserIDKey, 1)
res, err := gj.GraphQL(ctx, query, nil)
if err != nil {
log.Fatal(err)
}
}
*/
package core
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/json"
"errors"
_log "log"
"os"
"sync"
"github.com/chirino/graphql"
"github.com/dosco/graphjin/core/internal/allow"
"github.com/dosco/graphjin/core/internal/crypto"
"github.com/dosco/graphjin/core/internal/psql"
"github.com/dosco/graphjin/core/internal/qcode"
"github.com/dosco/graphjin/core/internal/sdata"
)
type contextkey int
// Constants to set values on the context passed to the NewGraphJin function
const (
// Name of the authentication provider. Eg. google, github, etc
UserIDProviderKey contextkey = iota
// User ID value for authenticated users
UserIDKey
// User role if pre-defined
UserRoleKey
)
// GraphJin struct is an instance of the GraphJin engine it holds all the required information like
// datase schemas, relationships, etc that the GraphQL to SQL compiler would need to do it's job.
type GraphJin struct {
conf *Config
db *sql.DB
log *_log.Logger
dbtype string
dbinfo *sdata.DBInfo
schema *sdata.DBSchema
allowList *allow.List
encKey [32]byte
queries map[string]*queryComp
roles map[string]*Role
roleStmt string
roleStmtMD psql.Metadata
rmap map[string]resItem
abacEnabled bool
qc *qcode.Compiler
pc *psql.Compiler
ge *graphql.Engine
subs sync.Map
prod bool
}
// NewGraphJin creates the GraphJin struct, this involves querying the database to learn its
// schemas and relationships
func NewGraphJin(conf *Config, db *sql.DB) (*GraphJin, error) {
return newGraphJin(conf, db, nil)
}
// newGraphJin helps with writing tests and benchmarks
func newGraphJin(conf *Config, db *sql.DB, dbinfo *sdata.DBInfo) (*GraphJin, error) {
if conf == nil {
conf = &Config{Debug: true, DisableAllowList: true}
}
gj := &GraphJin{
conf: conf,
db: db,
dbinfo: dbinfo,
log: _log.New(os.Stdout, "", 0),
prod: conf.Production || os.Getenv("GO_ENV") == "production",
}
//order matters, do not re-order the initializers
if err := gj.initConfig(); err != nil {
return nil, err
}
if err := gj.initDiscover(); err != nil {
return nil, err
}
if err := gj.initResolvers(); err != nil {
return nil, err
}
if err := gj.initSchema(); err != nil {
return nil, err
}
if err := gj.initAllowList(); err != nil {
return nil, err
}
if err := gj.initCompilers(); err != nil {
return nil, err
}
if err := gj.initGraphQLEgine(); err != nil {
return nil, err
}
if err := gj.prepareRoleStmt(); err != nil {
return nil, err
}
if conf.SecretKey != "" {
sk := sha256.Sum256([]byte(conf.SecretKey))
conf.SecretKey = ""
gj.encKey = sk
} else {
gj.encKey = crypto.NewEncryptionKey()
}
return gj, nil
}
// Result struct contains the output of the GraphQL function this includes resulting json from the
// database query and any error information
type Result struct {
op qcode.QType
name string
sql string
role string
Error string `json:"message,omitempty"`
Data json.RawMessage `json:"data,omitempty"`
Extensions *extensions `json:"extensions,omitempty"`
}
// ReqConfig is used to pass request specific config values to the GraphQLEx and SubscribeEx functions. Dynamic variables can be set here.
type ReqConfig struct {
Vars map[string]interface{}
}
// GraphQL function is called on the GraphJin struct to convert the provided GraphQL query into an
// SQL query and execute it on the database. In production mode prepared statements are directly used
// and no query compiling takes places.
//
// In developer mode all names queries are saved into a file `allow.list` and in production mode only
// queries from this file can be run.
func (gj *GraphJin) GraphQL(
c context.Context,
query string,
vars json.RawMessage,
rc *ReqConfig) (*Result, error) {
op, name := qcode.GetQType(query)
ct := scontext{
Context: c,
gj: gj,
op: op,
rc: rc,
name: name,
}
res := &Result{
op: ct.op,
name: ct.name,
}
if ct.op == qcode.QTSubscription {
return res, errors.New("use 'core.Subscribe' for subscriptions")
}
if ct.op == qcode.QTMutation && gj.schema.DBType() == "mysql" {
return res, errors.New("mysql: mutations not supported")
}
// use the chirino/graphql library for introspection queries
// disabled when allow list is enforced
if !gj.prod && ct.name == "IntrospectionQuery" {
r := gj.ge.ServeGraphQL(&graphql.Request{Query: query})
res.Data = r.Data
if r.Error() != nil {
res.Error = r.Error().Error()
}
return res, r.Error()
}
var role string
if v, ok := c.Value(UserRoleKey).(string); ok {
role = v
} else if c.Value(UserIDKey) != nil {
role = "user"
} else {
role = "anon"
}
qr, err := ct.execQuery(query, vars, role)
if err != nil {
res.Error = err.Error()
}
if qr.qc != nil {
res.sql = qr.qc.st.sql
}
res.Data = json.RawMessage(qr.data)
res.role = qr.role
return res, err
}
// Operation function return the operation type and name from the query.
// It uses a very fast algorithm to extract the operation without having to parse the query.
func Operation(query string) (OpType, string) {
qt, name := qcode.GetQType(query)
return OpType(qt), name
}