forked from mtusi2026/mtusi2026lab7
на оценку 4
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MinimumIdempotencyTTL = 24 * time.Hour
|
||||
const defaultAttachmentCleanupTimeout = time.Second
|
||||
const defaultAttachmentUploadConcurrency = 4
|
||||
const defaultAttachmentDecodeConcurrency = 1
|
||||
const defaultJobMaxAttempts = 5
|
||||
|
||||
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{}
|
||||
jobMaxAttempts int
|
||||
}
|
||||
|
||||
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),
|
||||
jobMaxAttempts: defaultJobMaxAttempts,
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
func WithJobMaxAttempts(attempts int) ServiceOption {
|
||||
return func(service *Service) error {
|
||||
if attempts < 1 {
|
||||
return fmt.Errorf("job max attempts must be positive")
|
||||
}
|
||||
service.jobMaxAttempts = attempts
|
||||
return nil
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user