Skip to content

Commit 0476b00

Browse files
committed
Spread the request context throughout up to db queries.
1 parent 2e1bdee commit 0476b00

File tree

6 files changed

+68
-68
lines changed

6 files changed

+68
-68
lines changed

cmd/go-graphkb/main.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ func logLevelParamToSeverity(level string) logrus.Level {
8282
case "error":
8383
return logrus.ErrorLevel
8484
}
85-
logrus.Fatal("Provided level %s is not a valid option")
85+
logrus.Fatal("Provided level %s is not a valid option", level)
8686
// This should never be reached but needed by the compiler
8787
return logrus.InfoLevel
8888
}
@@ -112,20 +112,20 @@ func onInit() {
112112
}
113113

114114
func count(cmd *cobra.Command, args []string) {
115-
countAssets, err := Database.CountAssets()
115+
countAssets, err := Database.CountAssets(context.Background())
116116
if err != nil {
117117
logrus.Fatal(err)
118118
}
119119

120-
countRelations, err := Database.CountRelations()
120+
countRelations, err := Database.CountRelations(context.Background())
121121
if err != nil {
122122
logrus.Fatal(err)
123123
}
124124
fmt.Printf("%d assets\n%d relations\n", countAssets, countRelations)
125125
}
126126

127127
func flush(cmd *cobra.Command, args []string) {
128-
if err := Database.FlushAll(); err != nil {
128+
if err := Database.FlushAll(context.Background()); err != nil {
129129
logrus.Fatal(err)
130130
}
131131
logrus.Info("Successul flush")
@@ -147,7 +147,7 @@ func listen(cmd *cobra.Command, args []string) {
147147

148148
func read(cmd *cobra.Command, args []string) {
149149
g := knowledge.NewGraph()
150-
err := Database.ReadGraph(args[0], g)
150+
err := Database.ReadGraph(context.Background(), args[0], g)
151151
if err != nil {
152152
logrus.Fatal(err)
153153
}

internal/database/mariadb.go

Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ func hashRelation(relation knowledge.Relation) uint64 {
249249
}
250250

251251
// InsertAssets insert multiple assets into the graph of the given source
252-
func (m *MariaDB) InsertAssets(source string, assets []knowledge.Asset) error {
252+
func (m *MariaDB) InsertAssets(ctx context.Context, source string, assets []knowledge.Asset) error {
253253
sourceID, err := m.resolveSourceID(source)
254254
if err != nil {
255255
return fmt.Errorf("Unable to resolve source ID of source %s for inserting assets: %v", source, err)
@@ -263,7 +263,7 @@ func (m *MariaDB) InsertAssets(source string, assets []knowledge.Asset) error {
263263
for _, asset := range assets {
264264
h := hashAsset(asset)
265265

266-
_, err = tx.ExecContext(context.Background(),
266+
_, err = tx.ExecContext(ctx,
267267
`INSERT INTO assets (id, type, value) VALUES (?, ?, ?)`,
268268
h, asset.Type, asset.Key)
269269
if err != nil {
@@ -275,7 +275,7 @@ func (m *MariaDB) InsertAssets(source string, assets []knowledge.Asset) error {
275275
}
276276
}
277277

278-
_, err = tx.ExecContext(context.Background(),
278+
_, err = tx.ExecContext(ctx,
279279
`INSERT INTO assets_by_source (source_id, asset_id) VALUES (?, ?)`, sourceID, h)
280280
if err != nil {
281281
if driverErr, ok := err.(*mysql.MySQLError); ok && driverErr.Number == mysqlerr.ER_DUP_ENTRY {
@@ -294,7 +294,7 @@ func (m *MariaDB) InsertAssets(source string, assets []knowledge.Asset) error {
294294
}
295295

296296
// InsertRelations upsert one relation into the graph of the given source
297-
func (m *MariaDB) InsertRelations(source string, relations []knowledge.Relation) error {
297+
func (m *MariaDB) InsertRelations(ctx context.Context, source string, relations []knowledge.Relation) error {
298298
sourceID, err := m.resolveSourceID(source)
299299
if err != nil {
300300
return fmt.Errorf("Unable to resolve source ID of source %s for inserting relations: %v", source, err)
@@ -311,7 +311,7 @@ func (m *MariaDB) InsertRelations(source string, relations []knowledge.Relation)
311311
aTo := hashAsset(knowledge.Asset(relation.To))
312312
rH := hashRelation(relation)
313313

314-
_, err = tx.ExecContext(context.Background(),
314+
_, err = tx.ExecContext(ctx,
315315
"INSERT INTO relations (id, from_id, to_id, type) VALUES (?, ?, ?, ?)",
316316
rH, aFrom, aTo, relation.Type)
317317
if err != nil {
@@ -323,7 +323,7 @@ func (m *MariaDB) InsertRelations(source string, relations []knowledge.Relation)
323323
}
324324
}
325325

326-
_, err = tx.ExecContext(context.Background(),
326+
_, err = tx.ExecContext(ctx,
327327
`INSERT INTO relations_by_source (source_id, relation_id) VALUES (?, ?)`, sourceID, rH)
328328
if err != nil {
329329
if driverErr, ok := err.(*mysql.MySQLError); ok && driverErr.Number == mysqlerr.ER_DUP_ENTRY {
@@ -342,7 +342,7 @@ func (m *MariaDB) InsertRelations(source string, relations []knowledge.Relation)
342342
}
343343

344344
// RemoveAssets remove one asset from the graph of the given source
345-
func (m *MariaDB) RemoveAssets(source string, assets []knowledge.Asset) error {
345+
func (m *MariaDB) RemoveAssets(ctx context.Context, source string, assets []knowledge.Asset) error {
346346
sourceID, err := m.resolveSourceID(source)
347347
if err != nil {
348348
return fmt.Errorf("Unable to resolve source ID of source %s for removing assets: %v", source, err)
@@ -356,15 +356,15 @@ func (m *MariaDB) RemoveAssets(source string, assets []knowledge.Asset) error {
356356
for _, asset := range assets {
357357
h := hashAsset(asset)
358358

359-
_, err = tx.ExecContext(context.Background(),
359+
_, err = tx.ExecContext(ctx,
360360
`DELETE FROM assets_by_source WHERE asset_id = ? AND source_id = ?`,
361361
h, sourceID)
362362
if err != nil {
363363
tx.Rollback()
364364
return fmt.Errorf("Unable to remove binding between asset %v (%d) and source %s: %v", asset, h, source, err)
365365
}
366366

367-
_, err = tx.ExecContext(context.Background(),
367+
_, err = tx.ExecContext(ctx,
368368
`DELETE FROM assets WHERE id = ? AND NOT EXISTS (
369369
SELECT * FROM assets_by_source WHERE asset_id = ?
370370
)`,
@@ -383,7 +383,7 @@ func (m *MariaDB) RemoveAssets(source string, assets []knowledge.Asset) error {
383383
}
384384

385385
// RemoveRelations remove relations from the graph of the given source
386-
func (m *MariaDB) RemoveRelations(source string, relations []knowledge.Relation) error {
386+
func (m *MariaDB) RemoveRelations(ctx context.Context, source string, relations []knowledge.Relation) error {
387387
sourceID, err := m.resolveSourceID(source)
388388
if err != nil {
389389
return fmt.Errorf("Unable to resolve source ID of source %s for removing relations: %v", source, err)
@@ -397,19 +397,18 @@ func (m *MariaDB) RemoveRelations(source string, relations []knowledge.Relation)
397397
for _, relation := range relations {
398398
rH := hashRelation(relation)
399399

400-
_, err = tx.ExecContext(context.Background(),
400+
_, err = tx.ExecContext(ctx,
401401
`DELETE FROM relations_by_source WHERE relation_id = ? AND source_id = ?`,
402402
rH, sourceID)
403403
if err != nil {
404404
tx.Rollback()
405405
return fmt.Errorf("Unable to remove binding between relation %v (%d) and source %s: %v", relation, rH, source, err)
406406
}
407407

408-
_, err = tx.ExecContext(context.Background(),
408+
_, err = tx.ExecContext(ctx,
409409
`DELETE FROM relations WHERE id = ? AND NOT EXISTS (
410410
SELECT * FROM relations_by_source WHERE relation_id = ?
411-
)`,
412-
rH, rH)
411+
)`, rH, rH)
413412
if err != nil {
414413
tx.Rollback()
415414
return fmt.Errorf("Unable to remove relation %v (%d) from source %s: %v", relation, rH, source, err)
@@ -423,7 +422,7 @@ func (m *MariaDB) RemoveRelations(source string, relations []knowledge.Relation)
423422
}
424423

425424
// ReadGraph read source subgraph
426-
func (m *MariaDB) ReadGraph(sourceName string, graph *knowledge.Graph) error {
425+
func (m *MariaDB) ReadGraph(ctx context.Context, sourceName string, graph *knowledge.Graph) error {
427426
logrus.Debugf("Start reading graph of data source with name %s", sourceName)
428427
sourceID, err := m.resolveSourceID(sourceName)
429428
if err != nil {
@@ -439,7 +438,7 @@ func (m *MariaDB) ReadGraph(sourceName string, graph *knowledge.Graph) error {
439438

440439
{
441440
// Select all relations produced by this source
442-
rows, err := tx.QueryContext(context.Background(), `
441+
rows, err := tx.QueryContext(ctx, `
443442
SELECT a.type, a.value, b.type, b.value, r.type FROM relations_by_source rbs
444443
INNER JOIN relations r ON rbs.relation_id = r.id
445444
INNER JOIN assets a ON a.id=r.from_id
@@ -477,7 +476,7 @@ WHERE rbs.source_id = ?
477476
{
478477
// Select all assets produced by this source. This is useful in case there are some standalone nodes in the graph of the source.
479478
// TODO(c.michaud): optimization could be done by only selecting assets without any relation since the others have already have been retrieved in the previous query.
480-
rows, err := tx.QueryContext(context.Background(), `
479+
rows, err := tx.QueryContext(ctx, `
481480
SELECT a.type, a.value FROM assets_by_source abs
482481
INNER JOIN assets a ON a.id=abs.asset_id
483482
WHERE abs.source_id = ?
@@ -510,53 +509,53 @@ WHERE abs.source_id = ?
510509
}
511510

512511
// FlushAll flush the database
513-
func (m *MariaDB) FlushAll() error {
512+
func (m *MariaDB) FlushAll(ctx context.Context) error {
514513
tx, err := m.db.Begin()
515514
if err != nil {
516515
return err
517516
}
518517

519-
_, err = tx.ExecContext(context.Background(), "DROP TABLE relations_by_source")
518+
_, err = tx.ExecContext(ctx, "DROP TABLE relations_by_source")
520519
if err != nil {
521520
if !isUnknownTableError(err) {
522521
tx.Rollback()
523522
return err
524523
}
525524
}
526525

527-
_, err = tx.ExecContext(context.Background(), "DROP TABLE assets_by_source")
526+
_, err = tx.ExecContext(ctx, "DROP TABLE assets_by_source")
528527
if err != nil {
529528
if !isUnknownTableError(err) {
530529
tx.Rollback()
531530
return err
532531
}
533532
}
534533

535-
_, err = tx.ExecContext(context.Background(), "DROP TABLE relations")
534+
_, err = tx.ExecContext(ctx, "DROP TABLE relations")
536535
if err != nil {
537536
if !isUnknownTableError(err) {
538537
tx.Rollback()
539538
return err
540539
}
541540
}
542541

543-
_, err = tx.ExecContext(context.Background(), "DROP TABLE assets")
542+
_, err = tx.ExecContext(ctx, "DROP TABLE assets")
544543
if err != nil {
545544
if !isUnknownTableError(err) {
546545
tx.Rollback()
547546
return err
548547
}
549548
}
550549

551-
_, err = tx.ExecContext(context.Background(), "DROP TABLE graph_schema")
550+
_, err = tx.ExecContext(ctx, "DROP TABLE graph_schema")
552551
if err != nil {
553552
if !isUnknownTableError(err) {
554553
tx.Rollback()
555554
return err
556555
}
557556
}
558557

559-
_, err = tx.ExecContext(context.Background(), "DROP TABLE query_history")
558+
_, err = tx.ExecContext(ctx, "DROP TABLE query_history")
560559
if err != nil {
561560
if !isUnknownTableError(err) {
562561
tx.Rollback()
@@ -568,9 +567,9 @@ func (m *MariaDB) FlushAll() error {
568567
}
569568

570569
// CountAssets count the total number of assets in db.
571-
func (m *MariaDB) CountAssets() (int64, error) {
570+
func (m *MariaDB) CountAssets(ctx context.Context) (int64, error) {
572571
var count int64
573-
row := m.db.QueryRowContext(context.Background(), "SELECT COUNT(*) FROM assets")
572+
row := m.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM assets")
574573

575574
err := row.Scan(&count)
576575
if err != nil {
@@ -580,9 +579,9 @@ func (m *MariaDB) CountAssets() (int64, error) {
580579
}
581580

582581
// CountRelations count the total number of relations in db.
583-
func (m *MariaDB) CountRelations() (int64, error) {
582+
func (m *MariaDB) CountRelations(ctx context.Context) (int64, error) {
584583
var count int64
585-
row := m.db.QueryRowContext(context.Background(), "SELECT COUNT(*) FROM relations")
584+
row := m.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM relations")
586585

587586
err := row.Scan(&count)
588587
if err != nil {

internal/handlers/handler_update_graph.go

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package handlers
22

33
import (
4+
"context"
45
"encoding/json"
56
"fmt"
67
"io"
@@ -15,7 +16,7 @@ import (
1516
"golang.org/x/sync/semaphore"
1617
)
1718

18-
func handleUpdate(registry sources.Registry, fn func(source string, body io.Reader) error, sem *semaphore.Weighted, operationDescriptor string) http.HandlerFunc {
19+
func handleUpdate(registry sources.Registry, fn func(ctx context.Context, source string, body io.Reader) error, sem *semaphore.Weighted, operationDescriptor string) http.HandlerFunc {
1920
return func(w http.ResponseWriter, r *http.Request) {
2021
ok, source, err := IsTokenValid(registry, r)
2122
if err != nil {
@@ -51,7 +52,7 @@ func handleUpdate(registry sources.Registry, fn func(source string, body io.Read
5152
With(promLabels).
5253
Inc()
5354

54-
if err = fn(source, r.Body); err != nil {
55+
if err = fn(r.Context(), source, r.Body); err != nil {
5556
metrics.GraphUpdateRequestsFailedCounter.
5657
With(promLabels).
5758
Inc()
@@ -78,14 +79,14 @@ func handleUpdate(registry sources.Registry, fn func(source string, body io.Read
7879

7980
// PutSchema upsert an asset into the graph of the data source
8081
func PutSchema(registry sources.Registry, graphUpdater *knowledge.GraphUpdater, sem *semaphore.Weighted) http.HandlerFunc {
81-
return handleUpdate(registry, func(source string, body io.Reader) error {
82+
return handleUpdate(registry, func(ctx context.Context, source string, body io.Reader) error {
8283
requestBody := client.PutGraphSchemaRequestBody{}
8384
if err := json.NewDecoder(body).Decode(&requestBody); err != nil {
8485
return err
8586
}
8687

8788
// TODO(c.michaud): verify compatibility of the schema with graph updates
88-
err := graphUpdater.UpdateSchema(source, requestBody.Schema)
89+
err := graphUpdater.UpdateSchema(ctx, source, requestBody.Schema)
8990
if err != nil {
9091
return fmt.Errorf("Unable to update the schema: %v", err)
9192
}
@@ -100,14 +101,14 @@ func PutSchema(registry sources.Registry, graphUpdater *knowledge.GraphUpdater,
100101

101102
// PutAssets upsert several assets into the graph of the data source
102103
func PutAssets(registry sources.Registry, graphUpdater *knowledge.GraphUpdater, sem *semaphore.Weighted) http.HandlerFunc {
103-
return handleUpdate(registry, func(source string, body io.Reader) error {
104+
return handleUpdate(registry, func(ctx context.Context, source string, body io.Reader) error {
104105
requestBody := client.PutGraphAssetRequestBody{}
105106
if err := json.NewDecoder(body).Decode(&requestBody); err != nil {
106107
return err
107108
}
108109

109110
// TODO(c.michaud): verify compatibility of the schema with graph updates
110-
err := graphUpdater.InsertAssets(source, requestBody.Assets)
111+
err := graphUpdater.InsertAssets(ctx, source, requestBody.Assets)
111112
if err != nil {
112113
return fmt.Errorf("Unable to insert assets: %v", err)
113114
}
@@ -122,14 +123,14 @@ func PutAssets(registry sources.Registry, graphUpdater *knowledge.GraphUpdater,
122123

123124
// PutRelations upsert multiple relations into the graph of the data source
124125
func PutRelations(registry sources.Registry, graphUpdater *knowledge.GraphUpdater, sem *semaphore.Weighted) http.HandlerFunc {
125-
return handleUpdate(registry, func(source string, body io.Reader) error {
126+
return handleUpdate(registry, func(ctx context.Context, source string, body io.Reader) error {
126127
requestBody := client.PutGraphRelationRequestBody{}
127128
if err := json.NewDecoder(body).Decode(&requestBody); err != nil {
128129
return err
129130
}
130131

131132
// TODO(c.michaud): verify compatibility of the schema with graph updates
132-
err := graphUpdater.InsertRelations(source, requestBody.Relations)
133+
err := graphUpdater.InsertRelations(ctx, source, requestBody.Relations)
133134
if err != nil {
134135
return fmt.Errorf("Unable to insert relation: %v", err)
135136
}
@@ -144,14 +145,14 @@ func PutRelations(registry sources.Registry, graphUpdater *knowledge.GraphUpdate
144145

145146
// DeleteAssets delete multiple assets from the graph of the data source
146147
func DeleteAssets(registry sources.Registry, graphUpdater *knowledge.GraphUpdater, sem *semaphore.Weighted) http.HandlerFunc {
147-
return handleUpdate(registry, func(source string, body io.Reader) error {
148+
return handleUpdate(registry, func(ctx context.Context, source string, body io.Reader) error {
148149
requestBody := client.DeleteGraphAssetRequestBody{}
149150
if err := json.NewDecoder(body).Decode(&requestBody); err != nil {
150151
return err
151152
}
152153

153154
// TODO(c.michaud): verify compatibility of the schema with graph updates
154-
err := graphUpdater.RemoveAssets(source, requestBody.Assets)
155+
err := graphUpdater.RemoveAssets(ctx, source, requestBody.Assets)
155156
if err != nil {
156157
return fmt.Errorf("Unable to remove assets: %v", err)
157158
}
@@ -166,14 +167,14 @@ func DeleteAssets(registry sources.Registry, graphUpdater *knowledge.GraphUpdate
166167

167168
// DeleteRelations remove multiple relations from the graph of the data source
168169
func DeleteRelations(registry sources.Registry, graphUpdater *knowledge.GraphUpdater, sem *semaphore.Weighted) http.HandlerFunc {
169-
return handleUpdate(registry, func(source string, body io.Reader) error {
170+
return handleUpdate(registry, func(ctx context.Context, source string, body io.Reader) error {
170171
requestBody := client.DeleteGraphRelationRequestBody{}
171172
if err := json.NewDecoder(body).Decode(&requestBody); err != nil {
172173
return err
173174
}
174175

175176
// TODO(c.michaud): verify compatibility of the schema with graph updates
176-
err := graphUpdater.RemoveRelations(source, requestBody.Relations)
177+
err := graphUpdater.RemoveRelations(ctx, source, requestBody.Relations)
177178
if err != nil {
178179
return fmt.Errorf("Unable to remove relation: %v", err)
179180
}

0 commit comments

Comments
 (0)