aboutsummaryrefslogtreecommitdiff
path: root/setup/process/process.go
blob: 01eb26e2233c191a31038755b4e32f6d2b750d69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package process

import (
	"context"
	"fmt"
	"sync"

	"github.com/getsentry/sentry-go"
	"github.com/sirupsen/logrus"
	"go.uber.org/atomic"
)

type ProcessContext struct {
	wg       *sync.WaitGroup    // used to wait for components to shutdown
	ctx      context.Context    // cancelled when Stop is called
	shutdown context.CancelFunc // shut down Dendrite
	degraded atomic.Bool
}

func NewProcessContext() *ProcessContext {
	ctx, shutdown := context.WithCancel(context.Background())
	return &ProcessContext{
		ctx:      ctx,
		shutdown: shutdown,
		wg:       &sync.WaitGroup{},
	}
}

func (b *ProcessContext) Context() context.Context {
	return context.WithValue(b.ctx, "scope", "process") // nolint:staticcheck
}

func (b *ProcessContext) ComponentStarted() {
	b.wg.Add(1)
}

func (b *ProcessContext) ComponentFinished() {
	b.wg.Done()
}

func (b *ProcessContext) ShutdownDendrite() {
	b.shutdown()
}

func (b *ProcessContext) WaitForShutdown() <-chan struct{} {
	return b.ctx.Done()
}

func (b *ProcessContext) WaitForComponentsToFinish() {
	b.wg.Wait()
}

func (b *ProcessContext) Degraded() {
	if b.degraded.CAS(false, true) {
		logrus.Warn("Dendrite is running in a degraded state")
		sentry.CaptureException(fmt.Errorf("Process is running in a degraded state"))
	}
}

func (b *ProcessContext) IsDegraded() bool {
	return b.degraded.Load()
}