Bound ordinary runs with attributable operation timeouts

This commit is contained in:
2026-11-14 17:37:25 +00:00
parent 2066579e09
commit d42b131de2
6 changed files with 144 additions and 3 deletions

View File

@@ -0,0 +1,36 @@
package usecase
import (
"context"
"errors"
"time"
)
// OperationScope owns an optional deadline and its invocation-specific cause.
type OperationScope struct {
Context context.Context
cancel context.CancelFunc
cause error
}
// NewOperationScope creates a child only when the selected duration is positive.
func NewOperationScope(parent context.Context, duration time.Duration) *OperationScope {
scope := &OperationScope{Context: parent, cancel: func() {}}
if duration > 0 {
scope.cause = errors.New("operation deadline")
scope.Context, scope.cancel = context.WithTimeoutCause(parent, duration, scope.cause)
}
return scope
}
// Finalize preserves the failure and marks it only when this scope expired.
func (s *OperationScope) Finalize(err error) error {
if err != nil && s.cause != nil && s.Context.Err() == context.DeadlineExceeded &&
errors.Is(err, s.Context.Err()) && context.Cause(s.Context) == s.cause {
return &OperationError{Category: ErrOperationTimeout, Cause: err}
}
return err
}
// Close releases the timer and associated child context.
func (s *OperationScope) Close() { s.cancel() }

View File

@@ -0,0 +1,52 @@
package usecase
import (
"context"
"errors"
"testing"
"testing/synctest"
"time"
)
func TestOperationScopeAttribution(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
parent := context.Background()
disabled := NewOperationScope(parent, 0)
defer disabled.Close()
if disabled.Context != parent || disabled.Finalize(context.DeadlineExceeded) != context.DeadlineExceeded {
t.Fatal("disabled scope changed context or error")
}
outer := NewOperationScope(parent, time.Second)
defer outer.Close()
inner := NewOperationScope(outer.Context, 2*time.Second)
defer inner.Close()
time.Sleep(time.Second)
synctest.Wait()
if !errors.Is(outer.Finalize(context.DeadlineExceeded), ErrOperationTimeout) {
t.Fatal("own deadline not attributed")
}
if errors.Is(inner.Finalize(context.DeadlineExceeded), ErrOperationTimeout) {
t.Fatal("inherited scope misattributed")
}
other := errors.New("other")
if outer.Finalize(other) != other || outer.Finalize(nil) != nil {
t.Fatal("unrelated failure or completion changed")
}
canceled, cancel := context.WithCancel(parent)
child := NewOperationScope(canceled, time.Second)
defer child.Close()
cancel()
if errors.Is(child.Finalize(context.Canceled), ErrOperationTimeout) {
t.Fatal("parent cancellation misattributed")
}
deadline, stop := context.WithTimeout(parent, time.Second)
defer stop()
child = NewOperationScope(deadline, 2*time.Second)
defer child.Close()
time.Sleep(time.Second)
synctest.Wait()
if errors.Is(child.Finalize(context.DeadlineExceeded), ErrOperationTimeout) {
t.Fatal("parent deadline misattributed")
}
})
}