From 7f6d1565ff0779faca582df47949c4faf52d68b4 Mon Sep 17 00:00:00 2001 From: Tobie Morgan Hitchcock Date: Wed, 2 May 2018 02:42:16 +0100 Subject: [PATCH] Enable ability to set a global query timeout duration --- cli/start.go | 2 ++ cnf/cnf.go | 4 ++++ db/executor.go | 17 +++++++++++++++++ 3 files changed, 23 insertions(+) diff --git a/cli/start.go b/cli/start.go index 9489724c..fbd51775 100644 --- a/cli/start.go +++ b/cli/start.go @@ -95,6 +95,8 @@ func init() { startCmd.PersistentFlags().DurationVar(&opts.DB.Proc.Sync, "db-sync", 0, flag("sync")) startCmd.PersistentFlags().DurationVar(&opts.DB.Proc.Shrink, "db-shrink", 0, flag("shrink")) + startCmd.PersistentFlags().DurationVar(&opts.Query.Timeout, "query-timeout", 0, "") + startCmd.PersistentFlags().StringSliceVarP(&opts.Node.Join, "join", "j", nil, flag("join")) startCmd.PersistentFlags().StringVarP(&opts.DB.Code, "key", "k", "", flag("key")) diff --git a/cnf/cnf.go b/cnf/cnf.go index 5c728a68..d7dbd86b 100644 --- a/cnf/cnf.go +++ b/cnf/cnf.go @@ -74,6 +74,10 @@ type Options struct { Join []string // Slice of cluster peers to join } + Query struct { + Timeout time.Duration // Fixed query timeout + } + Format struct { Type string // Stores the cli output format } diff --git a/db/executor.go b/db/executor.go index d46084a6..7e294b4c 100644 --- a/db/executor.go +++ b/db/executor.go @@ -21,6 +21,7 @@ import ( "runtime/debug" + "github.com/abcum/surreal/cnf" "github.com/abcum/surreal/kvs" "github.com/abcum/surreal/log" "github.com/abcum/surreal/mem" @@ -269,6 +270,22 @@ func (e *executor) operate(ctx context.Context, stm sql.Statement) (res []interf // can monitor the running time, and ensure // it runs no longer than specified. + if cnf.Settings.Query.Timeout > 0 { + if ctx.Value(ctxKeyKind) != cnf.AuthKV { + ctx, canc = context.WithTimeout(ctx, cnf.Settings.Query.Timeout) + defer func() { + if tim := ctx.Err(); err == nil && tim != nil { + res, err = nil, &TimerError{timer: cnf.Settings.Query.Timeout} + } + canc() + }() + } + } + + // Mark the beginning of this statement so we + // can monitor the running time, and ensure + // it runs no longer than specified. + if stm, ok := stm.(sql.KillableStatement); ok { if stm.Duration() > 0 { ctx, canc = context.WithTimeout(ctx, stm.Duration())