feat(jobs): add durable due-time job runner with leases
This commit is contained in:
1 parent
7e80c8ad2a
commit
008254e44a
39 files changed
+4909
-43
No files matched your search
@@ -0,0 +1,153 @@
|
||||
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 }
|
||||
@@ -0,0 +1,94 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func validScheduledJobInput() ScheduledJobInput {
|
||||
return ScheduledJobInput{
|
||||
Kind: "invitation.response_deadline",
|
||||
Key: "0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d",
|
||||
DueAt: time.Date(2026, 10, 13, 9, 0, 0, 123456789, time.FixedZone("MSK", 3*60*60)),
|
||||
Payload: []byte(` { "invitation_id" : "0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d", "version": 2 } `),
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewScheduledJobNormalizesValidInput(t *testing.T) {
|
||||
input := validScheduledJobInput()
|
||||
job, err := NewScheduledJob(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewScheduledJob() error = %v", err)
|
||||
}
|
||||
if job.Kind() != input.Kind || job.Key() != input.Key || job.MaxAttempts() != 0 {
|
||||
t.Fatalf("NewScheduledJob() did not keep the identity: %+v", job)
|
||||
}
|
||||
// PostgreSQL keeps microseconds, so a stored job compares equal.
|
||||
if want := time.Date(2026, 10, 13, 6, 0, 0, 123456000, time.UTC); !job.DueAt().Equal(want) || job.DueAt().Location() != time.UTC {
|
||||
t.Fatalf("DueAt() = %s, want %s in UTC", job.DueAt(), want)
|
||||
}
|
||||
if want := `{"invitation_id":"0192f0c4-7d4e-7a3b-9c1d-2e3f4a5b6c7d","version":2}`; string(job.Payload()) != want {
|
||||
t.Fatalf("Payload() = %s, want %s", job.Payload(), want)
|
||||
}
|
||||
job.Payload()[0] = '['
|
||||
if job.Payload()[0] != '{' {
|
||||
t.Fatal("Payload() exposed the job's internal buffer")
|
||||
}
|
||||
|
||||
input.Payload = nil
|
||||
input.MaxAttempts = MaxScheduledJobAttempts
|
||||
job, err = NewScheduledJob(input)
|
||||
if err != nil || string(job.Payload()) != "{}" || job.MaxAttempts() != MaxScheduledJobAttempts {
|
||||
t.Fatalf("NewScheduledJob() without a payload = %s, %d, %v; want {}", job.Payload(), job.MaxAttempts(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewScheduledJobRejectsInvalidInput(t *testing.T) {
|
||||
prefix, suffix := `{"padding":"`, `"}`
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*ScheduledJobInput)
|
||||
}{
|
||||
{name: "empty kind", change: func(input *ScheduledJobInput) { input.Kind = "" }},
|
||||
{name: "uppercase kind", change: func(input *ScheduledJobInput) { input.Kind = "Invitation.deadline" }},
|
||||
{name: "empty kind segment", change: func(input *ScheduledJobInput) { input.Kind = "invitation..deadline" }},
|
||||
{name: "long kind", change: func(input *ScheduledJobInput) { input.Kind = strings.Repeat("k", 65) }},
|
||||
{name: "empty key", change: func(input *ScheduledJobInput) { input.Key = "" }},
|
||||
{name: "email as key", change: func(input *ScheduledJobInput) { input.Key = "person@example.com" }},
|
||||
{name: "key with a space", change: func(input *ScheduledJobInput) { input.Key = "a b" }},
|
||||
{name: "long key", change: func(input *ScheduledJobInput) { input.Key = strings.Repeat("k", 129) }},
|
||||
{name: "zero due time", change: func(input *ScheduledJobInput) { input.DueAt = time.Time{} }},
|
||||
{name: "negative attempts", change: func(input *ScheduledJobInput) { input.MaxAttempts = -1 }},
|
||||
{name: "too many attempts", change: func(input *ScheduledJobInput) { input.MaxAttempts = MaxScheduledJobAttempts + 1 }},
|
||||
{name: "array payload", change: func(input *ScheduledJobInput) { input.Payload = []byte(`["id"]`) }},
|
||||
{name: "null payload", change: func(input *ScheduledJobInput) { input.Payload = []byte(`null`) }},
|
||||
{name: "nested payload", change: func(input *ScheduledJobInput) { input.Payload = []byte(`{"user":{"id":"1"}}`) }},
|
||||
{name: "invalid JSON", change: func(input *ScheduledJobInput) { input.Payload = []byte(`{"id":`) }},
|
||||
{name: "invalid UTF-8", change: func(input *ScheduledJobInput) { input.Payload = []byte("{\"id\":\"\xff\"}") }},
|
||||
{name: "NUL in a value", change: func(input *ScheduledJobInput) { input.Payload = []byte(`{"id":"a\u0000b"}`) }},
|
||||
{name: "number out of range", change: func(input *ScheduledJobInput) { input.Payload = []byte(`{"n":1e400}`) }},
|
||||
{name: "payload over the limit", change: func(input *ScheduledJobInput) {
|
||||
input.Payload = []byte(prefix + strings.Repeat("a", MaxScheduledJobPayloadBytes-len(prefix)-len(suffix)+1) + suffix)
|
||||
}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
input := validScheduledJobInput()
|
||||
test.change(&input)
|
||||
if _, err := NewScheduledJob(input); !errors.Is(err, ErrInvalidScheduledJob) {
|
||||
t.Fatalf("NewScheduledJob() error = %v, want ErrInvalidScheduledJob", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewScheduledJobAcceptsPayloadAtSizeLimit(t *testing.T) {
|
||||
input := validScheduledJobInput()
|
||||
prefix, suffix := `{"padding":"`, `"}`
|
||||
input.Payload = []byte(prefix + strings.Repeat("a", MaxScheduledJobPayloadBytes-len(prefix)-len(suffix)) + suffix)
|
||||
if _, err := NewScheduledJob(input); err != nil {
|
||||
t.Fatalf("NewScheduledJob() rejected a payload at the limit: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user