From 9630d43bc272382d5a8c25d95610436608555b0c Mon Sep 17 00:00:00 2001 From: Sander Pick Date: Fri, 25 Feb 2022 14:56:15 -0800 Subject: [PATCH] move vm timeout to where func is called Signed-off-by: Sander Pick --- db/collection.go | 11 +++++++---- db/collection_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/db/collection.go b/db/collection.go index b7b6f9b3..fa5f05c1 100644 --- a/db/collection.go +++ b/db/collection.go @@ -44,7 +44,7 @@ var ( baseKey = dsPrefix.ChildString("collection") - vmTimeout = time.Millisecond * 200 + vmTimeout = time.Second * 30 ) const ( @@ -87,9 +87,6 @@ func newCollection(d *DB, config CollectionConfig) (*Collection, error) { return nil, err } vm := goja.New() - time.AfterFunc(vmTimeout, func() { - vm.Interrupt("validator timed out") - }) wv := []byte(config.WriteValidator) rf := []byte(config.ReadFilter) c := &Collection{ @@ -344,6 +341,9 @@ func (c *Collection) validWrite(identity thread.PubKey, e core.Event) error { return fmt.Errorf("parsing instance in validate write: %v", err) } } + time.AfterFunc(vmTimeout, func() { + c.vm.Interrupt("validator timed out") + }) res, err := c.writeValidator(nil, writer, event, inv) if err != nil { return fmt.Errorf("running write validator func: %v", err) @@ -377,6 +377,9 @@ func (c *Collection) filterRead(identity thread.PubKey, instance []byte) ([]byte if err != nil { return nil, fmt.Errorf("parsing instance in filter read: %v", err) } + time.AfterFunc(vmTimeout, func() { + c.vm.Interrupt("filter timed out") + }) res, err := c.readFilter(nil, reader, inv) if err != nil { return nil, fmt.Errorf("running read filter func: %v", err) diff --git a/db/collection_test.go b/db/collection_test.go index ec3e47b8..df6dd0d0 100644 --- a/db/collection_test.go +++ b/db/collection_test.go @@ -143,6 +143,21 @@ func TestNewCollection(t *testing.T) { if err == nil { t.Fatal("delete should have been invalid") } + + // test vm interupt + c, err = db.UpdateCollection(CollectionConfig{ + Name: "Dog", + Schema: util.SchemaFromInstance(&Dog{}, false), + WriteValidator: ` + while(true){} + `, + }) + checkErr(t, err) + dog = Dog{Name: "Fido", Comments: []Comment{}} + id, err = c.Create(util.JSONFromInstance(dog)) + if err == nil { + t.Fatal("should get validator timed out error") + } }) t.Run("WithReadFilter", func(t *testing.T) { t.Parallel() @@ -167,6 +182,20 @@ func TestNewCollection(t *testing.T) { if filtered.Name != "Clyde" { t.Fatal("name should have been modified by read filter") } + + // test vm interupt + c, err = db.UpdateCollection(CollectionConfig{ + Name: "Dog", + Schema: util.SchemaFromInstance(&Dog{}, false), + ReadFilter: ` + while(true){} + `, + }) + checkErr(t, err) + _, err = c.FindByID(id) + if err == nil { + t.Fatal("should get filter timed out error") + } }) t.Run("SingleExpandedSchemaStruct", func(t *testing.T) { t.Parallel()