Files
mtusi2026lab4/internal/application/service.go
T

74 lines
2.1 KiB
Go

package application
import (
"fmt"
"time"
)
const MinimumIdempotencyTTL = 24 * time.Hour
const defaultAttachmentCleanupTimeout = time.Second
const defaultAttachmentUploadConcurrency = 4
const defaultAttachmentDecodeConcurrency = 1
type ServiceOption func(*Service) error
type Service struct {
repository Repository
cursors *CursorCodec
sessionTTL time.Duration
idempotencyTTL time.Duration
now func() time.Time
objectStore ObjectStore
attachmentCleanupTimeout time.Duration
attachmentUploadSlots chan struct{}
attachmentDecodeSlots chan struct{}
}
func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration, options ...ServiceOption) (*Service, error) {
if repository == nil {
return nil, fmt.Errorf("repository is required")
}
if cursors == nil {
return nil, fmt.Errorf("cursor codec is required")
}
if sessionTTL <= 0 {
return nil, fmt.Errorf("session TTL must be positive")
}
service := &Service{
repository: repository,
cursors: cursors,
sessionTTL: sessionTTL,
idempotencyTTL: MinimumIdempotencyTTL,
now: func() time.Time { return time.Now().UTC() },
attachmentCleanupTimeout: defaultAttachmentCleanupTimeout,
attachmentUploadSlots: make(chan struct{}, defaultAttachmentUploadConcurrency),
attachmentDecodeSlots: make(chan struct{}, defaultAttachmentDecodeConcurrency),
}
for _, option := range options {
if err := option(service); err != nil {
return nil, err
}
}
return service, nil
}
func WithIdempotencyTTL(ttl time.Duration) ServiceOption {
return func(service *Service) error {
if ttl < MinimumIdempotencyTTL {
return fmt.Errorf("idempotency TTL must be at least %s", MinimumIdempotencyTTL)
}
service.idempotencyTTL = ttl
return nil
}
}
func WithObjectStore(objectStore ObjectStore) ServiceOption {
return func(service *Service) error {
if objectStore == nil {
return fmt.Errorf("object store is required")
}
service.objectStore = objectStore
return nil
}
}