s3api.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package s3api
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/TecharoHQ/anubis/lib/store"
  11. "github.com/aws/aws-sdk-go-v2/service/s3"
  12. )
  13. type Store struct {
  14. s3 S3API
  15. bucket string
  16. }
  17. func (s *Store) Delete(ctx context.Context, key string) error {
  18. normKey := strings.ReplaceAll(key, ":", "/")
  19. // Emulate not found by probing first.
  20. if _, err := s.s3.HeadObject(ctx, &s3.HeadObjectInput{Bucket: &s.bucket, Key: &normKey}); err != nil {
  21. return fmt.Errorf("%w: %w", store.ErrNotFound, err)
  22. }
  23. if _, err := s.s3.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: &s.bucket, Key: &normKey}); err != nil {
  24. return fmt.Errorf("can't delete from s3: %w", err)
  25. }
  26. return nil
  27. }
  28. func (s *Store) Get(ctx context.Context, key string) ([]byte, error) {
  29. normKey := strings.ReplaceAll(key, ":", "/")
  30. out, err := s.s3.GetObject(ctx, &s3.GetObjectInput{
  31. Bucket: &s.bucket,
  32. Key: &normKey,
  33. })
  34. if err != nil {
  35. return nil, fmt.Errorf("%w: %w", store.ErrNotFound, err)
  36. }
  37. defer out.Body.Close()
  38. if msStr, ok := out.Metadata["x-anubis-expiry-ms"]; ok && msStr != "" {
  39. if ms, err := strconv.ParseInt(msStr, 10, 64); err == nil {
  40. if time.Now().UnixMilli() >= ms {
  41. _, _ = s.s3.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: &s.bucket, Key: &normKey})
  42. return nil, store.ErrNotFound
  43. }
  44. }
  45. }
  46. b, err := io.ReadAll(out.Body)
  47. if err != nil {
  48. return nil, fmt.Errorf("can't read s3 object: %w", err)
  49. }
  50. return b, nil
  51. }
  52. func (s *Store) Set(ctx context.Context, key string, value []byte, expiry time.Duration) error {
  53. normKey := strings.ReplaceAll(key, ":", "/")
  54. // S3 has no native TTL; we store object with metadata X-Anubis-Expiry as epoch seconds.
  55. var meta map[string]string
  56. if expiry > 0 {
  57. exp := time.Now().Add(expiry).UnixMilli()
  58. meta = map[string]string{"x-anubis-expiry-ms": fmt.Sprintf("%d", exp)}
  59. }
  60. _, err := s.s3.PutObject(ctx, &s3.PutObjectInput{
  61. Bucket: &s.bucket,
  62. Key: &normKey,
  63. Body: bytes.NewReader(value),
  64. Metadata: meta,
  65. })
  66. if err != nil {
  67. return fmt.Errorf("can't put s3 object: %w", err)
  68. }
  69. return nil
  70. }
  71. func (Store) IsPersistent() bool { return true }