| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package storagetest |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"errors" |
| 9 |
"sync" |
| 10 |
"sync/atomic" |
| 11 |
"time" |
| 12 |
|
| 13 |
"go.opentelemetry.io/collector/component" |
| 14 |
"go.opentelemetry.io/collector/extension/xextension/storage" |
| 15 |
) |
| 16 |
|
| 17 |
type mockStorageExtension struct { |
| 18 |
component.StartFunc |
| 19 |
component.ShutdownFunc |
| 20 |
st sync.Map |
| 21 |
getClientError error |
| 22 |
executionDelay time.Duration |
| 23 |
} |
| 24 |
|
| 25 |
func (m *mockStorageExtension) GetClient(context.Context, component.Kind, component.ID, string) (storage.Client, error) { |
| 26 |
if m.getClientError != nil { |
| 27 |
return nil, m.getClientError |
| 28 |
} |
| 29 |
return &MockStorageClient{st: &m.st, closed: &atomic.Bool{}, executionDelay: m.executionDelay}, nil |
| 30 |
} |
| 31 |
|
| 32 |
func NewMockStorageExtension(getClientError error) storage.Extension { |
| 33 |
return NewMockStorageExtensionWithDelay(getClientError, 0) |
| 34 |
} |
| 35 |
|
| 36 |
func NewMockStorageExtensionWithDelay(getClientError error, executionDelay time.Duration) storage.Extension { |
| 37 |
return &mockStorageExtension{ |
| 38 |
getClientError: getClientError, |
| 39 |
executionDelay: executionDelay, |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
type MockStorageClient struct { |
| 44 |
st *sync.Map |
| 45 |
closed *atomic.Bool |
| 46 |
executionDelay time.Duration |
| 47 |
} |
| 48 |
|
| 49 |
func (m *MockStorageClient) Get(ctx context.Context, s string) ([]byte, error) { |
| 50 |
getOp := storage.GetOperation(s) |
| 51 |
err := m.Batch(ctx, getOp) |
| 52 |
return getOp.Value, err |
| 53 |
} |
| 54 |
|
| 55 |
func (m *MockStorageClient) Set(ctx context.Context, s string, bytes []byte) error { |
| 56 |
return m.Batch(ctx, storage.SetOperation(s, bytes)) |
| 57 |
} |
| 58 |
|
| 59 |
func (m *MockStorageClient) Delete(ctx context.Context, s string) error { |
| 60 |
return m.Batch(ctx, storage.DeleteOperation(s)) |
| 61 |
} |
| 62 |
|
| 63 |
func (m *MockStorageClient) Close(context.Context) error { |
| 64 |
m.closed.Store(true) |
| 65 |
return nil |
| 66 |
} |
| 67 |
|
| 68 |
func (m *MockStorageClient) Batch(_ context.Context, ops ...*storage.Operation) error { |
| 69 |
if m.IsClosed() { |
| 70 |
panic("client already closed") |
| 71 |
} |
| 72 |
if m.executionDelay != 0 { |
| 73 |
time.Sleep(m.executionDelay) |
| 74 |
} |
| 75 |
for _, op := range ops { |
| 76 |
switch op.Type { |
| 77 |
case storage.Get: |
| 78 |
val, found := m.st.Load(op.Key) |
| 79 |
if !found { |
| 80 |
break |
| 81 |
} |
| 82 |
op.Value = val.([]byte) |
| 83 |
case storage.Set: |
| 84 |
m.st.Store(op.Key, op.Value) |
| 85 |
case storage.Delete: |
| 86 |
m.st.Delete(op.Key) |
| 87 |
default: |
| 88 |
return errors.New("wrong operation type") |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
return nil |
| 93 |
} |
| 94 |
|
| 95 |
func (m *MockStorageClient) IsClosed() bool { |
| 96 |
return m.closed.Load() |
| 97 |
} |