|
| 1 | +package repositories |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "sync" |
| 7 | + |
| 8 | + "github.com/NdoleStudio/httpsms/pkg/telemetry" |
| 9 | + "github.com/palantir/stacktrace" |
| 10 | +) |
| 11 | + |
| 12 | +// MemoryAttachmentStorage stores attachments in memory |
| 13 | +type MemoryAttachmentStorage struct { |
| 14 | + logger telemetry.Logger |
| 15 | + tracer telemetry.Tracer |
| 16 | + data sync.Map |
| 17 | +} |
| 18 | + |
| 19 | +// NewMemoryAttachmentStorage creates a new MemoryAttachmentStorage |
| 20 | +func NewMemoryAttachmentStorage( |
| 21 | + logger telemetry.Logger, |
| 22 | + tracer telemetry.Tracer, |
| 23 | +) *MemoryAttachmentStorage { |
| 24 | + return &MemoryAttachmentStorage{ |
| 25 | + logger: logger.WithService(fmt.Sprintf("%T", &MemoryAttachmentStorage{})), |
| 26 | + tracer: tracer, |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +// Upload stores attachment data at the given path |
| 31 | +func (s *MemoryAttachmentStorage) Upload(ctx context.Context, path string, data []byte) error { |
| 32 | + _, span := s.tracer.Start(ctx) |
| 33 | + defer span.End() |
| 34 | + |
| 35 | + s.data.Store(path, data) |
| 36 | + s.logger.Info(fmt.Sprintf("stored attachment at path [%s] with size [%d]", path, len(data))) |
| 37 | + return nil |
| 38 | +} |
| 39 | + |
| 40 | +// Download retrieves attachment data from the given path |
| 41 | +func (s *MemoryAttachmentStorage) Download(ctx context.Context, path string) ([]byte, error) { |
| 42 | + _, span := s.tracer.Start(ctx) |
| 43 | + defer span.End() |
| 44 | + |
| 45 | + value, ok := s.data.Load(path) |
| 46 | + if !ok { |
| 47 | + return nil, stacktrace.NewError(fmt.Sprintf("attachment not found at path [%s]", path)) |
| 48 | + } |
| 49 | + return value.([]byte), nil |
| 50 | +} |
| 51 | + |
| 52 | +// Delete removes an attachment at the given path |
| 53 | +func (s *MemoryAttachmentStorage) Delete(ctx context.Context, path string) error { |
| 54 | + _, span := s.tracer.Start(ctx) |
| 55 | + defer span.End() |
| 56 | + |
| 57 | + s.data.Delete(path) |
| 58 | + s.logger.Info(fmt.Sprintf("deleted attachment at path [%s]", path)) |
| 59 | + return nil |
| 60 | +} |
0 commit comments