154 lines
5.3 KiB
Go
154 lines
5.3 KiB
Go
package domain
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
const (
|
|
// MaxScheduledJobPayloadBytes bounds the compact JSON payload. A job
|
|
// carries identifiers only; its handler reads everything else from the
|
|
// source tables under the access rules in force when it runs.
|
|
MaxScheduledJobPayloadBytes = 2 << 10
|
|
// MaxScheduledJobAttempts bounds a per-job attempt limit.
|
|
MaxScheduledJobAttempts = 100
|
|
maxScheduledJobKindLength = 64
|
|
maxScheduledJobKeyLength = 128
|
|
)
|
|
|
|
var (
|
|
ErrInvalidScheduledJob = errors.New("invalid scheduled job")
|
|
|
|
// Lowercase snake_case names, optionally dotted, such as
|
|
// "invitation.response_deadline".
|
|
scheduledJobKindPattern = regexp.MustCompile(`^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$`)
|
|
// Opaque keys such as a UUID or "<uuid>:<version>". The alphabet leaves
|
|
// out "@" and spaces, so an email address or a name cannot be a key.
|
|
scheduledJobKeyPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:-]*$`)
|
|
)
|
|
|
|
// ScheduledJob is a job that a usecase schedules in its business
|
|
// transaction, to run once when it falls due.
|
|
//
|
|
// Kind names the handler. Key identifies the logical job within its kind:
|
|
// the first schedule of a (kind, key) pair wins and a repeat does nothing,
|
|
// also after the job ran or was canceled, so a key must change whenever a
|
|
// new occurrence is wanted, for example "<aggregate id>:<version>". Neither
|
|
// the key nor the payload may contain personal data: both are stored next
|
|
// to operator diagnostics, and the payload carries identifiers only.
|
|
type ScheduledJob struct {
|
|
kind string
|
|
key string
|
|
dueAt time.Time
|
|
payload []byte
|
|
maxAttempts int
|
|
}
|
|
|
|
// ScheduledJobInput describes a new job. DueAt comes from the application
|
|
// clock. Payload is a flat JSON object of strings, numbers, booleans, or
|
|
// nulls of at most MaxScheduledJobPayloadBytes in compact form; nil means
|
|
// an empty object. MaxAttempts is zero for the worker default.
|
|
type ScheduledJobInput struct {
|
|
Kind string
|
|
Key string
|
|
DueAt time.Time
|
|
Payload []byte
|
|
MaxAttempts int
|
|
}
|
|
|
|
// NewScheduledJob validates input. The due time is kept in UTC at the
|
|
// microsecond precision that PostgreSQL stores.
|
|
func NewScheduledJob(input ScheduledJobInput) (ScheduledJob, error) {
|
|
if err := ValidateScheduledJobKind(input.Kind); err != nil {
|
|
return ScheduledJob{}, err
|
|
}
|
|
if len(input.Key) > maxScheduledJobKeyLength || !scheduledJobKeyPattern.MatchString(input.Key) {
|
|
return ScheduledJob{}, invalidScheduledJob("key must be 1 to 128 letters, digits, dots, underscores, colons, or hyphens")
|
|
}
|
|
if input.DueAt.IsZero() {
|
|
return ScheduledJob{}, invalidScheduledJob("due time must be set")
|
|
}
|
|
if input.MaxAttempts < 0 || input.MaxAttempts > MaxScheduledJobAttempts {
|
|
return ScheduledJob{}, invalidScheduledJob("max attempts must be between 0 and 100")
|
|
}
|
|
payload, err := scheduledJobPayload(input.Payload)
|
|
if err != nil {
|
|
return ScheduledJob{}, err
|
|
}
|
|
return ScheduledJob{
|
|
kind: input.Kind,
|
|
key: input.Key,
|
|
dueAt: input.DueAt.UTC().Truncate(time.Microsecond),
|
|
payload: payload,
|
|
maxAttempts: input.MaxAttempts,
|
|
}, nil
|
|
}
|
|
|
|
// ValidateScheduledJobKind checks a job kind name. The worker applies it to
|
|
// the kinds of its handlers too.
|
|
func ValidateScheduledJobKind(kind string) error {
|
|
if len(kind) > maxScheduledJobKindLength || !scheduledJobKindPattern.MatchString(kind) {
|
|
return invalidScheduledJob("kind must be a lowercase dotted name of at most 64 bytes")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func scheduledJobPayload(payload []byte) ([]byte, error) {
|
|
if payload == nil {
|
|
return []byte("{}"), nil
|
|
}
|
|
// encoding/json accepts invalid UTF-8 inside strings; PostgreSQL does not.
|
|
if !utf8.Valid(payload) {
|
|
return nil, invalidScheduledJob("payload must be valid UTF-8")
|
|
}
|
|
var compact bytes.Buffer
|
|
if err := json.Compact(&compact, payload); err != nil {
|
|
return nil, invalidScheduledJob("payload must be valid JSON")
|
|
}
|
|
if compact.Len() > MaxScheduledJobPayloadBytes {
|
|
return nil, invalidScheduledJob("payload exceeds 2 KiB")
|
|
}
|
|
var fields map[string]any
|
|
if err := json.Unmarshal(compact.Bytes(), &fields); err != nil || fields == nil {
|
|
return nil, invalidScheduledJob("payload must be a JSON object with numbers that fit a float64")
|
|
}
|
|
for name, value := range fields {
|
|
text, isText := value.(string)
|
|
switch {
|
|
case strings.ContainsRune(name, 0), isText && strings.ContainsRune(text, 0):
|
|
return nil, invalidScheduledJob("payload must not contain NUL characters")
|
|
case isScalar(value):
|
|
default:
|
|
return nil, invalidScheduledJob("payload values must be strings, numbers, booleans, or null")
|
|
}
|
|
}
|
|
return compact.Bytes(), nil
|
|
}
|
|
|
|
func isScalar(value any) bool {
|
|
switch value.(type) {
|
|
case nil, string, float64, bool:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func invalidScheduledJob(reason string) error {
|
|
return fmt.Errorf("domain.NewScheduledJob - %s: %w", reason, ErrInvalidScheduledJob)
|
|
}
|
|
|
|
func (job ScheduledJob) Kind() string { return job.kind }
|
|
func (job ScheduledJob) Key() string { return job.key }
|
|
func (job ScheduledJob) DueAt() time.Time { return job.dueAt }
|
|
func (job ScheduledJob) Payload() json.RawMessage { return bytes.Clone(job.payload) }
|
|
|
|
// MaxAttempts is zero when the worker default applies.
|
|
func (job ScheduledJob) MaxAttempts() int { return job.maxAttempts }
|