| 1 | |
| 2 | |
| 3 | @@ -10,6 +10,7 @@ |
| 4 | "fmt" |
| 5 | "io" |
| 6 | "strings" |
| 7 | + "sync" |
| 8 | |
| 9 | "github.com/google/yamlfmt" |
| 10 | "github.com/google/yamlfmt/formatters/basic" |
| 11 | @@ -18,8 +19,16 @@ |
| 12 | logging "gopkg.in/op/go-logging.v1" |
| 13 | ) |
| 14 | |
| 15 | +// yqlib shares its parser, security preferences and logging backend. |
| 16 | +// Keep validation and evaluation in the same critical section so each call |
| 17 | +// owns both its parser state and the diagnostics captured for that call. |
| 18 | +var operationMu sync.Mutex |
| 19 | + |
| 20 | // ValidateContent decodes the content yaml, to check it for syntax errors. |
| 21 | func ValidateContent(content []byte) error { |
| 22 | + operationMu.Lock() |
| 23 | + defer operationMu.Unlock() |
| 24 | + |
| 25 | memory := logging.NewMemoryBackend(0) |
| 26 | backend := logging.AddModuleLevel(memory) |
| 27 | logging.SetBackend(backend) |
| 28 | @@ -44,6 +53,9 @@ |
| 29 | if expression == "" { |
| 30 | return content, nil |
| 31 | } |
| 32 | + operationMu.Lock() |
| 33 | + defer operationMu.Unlock() |
| 34 | + |
| 35 | logrus.Debugf("Evaluating yq expression: %#q", expression) |
| 36 | memory := logging.NewMemoryBackend(0) |
| 37 | backend := logging.AddModuleLevel(memory) |
| 38 | |
| 39 | |
| 40 | @@ -0,0 +1,38 @@ |
| 41 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 42 | +// SPDX-License-Identifier: Apache-2.0 |
| 43 | + |
| 44 | +package yqutil |
| 45 | + |
| 46 | +import ( |
| 47 | + "fmt" |
| 48 | + "strings" |
| 49 | + "sync" |
| 50 | + "testing" |
| 51 | +) |
| 52 | + |
| 53 | +func TestConcurrentValidationAndEvaluation(t *testing.T) { |
| 54 | + var workers sync.WaitGroup |
| 55 | + for i := range 16 { |
| 56 | + workers.Add(1) |
| 57 | + go func() { |
| 58 | + defer workers.Done() |
| 59 | + value := fmt.Sprintf("request-%d", i) |
| 60 | + for range 4 { |
| 61 | + if err := ValidateContent([]byte("source: " + value + "\n")); err != nil { |
| 62 | + t.Error(err) |
| 63 | + return |
| 64 | + } |
| 65 | + out, err := EvaluateExpressionPlain(`.result = .source | del(.source)`, "source: "+value+"\n", false) |
| 66 | + if err != nil || strings.TrimSpace(out) != "result: "+value { |
| 67 | + t.Errorf("evaluation for %s returned %q, %v", value, out, err) |
| 68 | + return |
| 69 | + } |
| 70 | + if err := ValidateContent([]byte("broken: [\n")); err == nil { |
| 71 | + t.Error("malformed YAML was accepted") |
| 72 | + return |
| 73 | + } |
| 74 | + } |
| 75 | + }() |
| 76 | + } |
| 77 | + workers.Wait() |
| 78 | +} |