Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 43 additions & 5 deletions docs/permissions.md
Original file line number Diff line number Diff line change
Expand Up @@ -468,11 +468,49 @@ Reports use a server-bound directory, never an existing folder selected by
name or references. Published CSVs are ordinary Drive files and may be shared
by their owner. The private binding and snapshot record are not Drive files.

The generator is not called by a route, worker, or scheduler. Publication of
the Drive file and recording its snapshot are separate operations: an
interruption between them can leave a complete file that the generator will
not reuse or overwrite. There is no migration recovery or automatic retry in
this step.
When `drive.public_link_events.enabled` is true, the Stack looks for expired
opted-in file links during the nightly window (02:00 inclusive to 06:00
exclusive UTC), without requiring a visit to the link. A process starting
inside the window can scan immediately; one starting outside waits until the
next window. A scan considers all still-eligible expiries at its start, not
just the last 24 hours. A new wave waits for the previous wave's queued jobs
to drain. Stacks sharing a Redis jobs backend record a completed scan until
that window ends, so a process restart does not repeat it. An incomplete scan
can be retried inside the same window, with a longer delay after repeated
errors. For each scan attempt, the Manager is queried without its usual cache,
at most once per context and ordered feature-set list. An unavailable flag
lookup does not count as a completed scan. The marker does not confirm delivery;
links missed or newly eligible after the scan can be picked up the next night.
This is not a fixed bound on jobs per night or on delivery time.

The internal worker only starts report generation inside the window and checks
the feature flag, current opt-in and exact expiry. It sends a link to the CSV
and a preview to the instance owner's current address, or saves the CSV alone
when no address is available. It rechecks the flag, consent, expiry, recipient
and report snapshot before SMTP submission, even when the attempt continues
past the end of the window. When the flag depends on the Manager, these worker
checks bypass the cache and do not authorize sending if that lookup fails.
Jobs skipped outside the window are rediscovered by a subsequent scan if still
eligible.

Attempts that fail before SMTP submission can be retried on subsequent nights.
The Stack does not automatically resend a message whose submission might have
reached the relay. This avoids blind replays, but does not guarantee delivery
or exactly-once SMTP. Publication of the Drive file and recording its snapshot
are separate operations: an interruption can leave a complete file that the
worker will not reuse or overwrite. There is no migration recovery.

With Redis jobs, scanners coordinate with a `locks:` lease on the jobs Redis
backend, even if instance locks are stored elsewhere. The jobs Redis ACL must
allow the standard lock operations (`SET`, `GET`, `PEXPIRE`, `DEL` and `EVAL`)
on that lease key, and queue length reads on both report queues. To suppress
repeated scans, also allow `EXISTS` and `SET` with expiration on
`j/expired-link-report-mail/scanned/*`. If access to the marker fails, scanning
and queuing can still proceed. A jobs backend configured with multiple
`redis.addrs` and no `redis.master` can use Redis
Cluster. On a native cluster, the broker's multi-key `BRPOP` can fail with
`CROSSSLOT` because the report queue keys are in separate slots. Report jobs
may then remain queued and prevent subsequent scans.

#### Request to add / remove codes with a document metadata

Expand Down
97 changes: 90 additions & 7 deletions model/feature/flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,82 @@ func (f *Flags) HasListItem(name, item string) (bool, error) {
return false, nil
}

// Enabled reports whether the effective flag is a boolean true.
func Enabled(inst *instance.Instance, name string) bool {
if value, ok := inst.FeatureFlags[name]; ok {
enabled, _ := value.(bool)
return enabled
}
flags, err := GetFlags(inst)
if err != nil {
return false
}
enabled, _ := flags.M[name].(bool)
return enabled
}

// EnabledFresh resolves a flag in source priority order without the Manager
// cache. Do not authorize work from a lower-priority source on lookup failure.
func EnabledFresh(inst *instance.Instance, name string) (bool, error) {
return resolveEnabled(inst, name, fetchManagerFlags)
}

// NewFreshFlagResolver returns a resolver for one scan. It shares fresh
// Manager responses (including failures) for the same context and ordered
// feature sets, without using or updating the regular Manager cache.
func NewFreshFlagResolver(name string) func(*instance.Instance) (bool, error) {
type key struct {
context string
sets string
}
type lookup struct {
flags map[string]interface{}
err error
}
results := make(map[key]lookup)
manager := func(inst *instance.Instance) (map[string]interface{}, error) {
// Quoting each element preserves the exact list and its order.
k := key{inst.ContextName, fmt.Sprintf("%q", inst.FeatureSets)}
result, ok := results[k]
if !ok {
result.flags, result.err = fetchManagerFlags(inst)
results[k] = result
}
return result.flags, result.err
}
return func(inst *instance.Instance) (bool, error) {
return resolveEnabled(inst, name, manager)
}
}

func resolveEnabled(inst *instance.Instance, name string, manager func(*instance.Instance) (map[string]interface{}, error)) (bool, error) {
if value, ok := inst.FeatureFlags[name]; ok {
enabled, _ := value.(bool)
return enabled, nil
}
if len(inst.FeatureSets) != 0 {
flags, err := manager(inst)
if err != nil {
return false, err
}
if value, ok := flags[name]; ok {
enabled, _ := value.(bool)
return enabled, nil
}
}
flags := &Flags{M: make(map[string]interface{})}
for _, add := range []func(*instance.Instance) error{flags.addConfig, flags.addContext, flags.addDefaults} {
if err := add(inst); err != nil {
return false, err
}
if value, ok := flags.M[name]; ok {
enabled, _ := value.(bool)
return enabled, nil
}
}
return false, nil
}

// GetFlags returns the list of feature flags for the given instance.
func GetFlags(inst *instance.Instance) (*Flags, error) {
sources := make([]*Flags, 0)
Expand Down Expand Up @@ -188,9 +264,20 @@ func getFlagsFromManager(inst *instance.Instance) (map[string]interface{}, error
}
}

flags, err := fetchManagerFlags(inst)
if err != nil || flags == nil {
return flags, err
}
if buf, err := json.Marshal(flags); err == nil {
cache.Set(cacheKey, buf, cacheDuration)
}
return flags, nil
}

func fetchManagerFlags(inst *instance.Instance) (map[string]interface{}, error) {
client := instance.APIManagerClient(inst)
if client == nil {
return flags, nil
return nil, nil
}
query := url.Values{
"sets": {strings.Join(inst.FeatureSets, ",")},
Expand All @@ -200,14 +287,10 @@ func getFlagsFromManager(inst *instance.Instance) (map[string]interface{}, error
if err != nil {
return nil, err
}
var ok bool
if flags, ok = data["flags"].(map[string]interface{}); !ok {
flags, ok := data["flags"].(map[string]interface{})
if !ok {
return nil, errInvalidResponse
}

if buf, err := json.Marshal(flags); err == nil {
cache.Set(cacheKey, buf, cacheDuration)
}
return flags, nil
}

Expand Down
6 changes: 5 additions & 1 deletion model/job/broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,11 @@ func (j *Job) Update() error {

// Create creates the job in couchdb
func (j *Job) Create() error {
return couchdb.CreateDoc(j, j)
return j.create(context.Background())
}

func (j *Job) create(ctx context.Context) error {
return couchdb.CreateDocWithContext(ctx, j, j)
}

// WaitUntilDone will wait until the job is done. It will return an error if
Expand Down
19 changes: 14 additions & 5 deletions model/job/globals.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package job

import (
"context"
"errors"

"github.com/cozy/cozy-stack/pkg/utils"
)
Expand All @@ -19,15 +20,18 @@ type JobSystem interface {
type jobSystem struct {
Broker
Scheduler
reports *expiredLinkScheduler
}

// Shutdown shuts down the job system. Implement the utils.Shutdowner
// interface.
func (j jobSystem) Shutdown(ctx context.Context) error {
func (j *jobSystem) Shutdown(ctx context.Context) error {
// Don't admit new report jobs while the consumers are shutting down.
reportErr := j.reports.stop(ctx)
if err := j.Broker.ShutdownWorkers(ctx); err != nil {
return err
return errors.Join(reportErr, err)
}
return j.Scheduler.ShutdownScheduler(ctx)
return errors.Join(reportErr, j.Scheduler.ShutdownScheduler(ctx))
}

var globalJobSystem JobSystem
Expand All @@ -38,11 +42,16 @@ func SystemStart(b Broker, s Scheduler, workersList WorkersList) error {
if globalJobSystem != nil {
panic("Job system already started")
}
globalJobSystem = jobSystem{b, s}
system := &jobSystem{Broker: b, Scheduler: s}
globalJobSystem = system
if err := b.StartWorkers(workersList); err != nil {
return err
}
return s.StartScheduler(b)
if err := s.StartScheduler(b); err != nil {
return err
}
system.reports = startExpiredLinkScheduler(b)
return nil
}

// System returns the global job system.
Expand Down
17 changes: 13 additions & 4 deletions model/job/mem_broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,12 @@ func newMemQueue(workerType string) *memQueue {
}
}

// Enqueue into the queue
func (q *memQueue) Enqueue(job *Job) error {
func (q *memQueue) enqueue(ctx context.Context, job *Job) error {
q.jmu.Lock()
defer q.jmu.Unlock()
if err := ctx.Err(); err != nil {
return err
}
q.list.PushBack(job.Clone())
if !q.run {
q.run = true
Expand Down Expand Up @@ -172,6 +174,13 @@ func (b *memBroker) ShutdownWorkers(ctx context.Context) error {
// PushJob will produce a new Job with the given options and enqueue the job in
// the proper queue.
func (b *memBroker) PushJob(db prefixer.Prefixer, req *JobRequest) (*Job, error) {
return b.pushJob(context.Background(), db, req)
}

func (b *memBroker) pushJob(ctx context.Context, db prefixer.Prefixer, req *JobRequest) (*Job, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if atomic.LoadUint32(&b.running) == 0 {
return nil, ErrClosed
}
Expand Down Expand Up @@ -215,7 +224,7 @@ func (b *memBroker) PushJob(db prefixer.Prefixer, req *JobRequest) (*Job, error)
}
}

if err := job.Create(); err != nil {
if err := job.create(ctx); err != nil {
return nil, err
}

Expand All @@ -225,7 +234,7 @@ func (b *memBroker) PushJob(db prefixer.Prefixer, req *JobRequest) (*Job, error)
}

q := b.queues[workerType]
if err := q.Enqueue(job); err != nil {
if err := q.enqueue(ctx, job); err != nil {
return nil, err
}
return job, nil
Expand Down
57 changes: 45 additions & 12 deletions model/job/redis_broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/cozy/cozy-stack/pkg/config/config"
"github.com/cozy/cozy-stack/pkg/limits"
"github.com/cozy/cozy-stack/pkg/lock"
"github.com/cozy/cozy-stack/pkg/logger"
"github.com/cozy/cozy-stack/pkg/prefixer"
multierror "github.com/hashicorp/go-multierror"
Expand All @@ -27,6 +28,7 @@ const (

type redisBroker struct {
client redis.UniversalClient
reportScanLock lock.Getter
ctx context.Context
workers []*Worker
workersRunning []*Worker
Expand All @@ -39,9 +41,10 @@ type redisBroker struct {
// the jobs among several cozy-stack processes.
func NewRedisBroker(client redis.UniversalClient) Broker {
return &redisBroker{
client: client,
ctx: context.Background(),
closed: make(chan struct{}),
client: client,
reportScanLock: lock.NewRedisLockGetter(client),
ctx: context.Background(),
closed: make(chan struct{}),
}
}

Expand Down Expand Up @@ -193,6 +196,13 @@ func (b *redisBroker) pollLoop(key string, ch chan<- *Job) {
// PushJob will produce a new Job with the given options and enqueue the job in
// the proper queue.
func (b *redisBroker) PushJob(db prefixer.Prefixer, req *JobRequest) (*Job, error) {
return b.pushJob(b.ctx, db, req)
}

func (b *redisBroker) pushJob(ctx context.Context, db prefixer.Prefixer, req *JobRequest) (*Job, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if atomic.LoadUint32(&b.running) == 0 {
return nil, ErrClosed
}
Expand Down Expand Up @@ -235,7 +245,7 @@ func (b *redisBroker) PushJob(db prefixer.Prefixer, req *JobRequest) (*Job, erro
}
}

if err := job.Create(); err != nil {
if err := job.create(ctx); err != nil {
return nil, err
}

Expand All @@ -257,7 +267,10 @@ func (b *redisBroker) PushJob(db prefixer.Prefixer, req *JobRequest) (*Job, erro
key += redisHighPrioritySuffix
}

if err := b.client.LPush(b.ctx, key, val).Err(); err != nil {
if err := ctx.Err(); err != nil {
return nil, err
}
if err := b.client.LPush(ctx, key, val).Err(); err != nil {
return nil, err
}

Expand All @@ -267,16 +280,36 @@ func (b *redisBroker) PushJob(db prefixer.Prefixer, req *JobRequest) (*Job, erro
// QueueLen returns the size of the number of elements in queue of the
// specified worker type.
func (b *redisBroker) WorkerQueueLen(workerType string) (int, error) {
return b.queueLen(b.ctx, workerType, false)
}

func (b *redisBroker) queueLen(ctx context.Context, workerType string, primaryOnly bool) (int, error) {
key := redisPrefix + workerType
l1, err := b.client.LLen(b.ctx, key).Result()
if err != nil {
return 0, err
var depth int64
for _, k := range []string{key, key + redisHighPrioritySuffix} {
client := b.client
if primaryOnly {
// A lagging replica can incorrectly report that the last wave drained.
primary, err := b.primaryForKey(ctx, k)
if err != nil {
return 0, err
}
client = primary
}
n, err := client.LLen(ctx, k).Result()
if err != nil {
return 0, err
}
depth += n
}
l2, err := b.client.LLen(b.ctx, key+redisHighPrioritySuffix).Result()
if err != nil {
return 0, err
return int(depth), nil
}

func (b *redisBroker) primaryForKey(ctx context.Context, key string) (redis.UniversalClient, error) {
if cluster, ok := b.client.(*redis.ClusterClient); ok && cluster.Options().ReadOnly {
return cluster.MasterForKey(ctx, key)
}
return int(l1 + l2), nil
return b.client, nil
}

func (b *redisBroker) WorkerIsReserved(workerType string) (bool, error) {
Expand Down
Loading
Loading