Skip to content

Commit e608209

Browse files
committed
Add a hard timeout to stop the SQL processing of a too long query.
This will prevent from killing the MariaDB with bad queries.
1 parent 692ee47 commit e608209

File tree

3 files changed

+10
-4
lines changed

3 files changed

+10
-4
lines changed

internal/database/mariadb.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,12 @@ func (m *MariaDB) Query(ctx context.Context, query *query.QueryIL) (*knowledge.G
486486
return nil, err
487487
}
488488

489+
deadline, ok := ctx.Deadline()
490+
// If there is a deadline, we make sure the query stops right after it has been reached.
491+
if ok {
492+
// Query can take 35 seconds max before being aborted...
493+
sql.Query = fmt.Sprintf("SET STATEMENT max_statement_time=%f FOR %s", time.Until(deadline).Seconds()+5, sql.Query)
494+
}
489495
fmt.Println(sql.Query)
490496

491497
rows, err := m.db.QueryContext(ctx, sql.Query)
@@ -499,7 +505,6 @@ func (m *MariaDB) Query(ctx context.Context, query *query.QueryIL) (*knowledge.G
499505
Projections: sql.ProjectionTypes,
500506
}
501507
res.Projections = sql.ProjectionTypes
502-
503508
return res, nil
504509
}
505510

internal/knowledge/querier.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,13 @@ func (q *Querier) Query(ctx context.Context, cypherQuery string) (*QuerierResult
4040
s.Execution = MeasureDuration(func() {
4141
res, err = q.GraphDB.Query(ctx, queryIL)
4242
})
43-
fmt.Printf("Found results in %dms\n", s.Execution/time.Millisecond)
4443

4544
if err != nil {
4645
return nil, err
4746
}
4847

48+
fmt.Printf("Found results in %dms\n", s.Execution/time.Millisecond)
49+
4950
result := &QuerierResult{
5051
Cursor: res.Cursor,
5152
Projections: res.Projections,

internal/server/server.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,15 +153,15 @@ func postQuery(database knowledge.GraphDB) http.HandlerFunc {
153153
}
154154

155155
querier := knowledge.NewQuerier(database)
156-
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
156+
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
157157
defer cancel()
158158

159159
res, err := querier.Query(ctx, requestBody.Query)
160-
161160
if err != nil {
162161
replyWithInternalError(w, err)
163162
return
164163
}
164+
defer res.Cursor.Close()
165165

166166
columns := make([]ColumnType, 0)
167167
for _, p := range res.Projections {

0 commit comments

Comments
 (0)