go.temporal.io/server/common/finalizer/finalizer.go
164 LOC · 95 covered · 69 uncovered · 26 ranges · 132 concepts · 18 introducers · 40 tests
File neighbourhood
The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.
Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file
In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.
Graph controls are ready.
Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.
package finalizer
import (
"context"
"errors"
"sync"
"time"
cclock "go.temporal.io/server/common/clock"
"go.temporal.io/server/common/goro"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/log/tag"
"go.temporal.io/server/common/metrics"
)
var (
FinalizerAlreadyDoneErr = errors.New("finalizer already finalized")
FinalizerUnknownIdErr = errors.New("finalizer callback not found")
FinalizerDuplicateIdErr = errors.New("finalizer callback already registered")
)
type Finalizer struct {
logger log.Logger
metricsHandler metrics.Handler
mu sync.Mutex
finalized bool
callbacks map[string]func(context.Context) error
}
func New(
logger log.Logger,
metricsHandler metrics.Handler,
return &Finalizer{
logger: logger,
metricsHandler: metricsHandler,
callbacks: make(map[string]func(context.Context) error),
}
}
// Register adds a callback to the finalizer.
// Returns an error if the ID is already registered, or when the finalizer is/was already running.
func (f *Finalizer) Register(
id string,
callback func(context.Context) error,
f.mu.Lock()
defer f.mu.Unlock()
if f.finalized {
return FinalizerAlreadyDoneErr
}
}
return nil
}
// Deregister removes a callback from the finalizer.
// Returns an error if the ID is not found, or when the finalizer is/was already running.
func (f *Finalizer) Deregister(
id string,
f.mu.Lock()
defer f.mu.Unlock()
if f.finalized {
return FinalizerAlreadyDoneErr
}
}
return nil
}
// Run executes all registered callback functions within the given timeout (zero timeout skips execution).
// It can only be invoked once; calling it again has no effect.
// Returns the number of completed callbacks.
func (f *Finalizer) Run(
timeout time.Duration,
if timeout == 0 {
return 0
}
if f.finalized {
f.mu.Unlock()
return 0
}
f.mu.Unlock() // unlocking immediately to unblock any calls to Register/Deregister
totalCount := len(f.callbacks)
if totalCount == 0 {
return 0
}
tag.Int("items", totalCount),
tag.Duration("timeout", timeout))
startTime := time.Now()
defer func() { metrics.FinalizerLatency.With(f.metricsHandler).Record(time.Since(startTime)) }()
defer cancel()
pool := goro.NewAdaptivePool(cclock.NewRealTimeSource(), 5, 15, 10*time.Millisecond, 10)
defer pool.Stop()
completionChannel := make(chan struct{})
go func() {
for _, callback := range f.callbacks {
// NOTE: Once `pool.Stop` is called, any remaining calls to `pool.Do` will do nothing.
pool.Do(func() {
defer func() { completionChannel <- struct{}{} }()
_ = callback(ctx)
})
}
// prevent holding on to the callbacks for longer than needed and allow garbage collection
// (safe since any calls to Register/Deregister will be aborted now that the finalizer ran)
}()
defer func() {
unfinishedItems := int64(totalCount - completedCallbacks)
metrics.FinalizerRuns.With(f.metricsHandler).Record(1)
if unfinishedItems > 0 {
}
metrics.FinalizerItemsCompleted.With(f.metricsHandler).Record(int64(completedCallbacks))
finalizer.go ×6
metrics.FinalizerItemsUnfinished.With(f.metricsHandler).Record(unfinishedItems)
}()
select {
case <-completionChannel:
completedCallbacks += 1
if completedCallbacks == totalCount {
tag.Int("completed", completedCallbacks))
return completedCallbacks
}
f.logger.Error("finalizer timed out",
tag.Int("completed", completedCallbacks),
tag.Int("unfinished", totalCount-completedCallbacks))
return completedCallbacks
}
}
}