Merge pull request #11287 from ziggie1984/fix-submodule-lint
What changed, and why it matters
This is a large housekeeping commit that fixes code-style and lint warnings across many submodules and adds a new CI step to lint those submodules. The only functional code change is a small rewrite of the retry-delay calculation to avoid integer overflow when retry settings are extremely large. There is no evidence of an exploitable vulnerability being fixed, and the commit message does not describe any security issue.
No urgent action required. Treat as routine maintenance. If reviewing for release notes, mention the defensive overflow fix in retry-delay calculation; otherwise, the change is primarily lint/CI hygiene.
Security signals we found
Defensive overflow hardening in retry-delay arithmetic
No memory-safety, cryptographic, authentication, authorization, or network changes
No bugfix or vulnerability disclosure language in commit title/message
Evidence from the diff
The commit is dominated by lint-driven formatting: replacing context.Background() with t.Context()/b.Context() in tests, removing loop capture copies, adding nolint directives for containedctx/gosec, and wrapping long lines. Build/CI changes add a lint-module step and pass GOGC into the lint Docker container. The only non-cosmetic logic change is in sqldb/interfaces.go and sqldb/v2/interfaces.go, where randRetryDelay() was rewritten to cap jitter and exponential backoff before arithmetic overflow can occur, replacing math.Pow-based doubling with a bounded bit-shift factor and explicit overflow checks. New unit tests verify the capping behavior.
Changed components
sqldb/interfaces.gosqldb/v2/interfaces.go.github/workflows/main.ymlMakefileactor package testskvdb package testsqueue package testssqldb package teststor package testsInspect captured patch +624 / −356
### .github/workflows/main.yml
@@ -239,6 +239,9 @@ jobs:
- name: lint
run: GOGC=50 make lint
+ - name: lint submodules
+ run: GOGC=50 make lint-module
+
########################
# cross compilation
########################
### .golangci.yml
@@ -185,6 +185,9 @@ linters:
# Temporary pins for confirmation-controlled lease expiry.
- github.com/btcsuite/btcwallet
- github.com/btcsuite/btcwallet/wtxmgr
+ # The sqldb/v2 module uses a fork of golang-migrate with custom
+ # functionality that is not yet available upstream.
+ - github.com/golang-migrate/migrate/v4
replace-local: true
gosec:
### Makefile
@@ -86,7 +86,7 @@ DOCKER_TOOLS_BASE = docker run \
-v "$${HOME}/.cache/golangci-lint:/root/.cache/golangci-lint" \
-v "$$(pwd):/build"
DOCKER_TOOLS = $(DOCKER_TOOLS_BASE) lnd-tools
-DOCKER_TOOLS_LINT_BASE = $(DOCKER_TOOLS_BASE)
+DOCKER_TOOLS_LINT_BASE = $(DOCKER_TOOLS_BASE) -e GOGC
DOCKER_TOOLS_LINT = $(DOCKER_TOOLS_LINT_BASE) lnd-tools
else
# Local mode: Docker named volumes for fast macOS/Windows performance.
@@ -106,7 +106,7 @@ DOCKER_TOOLS_BASE = docker run \
-v lnd-go-lint-cache:/root/.cache/golangci-lint \
-v "$$(pwd):/build"
DOCKER_TOOLS = $(DOCKER_TOOLS_BASE) lnd-tools
-DOCKER_TOOLS_LINT_BASE = $(DOCKER_TOOLS_BASE) $(GIT_VOLUME)
+DOCKER_TOOLS_LINT_BASE = $(DOCKER_TOOLS_BASE) $(GIT_VOLUME) -e GOGC
DOCKER_TOOLS_LINT = $(DOCKER_TOOLS_LINT_BASE) lnd-tools
endif
### actor/actor.go
@@ -57,7 +57,10 @@ type Actor[M Message, R any] struct {
// mailbox is the incoming message queue for the actor.
mailbox Mailbox[M, R]
- // ctx is the context governing the actor's lifecycle.
+ // ctx is owned by the actor and shared with its mailbox and behavior.
+ // It must remain available until Stop cancels the actor's lifecycle.
+ //
+ //nolint:containedctx
ctx context.Context
// cancel is the function to cancel the actor's context.
@@ -91,6 +94,10 @@ func NewActor[M Message, R any](cfg ActorConfig[M, R]) (*Actor[M, R],
return nil, ErrNilBehavior
}
+ // The cancel func is stored on the actor and called by Stop, which
+ // gosec can't see through.
+ //
+ //nolint:gosec
ctx, cancel := context.WithCancel(context.Background())
// Ensure MailboxSize has a sane default if not specified or zero. A
@@ -192,8 +199,6 @@ type actorRefImpl[M Message, R any] struct {
// Tell sends a message without waiting for a response. If the context is
// cancelled before the message can be sent to the actor's mailbox, the message
// may be dropped.
-//
-//nolint:ll
func (ref *actorRefImpl[M, R]) Tell(ctx context.Context, msg M) {
// If the actor's own context is already done, don't try to send.
// Route to DLO if available.
### actor/actor_test.go
@@ -87,6 +87,7 @@ func (b *echoBehavior) GetLastMsgData() (string, bool) {
return "", false
}
data, ok := val.(string)
+
return data, ok
}
@@ -108,30 +109,6 @@ func (b *errorBehavior) Receive(_ context.Context,
return fn.Err[string](b.err)
}
-// blockingBehavior is an actor behavior that blocks until its actorCtx is done.
-type blockingBehavior struct{}
-
-// Receive blocks until the actor's context is cancelled, then returns the
-// context's error.
-func (b *blockingBehavior) Receive(actorCtx context.Context,
- _ *testMsg) fn.Result[string] {
-
- <-actorCtx.Done()
- return fn.Err[string](actorCtx.Err())
-}
-
-// deadLetterTestMsg is a distinct message type used for testing DLO
-// interactions.
-type deadLetterTestMsg struct {
- BaseMessage
- id string
-}
-
-// MessageType returns the type name of the message.
-func (m *deadLetterTestMsg) MessageType() string {
- return "deadLetterTestMsg"
-}
-
// deadLetterObserverBehavior is a behavior for a test Dead Letter Office actor.
// It records all messages sent to it, allowing tests to verify DLO
// interactions.
@@ -235,6 +212,7 @@ func (h *actorTestHarness) assertDLOMessage(expectedMsg Message) {
return true
}
}
+
return false
}, time.Second, 10*time.Millisecond,
"dLO did not receive expected message: %v", expectedMsg,
@@ -284,13 +262,16 @@ func TestActorStartStop(t *testing.T) {
msgData := "hello"
replyChan := make(chan string, 1)
actor.Ref().Tell(
- context.Background(), newTestMsgWithReply(msgData, replyChan),
+ t.Context(), newTestMsgWithReply(msgData, replyChan),
)
received, err := fn.RecvOrTimeout(replyChan, 100*time.Millisecond)
- require.NoError(t, err, "timed out waiting for actor to process message")
+ require.NoError(
+ t, err, "timed out waiting for actor to process message",
+ )
require.Equal(
- t, msgData, received, "actor did not process message before stop",
+ t, msgData, received,
+ "actor did not process message before stop",
)
actor.Stop()
@@ -301,7 +282,7 @@ func TestActorStartStop(t *testing.T) {
msgDataAfterStop := "message-after-stop"
replyChanAfterStop := make(chan string, 1)
actor.Ref().Tell(
- context.Background(),
+ t.Context(),
newTestMsgWithReply(msgDataAfterStop, replyChanAfterStop),
)
@@ -330,13 +311,18 @@ func TestActorTellBasic(t *testing.T) {
msgData := "tell-message"
replyChan := make(chan string, 1)
actor.Ref().Tell(
- context.Background(), newTestMsgWithReply(msgData, replyChan),
+ t.Context(), newTestMsgWithReply(msgData, replyChan),
)
- receivedTell, errTell := fn.RecvOrTimeout(replyChan, 100*time.Millisecond)
- require.NoError(t, errTell, "timed out waiting for Tell message processing")
+ receivedTell, errTell := fn.RecvOrTimeout(
+ replyChan, 100*time.Millisecond,
+ )
+ require.NoError(
+ t, errTell, "timed out waiting for Tell message processing",
+ )
require.Equal(
- t, msgData, receivedTell, "behavior did not receive Tell message data",
+ t, msgData, receivedTell,
+ "behavior did not receive Tell message data",
)
lastData, ok := beh.GetLastMsgData()
@@ -355,10 +341,12 @@ func TestActorAskSuccess(t *testing.T) {
actor := h.newActor("test-actor-ask-success", beh, 1)
msgData := "ask-message"
- future := actor.Ref().Ask(context.Background(), newTestMsg(msgData))
+ future := actor.Ref().Ask(t.Context(), newTestMsg(msgData))
- result := future.Await(context.Background())
- require.False(t, result.IsErr(), "ask returned an error: %v", result.Err())
+ result := future.Await(t.Context())
+ require.False(
+ t, result.IsErr(), "ask returned an error: %v", result.Err(),
+ )
result.WhenOk(func(val string) {
expectedReply := fmt.Sprintf("echo: %s", msgData)
@@ -382,10 +370,10 @@ func TestActorAskErrorBehavior(t *testing.T) {
actor := h.newActor("test-actor-ask-error", beh, 1)
future := actor.Ref().Ask(
- context.Background(), newTestMsg("ask-error-test"),
+ t.Context(), newTestMsg("ask-error-test"),
)
- result := future.Await(context.Background())
+ result := future.Await(t.Context())
require.True(t, result.IsErr(), "ask should have returned an error")
require.ErrorIs(t, result.Err(), expectedErr, "ask error mismatch")
@@ -411,9 +399,9 @@ func TestFunctionBehaviorFromSimple(t *testing.T) {
actor := h.newActor("test-simple-success", beh, 1)
future := actor.Ref().Ask(
- context.Background(), newTestMsg("hello"),
+ t.Context(), newTestMsg("hello"),
)
- result := future.Await(context.Background())
+ result := future.Await(t.Context())
require.False(
t, result.IsErr(),
"expected success, got: %v", result.Err(),
@@ -437,9 +425,9 @@ func TestFunctionBehaviorFromSimple(t *testing.T) {
actor := h.newActor("test-simple-error", beh, 1)
future := actor.Ref().Ask(
- context.Background(), newTestMsg("hello"),
+ t.Context(), newTestMsg("hello"),
)
- result := future.Await(context.Background())
+ result := future.Await(t.Context())
require.True(t, result.IsErr())
require.ErrorIs(t, result.Err(), expectedErr)
})
### actor/backpressure_mailbox.go
@@ -28,6 +28,8 @@ type BackpressureMailbox[M Message, R any] struct {
closeOnce sync.Once
// actorCtx is the actor's context for lifecycle management.
+ //
+ //nolint:containedctx
actorCtx context.Context
}
### actor/backpressure_mailbox_test.go
@@ -18,7 +18,7 @@ var _ Mailbox[TestMessage, int] = (*BackpressureMailbox[TestMessage, int])(nil)
func TestBackpressureMailboxDropsWhenThresholdReached(t *testing.T) {
t.Parallel()
- ctx := context.Background()
+ ctx := t.Context()
const capacity = 10
const dropThreshold = 5
@@ -52,7 +52,7 @@ func TestBackpressureMailboxDropsWhenThresholdReached(t *testing.T) {
func TestBackpressureMailboxTrySendDrops(t *testing.T) {
t.Parallel()
- ctx := context.Background()
+ ctx := t.Context()
const capacity = 10
const dropThreshold = 3
@@ -86,7 +86,7 @@ func TestBackpressureMailboxTrySendDrops(t *testing.T) {
func TestBackpressureMailboxNeverDropPassesThrough(t *testing.T) {
t.Parallel()
- ctx := context.Background()
+ ctx := t.Context()
const capacity = 5
neverDrop := queue.DropCheckFunc(func(queueLen int) bool {
@@ -112,7 +112,7 @@ func TestBackpressureMailboxNeverDropPassesThrough(t *testing.T) {
func TestBackpressureMailboxDelegatesReceive(t *testing.T) {
t.Parallel()
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
defer cancel()
const capacity = 5
@@ -147,7 +147,7 @@ func TestBackpressureMailboxDelegatesReceive(t *testing.T) {
func TestBackpressureMailboxDelegatesDrain(t *testing.T) {
t.Parallel()
- ctx := context.Background()
+ ctx := t.Context()
const capacity = 5
neverDrop := queue.DropCheckFunc(func(queueLen int) bool {
return false
@@ -180,7 +180,7 @@ func TestBackpressureMailboxDelegatesDrain(t *testing.T) {
func TestBackpressureMailboxSendRespectsActorCtx(t *testing.T) {
t.Parallel()
- actorCtx, actorCancel := context.WithCancel(context.Background())
+ actorCtx, actorCancel := context.WithCancel(t.Context())
const capacity = 1
neverDrop := queue.DropCheckFunc(func(queueLen int) bool {
@@ -194,7 +194,7 @@ func TestBackpressureMailboxSendRespectsActorCtx(t *testing.T) {
env := envelope[TestMessage, int]{
message: TestMessage{Value: 1},
}
- ok := mbox.Send(context.Background(), env)
+ ok := mbox.Send(t.Context(), env)
require.True(t, ok)
// Cancel the actor context. The next blocking send should fail.
@@ -203,7 +203,7 @@ func TestBackpressureMailboxSendRespectsActorCtx(t *testing.T) {
env2 := envelope[TestMessage, int]{
message: TestMessage{Value: 2},
}
- ok = mbox.Send(context.Background(), env2)
+ ok = mbox.Send(t.Context(), env2)
require.False(t, ok, "send should fail when actor context is cancelled")
}
@@ -212,7 +212,7 @@ func TestBackpressureMailboxSendRespectsActorCtx(t *testing.T) {
func TestBackpressureMailboxReceiveAfterClose(t *testing.T) {
t.Parallel()
- ctx := context.Background()
+ ctx := t.Context()
const capacity = 5
neverDrop := queue.DropCheckFunc(func(queueLen int) bool {
return false
@@ -242,7 +242,7 @@ func TestBackpressureMailboxReceiveAfterClose(t *testing.T) {
func TestBackpressureMailboxDrainAfterDrain(t *testing.T) {
t.Parallel()
- ctx := context.Background()
+ ctx := t.Context()
const capacity = 5
neverDrop := queue.DropCheckFunc(func(queueLen int) bool {
return false
@@ -283,7 +283,7 @@ func TestBackpressureMailboxConcurrentSendClose(t *testing.T) {
capacity = 20
)
- ctx := context.Background()
+ ctx := t.Context()
neverDrop := queue.DropCheckFunc(func(queueLen int) bool {
return false
})
@@ -361,7 +361,7 @@ func TestBackpressureMailboxConcurrentSendClose(t *testing.T) {
func TestBackpressureMailboxConcurrentMultiClose(t *testing.T) {
t.Parallel()
- ctx := context.Background()
+ ctx := t.Context()
neverDrop := queue.DropCheckFunc(func(queueLen int) bool {
return false
})
### actor/example_basic_actor_test.go
@@ -27,7 +27,9 @@ type BasicGreetingResponse struct {
// directly using Ask, and then unregistering and stopping it.
func ExampleActor() {
system := actor.NewActorSystem()
- defer system.Shutdown()
+ defer func() {
+ _ = system.Shutdown()
+ }()
//nolint:ll
greeterKey := actor.NewServiceKey[BasicGreetingMsg, BasicGreetingResponse](
### actor/example_router_test.go
@@ -28,7 +28,9 @@ type RouterGreetingResponse struct {
// key and using a router to dispatch messages to them.
func ExampleRouter() {
system := actor.NewActorSystem()
- defer system.Shutdown()
+ defer func() {
+ _ = system.Shutdown()
+ }()
//nolint:ll
routerGreeterKey := actor.NewServiceKey[RouterGreetingMsg, RouterGreetingResponse](
@@ -39,7 +41,8 @@ func ExampleRouter() {
actorID1 := "router-greeter-1"
greeterBehavior1 := actor.NewFunctionBehavior(
func(ctx context.Context,
- msg RouterGreetingMsg) fn.Result[RouterGreetingResponse] {
+ msg RouterGreetingMsg,
+ ) fn.Result[RouterGreetingResponse] {
return fn.Ok(RouterGreetingResponse{
Greeting: "Greetings, " + msg.Name + "!",
@@ -58,7 +61,8 @@ func ExampleRouter() {
actorID2 := "router-greeter-2"
greeterBehavior2 := actor.NewFunctionBehavior(
func(ctx context.Context,
- msg RouterGreetingMsg) fn.Result[RouterGreetingResponse] {
+ msg RouterGreetingMsg,
+ ) fn.Result[RouterGreetingResponse] {
return fn.Ok(RouterGreetingResponse{
Greeting: "Salutations, " + msg.Name + "!",
@@ -80,8 +84,7 @@ func ExampleRouter() {
RouterGreetingResponse](),
system.DeadLetters(),
)
- fmt.Printf("Router %s created for service key '%s'.\n",
- greeterRouter.ID(), "router-greeter-service")
+ fmt.Printf("Router %s created.\n", greeterRouter.ID())
// Send messages through the router.
names := []string{"Alice", "Bob", "Charlie", "David"}
@@ -112,7 +115,7 @@ func ExampleRouter() {
// Output:
// Actor router-greeter-1 spawned.
// Actor router-greeter-2 spawned.
- // Router router(router-greeter-service) created for service key 'router-greeter-service'.
+ // Router router(router-greeter-service) created.
// For Alice: Received 'Greetings, Alice!' from router-greeter-1
// For Bob: Received 'Salutations, Bob!' from router-greeter-2
// For Charlie: Received 'Greetings, Charlie!' from router-greeter-1
### actor/example_struct_actor_test.go
@@ -68,11 +68,13 @@ func (s *StatefulCounterActor) Receive(ctx context.Context,
return fn.Err[CounterResponse](fmt.Errorf("invalid CounterMsg"))
}
-// ExampleActor_stateful demonstrates creating an actor whose behavior is defined
-// by a struct with methods, allowing it to maintain internal state.
+// ExampleActor_stateful demonstrates creating an actor whose behavior is
+// defined by a struct with methods, allowing it to maintain internal state.
func ExampleActor_stateful() {
system := actor.NewActorSystem()
- defer system.Shutdown()
+ defer func() {
+ _ = system.Shutdown()
+ }()
counterServiceKey := actor.NewServiceKey[CounterMsg, CounterResponse](
"struct-counter-service",
### actor/example_tell_only_test.go
@@ -69,7 +69,9 @@ func (l *LoggerActorBehavior) GetLogs() []string {
// messaging with an actor.
func ExampleTellOnlyRef() {
system := actor.NewActorSystem()
- defer system.Shutdown()
+ defer func() {
+ _ = system.Shutdown()
+ }()
// The logger actor doesn't really have a response type for Ask, so we
// use 'any'.
### actor/future.go
@@ -110,7 +110,8 @@ func (f *futureImpl[T]) Await(ctx context.Context) fn.Result[T] {
return *resPtr
case <-ctx.Done():
- // The waiting context was cancelled before the future completed.
+ // The waiting context was cancelled before the future
+ // completed.
return fn.Err[T](ctx.Err())
}
}
@@ -144,8 +145,8 @@ func (f *futureImpl[T]) ThenApply(ctx context.Context,
return
}
- // Otherwise, the original future completed successfully. Apply the
- // transformation function to its result.
+ // Otherwise, the original future completed successfully. Apply
+ // the transformation function to its result.
originalResult.WhenOk(func(res T) {
newValue := fApply(res)
transformedPromise.Complete(fn.Ok(newValue))
### actor/future_test.go
@@ -20,11 +20,11 @@ func TestFutureAwaitContextCancellation(t *testing.T) {
rapid.Check(t, func(t *rapid.T) {
// Test cancellation when the Await context is cancelled via
- // context.Cancel. The underlying future will not be completed, allowing
- // us to test the cancellation path of Await.
+ // context.Cancel. The underlying future will not be completed,
+ // allowing us to test the cancellation path of Await.
prom1 := NewPromise[int]()
fut1 := prom1.Future()
- ctx1, cancel1 := context.WithCancel(context.Background())
+ ctx1, cancel1 := context.WithCancel(t.Context())
// We'll cancel the future immediately after creating it.
cancel1()
@@ -44,7 +44,7 @@ func TestFutureAwaitContextCancellation(t *testing.T) {
// Use a very short timeout that will trigger.
ctx2, cancel2 := context.WithTimeout(
- context.Background(), 1*time.Nanosecond,
+ t.Context(), 1*time.Nanosecond,
)
defer cancel2()
@@ -80,7 +80,7 @@ func TestFutureAwaitFutureCompletes(t *testing.T) {
// Use a background context for Await, as we expect the future
// to complete normally.
- ctx := context.Background()
+ ctx := t.Context()
// Complete the future in a separate goroutine to simulate an
// asynchronous operation.
@@ -133,7 +133,7 @@ func TestFutureThenApplyContextCancellation(t *testing.T) {
// Create a context for ThenApply and cancel it immediately.
ctxApply, cancelApply := context.WithCancel(
- context.Background(),
+ t.Context(),
)
cancelApply()
@@ -150,7 +150,7 @@ func TestFutureThenApplyContextCancellation(t *testing.T) {
// Await the new (transformed) future. Use a background context
// for this Await to isolate the test to the cancellation of
// ctxApply.
- result := newFut.Await(context.Background())
+ result := newFut.Await(t.Context())
require.True(t, result.IsErr())
require.ErrorIs(
@@ -187,7 +187,7 @@ func TestFutureThenApplyOriginalFutureCompletes(t *testing.T) {
// Create a context for ThenApply that should not cancel before
// the original future completes.
ctxApply, cancelApply := context.WithTimeout(
- context.Background(), 50*time.Millisecond,
+ t.Context(), 50*time.Millisecond,
)
defer cancelApply()
@@ -213,7 +213,7 @@ func TestFutureThenApplyOriginalFutureCompletes(t *testing.T) {
// Await our new future which transforms the original future's
// result. Use a background context for this Await.
- result := newFut.Await(context.Background())
+ result := newFut.Await(t.Context())
if originalErr != nil {
// If the original future had an error, the transformed
@@ -230,7 +230,8 @@ func TestFutureThenApplyOriginalFutureCompletes(t *testing.T) {
)
} else {
// If the original future completed successfully, the
- // transformed future should contain the transformed value.
+ // transformed future should contain the transformed
+ // value.
require.False(
t, result.IsErr(),
"ThenApply with original value",
@@ -267,7 +268,7 @@ func TestFutureOnCompleteContextCancellation(t *testing.T) {
// Create a context for OnComplete and cancel it immediately to
// simulate a premature cancellation.
ctxComplete, cancelComplete := context.WithCancel(
- context.Background(),
+ t.Context(),
)
cancelComplete()
@@ -350,7 +351,7 @@ func TestFutureOnCompleteFutureCompletes(t *testing.T) {
// Use a background context for OnComplete, as we expect the
// future to complete normally.
- ctxComplete := context.Background()
+ ctxComplete := t.Context()
var wg sync.WaitGroup
wg.Add(1)
@@ -441,7 +442,7 @@ func TestCompleteWith(t *testing.T) {
promise := NewPromise[int]()
CompleteWith(promise, 42)
- result := promise.Future().Await(context.Background())
+ result := promise.Future().Await(t.Context())
require.False(t, result.IsErr())
result.WhenOk(func(v int) {
require.Equal(t, 42, v)
@@ -450,10 +451,12 @@ func TestCompleteWith(t *testing.T) {
// Second call must be a no-op; the future must still hold 42.
CompleteWith(promise, 99)
- result2 := promise.Future().Await(context.Background())
+ result2 := promise.Future().Await(t.Context())
require.False(t, result2.IsErr())
result2.WhenOk(func(v int) {
- require.Equal(t, 42, v, "second CompleteWith must not overwrite")
+ require.Equal(
+ t, 42, v, "second CompleteWith must not overwrite",
+ )
})
}
@@ -468,7 +471,7 @@ func TestAwaitFuture(t *testing.T) {
promise := NewPromise[string]()
CompleteWith(promise, "hello")
- val, err := AwaitFuture(context.Background(), promise.Future())
+ val, err := AwaitFuture(t.Context(), promise.Future())
require.NoError(t, err)
require.Equal(t, "hello", val)
@@ -478,13 +481,13 @@ func TestAwaitFuture(t *testing.T) {
errPromise := NewPromise[string]()
errPromise.Complete(fn.Err[string](sentinel))
- val3, err3 := AwaitFuture(context.Background(), errPromise.Future())
+ val3, err3 := AwaitFuture(t.Context(), errPromise.Future())
require.ErrorIs(t, err3, sentinel)
require.Equal(t, "", val3, "zero value expected on fn.Err result")
// Cancelled context — should return the zero value and ctx.Err().
unresolved := NewPromise[string]()
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
cancel()
val2, err2 := AwaitFuture(ctx, unresolved.Future())
@@ -514,7 +517,7 @@ func TestPromiseCompleteIdempotency(t *testing.T) {
require.False(t, ok, "third Complete should return false")
// The future should contain the first value.
- result := future.Await(context.Background())
+ result := future.Await(t.Context())
require.False(t, result.IsErr(), "future should not be an error")
result.WhenOk(func(val string) {
require.Equal(
### actor/mailbox.go
@@ -49,6 +49,8 @@ type ChannelMailbox[M Message, R any] struct {
closeOnce sync.Once
// actorCtx is the actor's context for lifecycle management.
+ //
+ //nolint:containedctx
actorCtx context.Context
}
@@ -60,6 +62,7 @@ func NewChannelMailbox[M Message, R any](actorCtx context.Context,
if capacity <= 0 {
capacity = 1
}
+
return &ChannelMailbox[M, R]{
ch: make(chan envelope[M, R], capacity),
actorCtx: actorCtx,
@@ -108,6 +111,7 @@ func (m *ChannelMailbox[M, R]) TrySend(env envelope[M, R]) bool {
// Receive implements Mailbox.Receive using iter.Seq pattern.
func (m *ChannelMailbox[M, R]) Receive(
ctx context.Context) iter.Seq[envelope[M, R]] {
+
return func(yield func(envelope[M, R]) bool) {
for {
select {
### actor/mailbox_test.go
@@ -22,8 +22,8 @@ func (tm TestMessage) MessageType() string {
// TestChannelMailboxSend tests the Send method of ChannelMailbox.
func TestChannelMailboxSend(t *testing.T) {
t.Run("successful send", func(t *testing.T) {
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 10)
- ctx := context.Background()
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 10)
+ ctx := t.Context()
env := envelope[TestMessage, int]{
message: TestMessage{Value: 42},
promise: nil,
@@ -34,15 +34,15 @@ func TestChannelMailboxSend(t *testing.T) {
})
t.Run("send with cancelled context", func(t *testing.T) {
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 1)
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 1)
// Fill the mailbox first.
env := envelope[TestMessage, int]{
message: TestMessage{Value: 42},
promise: nil,
}
mailbox.TrySend(env)
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
// Cancel immediately.
cancel()
@@ -52,14 +52,16 @@ func TestChannelMailboxSend(t *testing.T) {
}
sent := mailbox.Send(ctx, env2)
- require.False(t, sent, "Send should fail with cancelled context")
+ require.False(
+ t, sent, "Send should fail with cancelled context",
+ )
})
t.Run("send to closed mailbox", func(t *testing.T) {
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 10)
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 10)
mailbox.Close()
- ctx := context.Background()
+ ctx := t.Context()
env := envelope[TestMessage, int]{
message: TestMessage{Value: 42},
promise: nil,
@@ -73,7 +75,7 @@ func TestChannelMailboxSend(t *testing.T) {
// TestChannelMailboxTrySend tests the TrySend method of ChannelMailbox.
func TestChannelMailboxTrySend(t *testing.T) {
t.Run("successful try send", func(t *testing.T) {
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 10)
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 10)
env := envelope[TestMessage, int]{
message: TestMessage{Value: 42},
promise: nil,
@@ -84,7 +86,7 @@ func TestChannelMailboxTrySend(t *testing.T) {
})
t.Run("try send to full mailbox", func(t *testing.T) {
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 1)
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 1)
env := envelope[TestMessage, int]{
message: TestMessage{Value: 42},
promise: nil,
@@ -100,7 +102,7 @@ func TestChannelMailboxTrySend(t *testing.T) {
})
t.Run("try send to closed mailbox", func(t *testing.T) {
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 10)
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 10)
mailbox.Close()
env := envelope[TestMessage, int]{
@@ -116,11 +118,11 @@ func TestChannelMailboxTrySend(t *testing.T) {
// TestChannelMailboxReceive tests the Receive method of ChannelMailbox.
func TestChannelMailboxReceive(t *testing.T) {
t.Run("receive messages", func(t *testing.T) {
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 10)
- ctx := context.Background()
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 10)
+ ctx := t.Context()
// Send some messages.
- for i := 0; i < 3; i++ {
+ for i := range 3 {
env := envelope[TestMessage, int]{
message: TestMessage{Value: i},
promise: nil,
@@ -144,19 +146,22 @@ func TestChannelMailboxReceive(t *testing.T) {
wg.Wait()
require.Len(t, received, 3, "Should receive 3 messages")
- require.Equal(t, []int{0, 1, 2}, received, "Should receive messages in order")
+ require.Equal(
+ t, []int{0, 1, 2}, received,
+ "Should receive messages in order",
+ )
})
t.Run("receive with cancelled context", func(t *testing.T) {
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 10)
- ctx, cancel := context.WithCancel(context.Background())
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 10)
+ ctx, cancel := context.WithCancel(t.Context())
// Send a message.
env := envelope[TestMessage, int]{
message: TestMessage{Value: 42},
promise: nil,
}
- mailbox.Send(context.Background(), env)
+ mailbox.Send(t.Context(), env)
// Start receiving.
var received int
@@ -182,12 +187,16 @@ func TestChannelMailboxReceive(t *testing.T) {
// TestChannelMailboxClose tests the Close and IsClosed methods.
func TestChannelMailboxClose(t *testing.T) {
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 10)
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 10)
- require.False(t, mailbox.IsClosed(), "Mailbox should not be closed initially")
+ require.False(
+ t, mailbox.IsClosed(), "Mailbox should not be closed initially",
+ )
mailbox.Close()
- require.True(t, mailbox.IsClosed(), "Mailbox should be closed after Close()")
+ require.True(
+ t, mailbox.IsClosed(), "Mailbox should be closed after Close()",
+ )
// Closing again should be safe.
mailbox.Close()
@@ -196,11 +205,11 @@ func TestChannelMailboxClose(t *testing.T) {
// TestChannelMailboxDrain tests the Drain method of ChannelMailbox.
func TestChannelMailboxDrain(t *testing.T) {
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 10)
- ctx := context.Background()
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 10)
+ ctx := t.Context()
// Send some messages.
- for i := 0; i < 3; i++ {
+ for i := range 3 {
env := envelope[TestMessage, int]{
message: TestMessage{Value: i},
promise: nil,
@@ -218,27 +227,31 @@ func TestChannelMailboxDrain(t *testing.T) {
}
require.Len(t, drained, 3, "Should drain 3 messages")
- require.Equal(t, []int{0, 1, 2}, drained, "Should drain messages in order")
+ require.Equal(
+ t, []int{0, 1, 2}, drained, "Should drain messages in order",
+ )
}
// TestChannelMailboxConcurrent tests concurrent operations on ChannelMailbox.
func TestChannelMailboxConcurrent(t *testing.T) {
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 100)
- ctx := context.Background()
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 100)
+ ctx := t.Context()
const numSenders = 10
const messagesPerSender = 100
var wg sync.WaitGroup
// Start multiple senders.
- for i := 0; i < numSenders; i++ {
+ for i := range numSenders {
wg.Add(1)
go func(senderID int) {
defer wg.Done()
- for j := 0; j < messagesPerSender; j++ {
+ for j := range messagesPerSender {
env := envelope[TestMessage, int]{
- message: TestMessage{Value: senderID*1000 + j},
+ message: TestMessage{
+ Value: senderID*1000 + j,
+ },
promise: nil,
}
mailbox.Send(ctx, env)
@@ -270,7 +283,7 @@ func TestChannelMailboxConcurrent(t *testing.T) {
// TestChannelMailboxZeroCapacity tests that zero capacity defaults to 1.
func TestChannelMailboxZeroCapacity(t *testing.T) {
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 0)
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 0)
// Should default to capacity of 1.
env := envelope[TestMessage, int]{
@@ -290,7 +303,7 @@ func TestChannelMailboxZeroCapacity(t *testing.T) {
// context for cancellation.
func TestChannelMailboxActorContext(t *testing.T) {
t.Run("send respects actor context", func(t *testing.T) {
- actorCtx, actorCancel := context.WithCancel(context.Background())
+ actorCtx, actorCancel := context.WithCancel(t.Context())
mailbox := NewChannelMailbox[TestMessage, int](actorCtx, 1)
// Fill the mailbox.
@@ -305,29 +318,32 @@ func TestChannelMailboxActorContext(t *testing.T) {
// Try to send with a fresh caller context - should fail due to
// actor context cancellation.
- callerCtx := context.Background()
+ callerCtx := t.Context()
env2 := envelope[TestMessage, int]{
message: TestMessage{Value: 43},
promise: nil,
}
sent := mailbox.Send(callerCtx, env2)
- require.False(t, sent, "Send should fail when actor context is cancelled")
+ require.False(
+ t, sent,
+ "Send should fail when actor context is cancelled",
+ )
})
t.Run("receive respects actor context", func(t *testing.T) {
- actorCtx, actorCancel := context.WithCancel(context.Background())
+ actorCtx, actorCancel := context.WithCancel(t.Context())
mailbox := NewChannelMailbox[TestMessage, int](actorCtx, 10)
// Send a message.
env := envelope[TestMessage, int]{
message: TestMessage{Value: 42},
promise: nil,
}
- mailbox.Send(context.Background(), env)
+ mailbox.Send(t.Context(), env)
// Start receiving with a fresh context.
- callerCtx := context.Background()
+ callerCtx := t.Context()
var received int
var wg sync.WaitGroup
wg.Add(1)
@@ -343,7 +359,8 @@ func TestChannelMailboxActorContext(t *testing.T) {
actorCancel()
wg.Wait()
- // Should have stopped receiving due to actor context cancellation.
+ // Should have stopped receiving due to actor context
+ // cancellation.
require.LessOrEqual(t, received, 1,
"Should stop receiving when actor context is cancelled")
})
@@ -355,8 +372,8 @@ func TestMailboxConcurrentSendAndClose(t *testing.T) {
const numSenders = 20
const sendsPerSender = 100
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 100)
- ctx := context.Background()
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 100)
+ ctx := t.Context()
var wg sync.WaitGroup
@@ -371,13 +388,15 @@ func TestMailboxConcurrentSendAndClose(t *testing.T) {
}()
// Start multiple senders.
- for i := 0; i < numSenders; i++ {
+ for i := range numSenders {
wg.Add(1)
go func(senderID int) {
defer wg.Done()
- for j := 0; j < sendsPerSender; j++ {
+ for j := range sendsPerSender {
env := envelope[TestMessage, int]{
- message: TestMessage{Value: senderID*1000 + j},
+ message: TestMessage{
+ Value: senderID*1000 + j,
+ },
promise: nil,
}
// Send may fail if mailbox closes, that's ok.
@@ -388,7 +407,7 @@ func TestMailboxConcurrentSendAndClose(t *testing.T) {
// Concurrently close the mailbox multiple times from different
// goroutines.
- for i := 0; i < 5; i++ {
+ for range 5 {
wg.Add(1)
go func() {
defer wg.Done()
@@ -417,28 +436,31 @@ func TestMailboxConcurrentTrySendAndClose(t *testing.T) {
const numSenders = 20
const sendsPerSender = 100
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 10)
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 10)
var wg sync.WaitGroup
// Start multiple senders using TrySend.
- for i := 0; i < numSenders; i++ {
+ for i := range numSenders {
wg.Add(1)
go func(senderID int) {
defer wg.Done()
- for j := 0; j < sendsPerSender; j++ {
+ for j := range sendsPerSender {
env := envelope[TestMessage, int]{
- message: TestMessage{Value: senderID*1000 + j},
+ message: TestMessage{
+ Value: senderID*1000 + j,
+ },
promise: nil,
}
- // TrySend may fail if mailbox is full or closed.
+ // TrySend may fail if mailbox is full or
+ // closed.
mailbox.TrySend(env)
}
}(i)
}
// Concurrently close the mailbox.
- for i := 0; i < 5; i++ {
+ for range 5 {
wg.Add(1)
go func() {
defer wg.Done()
@@ -465,12 +487,12 @@ func TestMailboxConcurrentTrySendAndClose(t *testing.T) {
func TestMailboxMultipleCloseCallers(t *testing.T) {
const numClosers = 100
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 10)
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 10)
var wg sync.WaitGroup
// Start many goroutines all trying to close the mailbox.
- for i := 0; i < numClosers; i++ {
+ for range numClosers {
wg.Add(1)
go func() {
defer wg.Done()
@@ -494,19 +516,21 @@ func TestMailboxCloseWhileSending(t *testing.T) {
const numSenders = 10
const sendsPerSender = 1000
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 100)
- ctx := context.Background()
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 100)
+ ctx := t.Context()
var sendWg sync.WaitGroup
// Start multiple senders.
- for i := 0; i < numSenders; i++ {
+ for i := range numSenders {
sendWg.Add(1)
go func(senderID int) {
defer sendWg.Done()
- for j := 0; j < sendsPerSender; j++ {
+ for j := range sendsPerSender {
env := envelope[TestMessage, int]{
- message: TestMessage{Value: senderID*1000 + j},
+ message: TestMessage{
+ Value: senderID*1000 + j,
+ },
promise: nil,
}
// Send may fail after close, that's expected.
@@ -547,19 +571,21 @@ func TestMailboxStressTest(t *testing.T) {
const numReceivers = 5
const sendsPerSender = 200
- mailbox := NewChannelMailbox[TestMessage, int](context.Background(), 200)
- ctx := context.Background()
+ mailbox := NewChannelMailbox[TestMessage, int](t.Context(), 200)
+ ctx := t.Context()
var sendWg sync.WaitGroup
// Start multiple senders.
- for i := 0; i < numSenders; i++ {
+ for i := range numSenders {
sendWg.Add(1)
go func(senderID int) {
defer sendWg.Done()
- for j := 0; j < sendsPerSender; j++ {
+ for j := range sendsPerSender {
env := envelope[TestMessage, int]{
- message: TestMessage{Value: senderID*1000 + j},
+ message: TestMessage{
+ Value: senderID*1000 + j,
+ },
promise: nil,
}
mailbox.Send(ctx, env)
@@ -569,7 +595,7 @@ func TestMailboxStressTest(t *testing.T) {
// Start multiple receivers.
var recvWg sync.WaitGroup
- for i := 0; i < numReceivers; i++ {
+ for range numReceivers {
recvWg.Add(1)
go func() {
defer recvWg.Done()
### actor/router.go
@@ -47,6 +47,7 @@ func NewRoundRobinStrategy[M Message, R any]() *RoundRobinStrategy[M, R] {
func (s *RoundRobinStrategy[M, R]) Select(
refs []ActorRef[M, R],
) (ActorRef[M, R], error) {
+
if len(refs) == 0 {
return nil, ErrNoActorsAvailable
}
### actor/system.go
@@ -55,6 +55,8 @@ type ActorSystem struct {
mu sync.RWMutex
// ctx is the main context for the actor system.
+ //
+ //nolint:containedctx
ctx context.Context
// cancel cancels the main system context.
@@ -66,7 +68,8 @@ func NewActorSystem() *ActorSystem {
return NewActorSystemWithConfig(DefaultConfig())
}
-// NewActorSystemWithConfig creates a new actor system with custom configuration
+// NewActorSystemWithConfig creates a new actor system with custom
+// configuration.
func NewActorSystemWithConfig(config SystemConfig) *ActorSystem {
ctx, cancel := context.WithCancel(context.Background())
@@ -433,8 +436,9 @@ func FindInReceptionist[M Message, R any](r *Receptionist,
typedRefs := make([]ActorRef[M, R], 0, len(refs))
for _, ref := range refs {
// Make sure that the reference is of the correct type.
- // This type assertion is crucial for type safety, ensuring
- // that the returned ActorRefs match the expected M and R.
+ // This type assertion is crucial for type safety,
+ // ensuring that the returned ActorRefs match the
+ // expected M and R.
if typedRef, ok := ref.(ActorRef[M, R]); ok {
typedRefs = append(typedRefs, typedRef)
}
### actor/system_test.go
@@ -21,12 +21,14 @@ func TestActorSystemNewActorSystem(t *testing.T) {
require.NotNil(t, as, "newActorSystem should not return nil")
require.NotNil(t, as.Receptionist(), "receptionist should not be nil")
require.NotNil(t, as.DeadLetters(), "deadLetters should not be nil")
- require.Equal(t, "dead-letters", as.DeadLetters().ID(), "dLO ID mismatch")
+ require.Equal(
+ t, "dead-letters", as.DeadLetters().ID(), "dLO ID mismatch",
+ )
// Test the DLO's behavior (it should return an error for Ask).
testDLOMsg := newTestMsg("to-dlo")
- future := as.DeadLetters().Ask(context.Background(), testDLOMsg)
- result := future.Await(context.Background())
+ future := as.DeadLetters().Ask(t.Context(), testDLOMsg)
+ result := future.Await(t.Context())
// We should get back an error for asks.
require.True(
@@ -62,22 +64,29 @@ func TestActorSystemRegisterWithSystem(t *testing.T) {
// We'll start off by registering the actor.
actorRef, err := RegisterWithSystem(as, actorID, serviceKey, beh)
require.NoError(t, err)
- require.NotNil(t, actorRef, "registerWithSystem should return a valid ActorRef")
+ require.NotNil(
+ t, actorRef,
+ "registerWithSystem should return a valid ActorRef",
+ )
require.Equal(t, actorID, actorRef.ID(), "registered actor ID mismatch")
// The actor should be found in the receptionist.
foundActors := FindInReceptionist(as.Receptionist(), serviceKey)
require.Len(t, foundActors, 1, "actor not found in receptionist")
- require.Equal(t, actorRef, foundActors[0], "incorrect actor in receptionist")
+ require.Equal(
+ t, actorRef, foundActors[0], "incorrect actor in receptionist",
+ )
// Next, we'll send out a simple tell, using our reply channel to make
// sure it's actually processed.
msgData := "hello-system-actor"
replyChan := make(chan string, 1)
- actorRef.Tell(context.Background(), newTestMsgWithReply(msgData, replyChan))
+ actorRef.Tell(t.Context(), newTestMsgWithReply(msgData, replyChan))
received, err := fn.RecvOrTimeout(replyChan, 100*time.Millisecond)
- require.NoError(t, err, "timed out waiting for actor to process message")
+ require.NoError(
+ t, err, "timed out waiting for actor to process message",
+ )
require.Equal(t, msgData, received, "actor did not process message")
// Stop the actor through the system.
@@ -91,7 +100,7 @@ func TestActorSystemRegisterWithSystem(t *testing.T) {
// system's DLO.
afterStopMsg := newTestMsg("after-stop-to-dlo")
require.NotPanics(t, func() {
- actorRef.Tell(context.Background(), afterStopMsg)
+ actorRef.Tell(t.Context(), afterStopMsg)
}, "tell to stopped actor should not panic")
}
@@ -105,7 +114,7 @@ func TestActorSystemShutdown(t *testing.T) {
// We'll start by making 3 new actors, each with a unique ID.
numActors := 3
actorRefs := make([]ActorRef[*testMsg, string], numActors)
- for i := 0; i < numActors; i++ {
+ for i := range numActors {
actorID := fmt.Sprintf("shutdown-test-actor-%d", i)
key := NewServiceKey[*testMsg, string](
fmt.Sprintf("service-%d", i),
@@ -120,11 +129,11 @@ func TestActorSystemShutdown(t *testing.T) {
// running.
for i, ref := range actorRefs {
future := ref.Ask(
- context.Background(),
+ t.Context(),
newTestMsg(fmt.Sprintf("ping-%d", i)),
)
ctxAwait, cancelAwait := context.WithTimeout(
- context.Background(), time.Second,
+ t.Context(), time.Second,
)
res := future.Await(ctxAwait)
cancelAwait()
@@ -143,16 +152,18 @@ func TestActorSystemShutdown(t *testing.T) {
// Check if the system context is done using RecvOrTimeout with a zero
// timeout for a non-blocking check.
_, err = fn.RecvOrTimeout(as.ctx.Done(), time.Millisecond*100)
- require.NoError(t, err, "actorSystem context not cancelled after shutdown")
+ require.NoError(
+ t, err, "actorSystem context not cancelled after shutdown",
+ )
// We'll now try to send a message to each of the actors, this should
// result in an error.
for i, ref := range actorRefs {
future := ref.Ask(
- context.Background(),
+ t.Context(),
newTestMsg(fmt.Sprintf("ping-after-shutdown-%d", i)),
)
- res := future.Await(context.Background())
+ res := future.Await(t.Context())
require.True(
t, res.IsErr(),
"actor %d Ask should fail after shutdown", i,
@@ -167,9 +178,9 @@ func TestActorSystemShutdown(t *testing.T) {
// Once shutdown, we shouldn't be able to send to the DLO either.
dloRef := as.DeadLetters()
futureDLO := dloRef.Ask(
- context.Background(), newTestMsg("ping-dlo-after-shutdown"),
+ t.Context(), newTestMsg("ping-dlo-after-shutdown"),
)
- resDLO := futureDLO.Await(context.Background())
+ resDLO := futureDLO.Await(t.Context())
require.True(
t, resDLO.IsErr(), "DLO Ask should fail after system shutdown",
)
@@ -207,8 +218,8 @@ func TestActorSystemStopAndRemoveActor(t *testing.T) {
stopped := as.StopAndRemoveActor(actor1ID)
require.True(t, stopped, "failed to stop and remove actor1")
- future1 := ref1.Ask(context.Background(), newTestMsg("ping-actor1"))
- res1 := future1.Await(context.Background())
+ future1 := ref1.Ask(t.Context(), newTestMsg("ping-actor1"))
+ res1 := future1.Await(t.Context())
require.True(t, res1.IsErr(), "actor1 should be stopped")
require.ErrorIs(t, res1.Err(), ErrActorTerminated)
@@ -221,11 +232,11 @@ func TestActorSystemStopAndRemoveActor(t *testing.T) {
// Make sure that we can still send messages to the existing actor.
future2 := ref2.Ask(
- context.Background(), newTestMsg("ping-actor2"),
+ t.Context(), newTestMsg("ping-actor2"),
)
ctxAwait2, cancelAwait2 := context.WithTimeout(
- context.Background(), time.Second,
+ t.Context(), time.Second,
)
res2 := future2.Await(ctxAwait2)
cancelAwait2()
@@ -299,24 +310,34 @@ func TestReceptionist(t *testing.T) {
require.Equal(t, actor2Ref, foundForKey1AfterUnreg[0])
// If we try to unregister the same actor again, it should fail.
- unregisteredAgain := UnregisterFromReceptionist(receptionist, key1, actor1Ref)
+ unregisteredAgain := UnregisterFromReceptionist(
+ receptionist, key1, actor1Ref,
+ )
require.False(t, unregisteredAgain)
- unregisteredLast := UnregisterFromReceptionist(receptionist, key1, actor2Ref)
+ unregisteredLast := UnregisterFromReceptionist(
+ receptionist, key1, actor2Ref,
+ )
require.True(t, unregisteredLast)
foundForKey1AfterAllUnreg := FindInReceptionist(receptionist, key1)
require.Empty(t, foundForKey1AfterAllUnreg)
receptionist.mu.RLock()
_, exists := receptionist.registrations[key1.name]
receptionist.mu.RUnlock()
- require.False(t, exists, "key1 should be removed from registrations map")
+ require.False(
+ t, exists, "key1 should be removed from registrations map",
+ )
// Finally, if we use the wrong key, or one that doesn't exist, that
// should also fail.
- unregisteredWrongKey := UnregisterFromReceptionist(receptionist, key1, actor3Ref)
+ unregisteredWrongKey := UnregisterFromReceptionist(
+ receptionist, key1, actor3Ref,
+ )
require.False(t, unregisteredWrongKey)
- unregisteredNonExistentKey := UnregisterFromReceptionist(receptionist, nonExistentKey, actor1Ref)
+ unregisteredNonExistentKey := UnregisterFromReceptionist(
+ receptionist, nonExistentKey, actor1Ref,
+ )
require.False(t, unregisteredNonExistentKey)
}
@@ -365,8 +386,8 @@ func TestServiceKeyMethods(t *testing.T) {
// If we try to send a message to the actor after unregistering it, then
// we should get an error.
- future := actorRef.Ask(context.Background(), newTestMsg("ping"))
- res := future.Await(context.Background())
+ future := actorRef.Ask(t.Context(), newTestMsg("ping"))
+ res := future.Await(t.Context())
require.True(t, res.IsErr() && errors.Is(res.Err(), ErrActorTerminated))
successAgain := key.Unregister(as, actorRef)
@@ -473,8 +494,8 @@ func TestServiceKeyUnregisterAll(t *testing.T) {
// Verify actors are stopped.
resultActor1Key1 := actor1Key1.Ask(
- context.Background(), newTestMsg("ping-k1-a1"),
- ).Await(context.Background())
+ t.Context(), newTestMsg("ping-k1-a1"),
+ ).Await(t.Context())
require.True(
st, resultActor1Key1.IsErr(),
"Actor1 key1 Ask should fail after UnregisterAll.",
@@ -485,8 +506,8 @@ func TestServiceKeyUnregisterAll(t *testing.T) {
)
resultActor2Key1 := actor2Key1.Ask(
- context.Background(), newTestMsg("ping-k1-a2"),
- ).Await(context.Background())
+ t.Context(), newTestMsg("ping-k1-a2"),
+ ).Await(t.Context())
require.True(
st, resultActor2Key1.IsErr(),
"Actor2 key1 Ask should fail after UnregisterAll.",
@@ -587,16 +608,16 @@ func TestServiceKeyUnregisterAll(t *testing.T) {
// Verify keyA actors are stopped, keyB actor is running.
resultActorA1Mixed := actorA1.Ask(
- context.Background(), newTestMsg("ping-kA-a1"),
- ).Await(context.Background())
+ t.Context(), newTestMsg("ping-kA-a1"),
+ ).Await(t.Context())
require.True(st, resultActorA1Mixed.IsErr())
require.ErrorIs(
st, resultActorA1Mixed.Err(), ErrActorTerminated,
)
resultActorB1Mixed := actorB1.Ask(
- context.Background(), newTestMsg("ping-kB-a1"),
- ).Await(context.Background())
+ t.Context(), newTestMsg("ping-kB-a1"),
+ ).Await(t.Context())
require.False(
st, resultActorB1Mixed.IsErr(),
"ActorB1 terminated incorrectly (mixed test): %v",
@@ -632,7 +653,8 @@ func TestServiceKeyUnregisterAll(t *testing.T) {
// Verify actor is gone from receptionist and system map, and is
// stopped.
require.Empty(
- st, FindInReceptionist(as.Receptionist(), keyIdempotent),
+ st,
+ FindInReceptionist(as.Receptionist(), keyIdempotent),
"Actors for keyIdempotent still in receptionist "+
"after calls.",
)
@@ -646,14 +668,15 @@ func TestServiceKeyUnregisterAll(t *testing.T) {
)
resultActorIdem := actorIdem.Ask(
- context.Background(), newTestMsg("ping-kidem-a1"),
- ).Await(context.Background())
+ t.Context(), newTestMsg("ping-kidem-a1"),
+ ).Await(t.Context())
require.True(st, resultActorIdem.IsErr())
require.ErrorIs(st, resultActorIdem.Err(), ErrActorTerminated)
})
}
-// routerTestHarness helps set up routers and their associated actors for testing.
+// routerTestHarness helps set up routers and their associated actors for
+// testing.
// It uses an actorTestHarness internally for DLO observation for the router.
type routerTestHarness struct {
*actorTestHarness
@@ -669,11 +692,14 @@ func newRouterTestHarness(t *testing.T) *routerTestHarness {
system := NewActorSystem()
t.Cleanup(func() {
err := system.Shutdown()
- require.NoError(t, err, "router test actor system shutdown failed")
+ require.NoError(
+ t, err, "router test actor system shutdown failed",
+ )
})
// The DLO for the router itself will come from actorTestHarness.
- // Actors managed by `system` (router targets) will use `system.DeadLetters()`.
+ // Actors managed by `system` (router targets) will use
+ // `system.DeadLetters()`.
return &routerTestHarness{
actorTestHarness: newActorTestHarness(t),
as: system,
@@ -706,7 +732,9 @@ func TestRouterNewRouter(t *testing.T) {
router := NewRouter(h.receptionist, key, strategy, h.dlo.Ref())
require.NotNil(t, router, "newRouter should not return nil")
- require.Equal(t, "router(router-service)", router.ID(), "router ID mismatch")
+ require.Equal(
+ t, "router(router-service)", router.ID(), "router ID mismatch",
+ )
}
// countingEchoBehavior is an echo behavior that also counts how many messages
@@ -735,6 +763,7 @@ func (b *countingEchoBehavior) Receive(ctx context.Context,
if err == nil {
return fn.Ok(fmt.Sprintf("%s:%s", b.id, val))
}
+
return res
}
@@ -758,22 +787,23 @@ func TestRouterTellAndAskRoundRobin(t *testing.T) {
// Nxet, we'll send a mix of Tell and Ask messages to the router.
numMessages := 6
- for i := 0; i < numMessages; i++ {
+ for i := range numMessages {
msgData := fmt.Sprintf("message-%d", i)
if i%2 == 0 {
- router.Tell(context.Background(), newTestMsg(msgData))
+ router.Tell(t.Context(), newTestMsg(msgData))
} else {
future := router.Ask(
- context.Background(), newTestMsg(msgData),
+ t.Context(), newTestMsg(msgData),
)
ctxAwait, cancelAwait := context.WithTimeout(
- context.Background(), time.Second,
+ t.Context(), time.Second,
)
result := future.Await(ctxAwait)
cancelAwait()
require.False(
- t, result.IsErr(), "ask failed: %v", result.Err(),
+ t, result.IsErr(), "ask failed: %v",
+ result.Err(),
)
}
}
@@ -807,16 +837,17 @@ func TestRouterNoActorsAvailable(t *testing.T) {
// We'll send a message, then assert that it goes to the DLO.
tellMsg := newTestMsg("tell-no-actor")
- router.Tell(context.Background(), tellMsg)
+ router.Tell(t.Context(), tellMsg)
h.assertDLOMessage(tellMsg)
// If we use an ask instead, then we should get an error.
askMsg := newTestMsg("ask-no-actor")
- future := router.Ask(context.Background(), askMsg)
- result := future.Await(context.Background())
+ future := router.Ask(t.Context(), askMsg)
+ result := future.Await(t.Context())
require.True(
- t, result.IsErr(), "ask should fail when no actors are available",
+ t, result.IsErr(),
+ "ask should fail when no actors are available",
)
require.ErrorIs(t, result.Err(), ErrNoActorsAvailable, "error mismatch")
}
@@ -837,7 +868,7 @@ func TestRouterTellAskContextCancellation(t *testing.T) {
// Next, we'll send a Tell message with a context that will be cancelled
// before we even send.
- ctxTell, cancelTell := context.WithCancel(context.Background())
+ ctxTell, cancelTell := context.WithCancel(t.Context())
cancelTell()
router.Tell(ctxTell, newTestMsg("tell-ctx-cancelled"))
@@ -846,10 +877,10 @@ func TestRouterTellAskContextCancellation(t *testing.T) {
h.assertNoDLOMessages()
// Next, we'll do the same for Ask. This time, we should get an error.
- ctxAsk, cancelAsk := context.WithCancel(context.Background())
+ ctxAsk, cancelAsk := context.WithCancel(t.Context())
cancelAsk()
futureAsk := router.Ask(ctxAsk, newTestMsg("ask-ctx-cancelled"))
- resultAsk := futureAsk.Await(context.Background())
+ resultAsk := futureAsk.Await(t.Context())
require.True(
t, resultAsk.IsErr(), "ask with cancelled context should fail",
@@ -872,20 +903,27 @@ func TestRouterDynamicActorRegistration(t *testing.T) {
// If we try to send a mesasge to the router before any actors are
// added, we should get an error.
- futureNoActor := router.Ask(context.Background(), newTestMsg("ping-no-actors"))
- resNoActor := futureNoActor.Await(context.Background())
+ futureNoActor := router.Ask(t.Context(), newTestMsg("ping-no-actors"))
+ resNoActor := futureNoActor.Await(t.Context())
require.ErrorIs(t, resNoActor.Err(), ErrNoActorsAvailable)
actor1Beh := newCountingEchoBehavior(t, "actor1")
- actor1Ref := h.newRouterTargetActor("actor1-dynamic", serviceKey, actor1Beh)
+ actor1Ref := h.newRouterTargetActor(
+ "actor1-dynamic", serviceKey, actor1Beh,
+ )
// At this point, we have a new actor added, but we'll try to send a
// message to a different actor ID. This should go to the router's DLO.
- futureActor1 := router.Ask(context.Background(), newTestMsg("ping-actor1"))
- ctxAwaitA1, cancelAwaitA1 := context.WithTimeout(context.Background(), time.Second)
+ futureActor1 := router.Ask(t.Context(), newTestMsg("ping-actor1"))
+ ctxAwaitA1, cancelAwaitA1 := context.WithTimeout(
+ t.Context(), time.Second,
+ )
resActor1 := futureActor1.Await(ctxAwaitA1)
cancelAwaitA1()
- require.False(t, resActor1.IsErr(), "ask to actor1 failed: %v", resActor1.Err())
+ require.False(
+ t, resActor1.IsErr(), "ask to actor1 failed: %v",
+ resActor1.Err(),
+ )
resActor1.WhenOk(func(s string) {
require.Equal(t, "actor1:echo: ping-actor1", s)
})
@@ -898,15 +936,17 @@ func TestRouterDynamicActorRegistration(t *testing.T) {
// Now that we've added two actors above, we should round robin between
// them when sending.
ctxAwaitDA1, cancelAwaitDA1 := context.WithTimeout(
- context.Background(), time.Second,
+ t.Context(), time.Second,
)
- router.Ask(context.Background(), newTestMsg("dynamic-ask1")).Await(
+ router.Ask(t.Context(), newTestMsg("dynamic-ask1")).Await(
ctxAwaitDA1,
)
cancelAwaitDA1()
- ctxAwaitDA2, cancelAwaitDA2 := context.WithTimeout(context.Background(), time.Second)
- router.Ask(context.Background(), newTestMsg("dynamic-ask2")).Await(ctxAwaitDA2)
+ ctxAwaitDA2, cancelAwaitDA2 := context.WithTimeout(
+ t.Context(), time.Second,
+ )
+ router.Ask(t.Context(), newTestMsg("dynamic-ask2")).Await(ctxAwaitDA2)
cancelAwaitDA2()
time.Sleep(50 * time.Millisecond)
@@ -922,11 +962,11 @@ func TestRouterDynamicActorRegistration(t *testing.T) {
require.True(t, unregistered)
// All the messages should now go to the second actor.
- for i := 0; i < 2; i++ {
+ for i := range 2 {
msgData := fmt.Sprintf("to-actor2-%d", i)
- future := router.Ask(context.Background(), newTestMsg(msgData))
+ future := router.Ask(t.Context(), newTestMsg(msgData))
ctxAwaitLoop, cancelAwaitLoop := context.WithTimeout(
- context.Background(), time.Second,
+ t.Context(), time.Second,
)
res := future.Await(ctxAwaitLoop)
@@ -953,6 +993,6 @@ func TestRouterDynamicActorRegistration(t *testing.T) {
// If we try to send another message, it should go to the DL.
tellMsg := newTestMsg("dynamic-tell-no-actors")
- router.Tell(context.Background(), tellMsg)
+ router.Tell(t.Context(), tellMsg)
h.assertDLOMessage(tellMsg)
}
### fn/context_guard_test.go
@@ -458,7 +458,7 @@ func TestContextGuardCountGoroutines(t *testing.T) {
count1 := runtime.NumGoroutine()
// Create 1000 contexts of each type.
- for i := 0; i < 1000; i++ {
+ for range 1000 {
_, _ = g.Create(ctx)
_, _ = g.Create(ctx, WithBlockingCG())
_, _ = g.Create(ctx, WithTimeoutCG())
### fn/iter.go
@@ -5,7 +5,6 @@ import "iter"
// Collect drains all of the elements from the passed iterator, returning a
// slice of the contents.
func Collect[T any](seq iter.Seq[T]) []T {
-
var ret []T
for i := range seq {
ret = append(ret, i)
### fn/result_opt.go
@@ -27,6 +27,7 @@ func MapResultOpt[T, U any](ro ResultOpt[T], f func(T) U) ResultOpt[U] {
return ErrOpt[U](ro.Err())
}
opt, _ := ro.Unpack()
+
return ResultOpt[U]{Ok(MapOption(f)(opt))}
}
@@ -42,6 +43,7 @@ func AndThenResultOpt[T, U any](ro ResultOpt[T],
if opt.IsNone() {
return NoneOpt[U]()
}
+
return f(opt.some)
}
@@ -51,6 +53,7 @@ func (ro ResultOpt[T]) IsSome() bool {
return false
}
opt, _ := ro.Unpack()
+
return opt.IsSome()
}
@@ -60,5 +63,6 @@ func (ro ResultOpt[T]) IsNone() bool {
return false
}
opt, _ := ro.Unpack()
+
return opt.IsNone()
}
### fn/result_opt_test.go
@@ -104,6 +104,7 @@ func maybeEvenOpt(x int) ResultOpt[int] {
if x%2 == 0 {
return OkOpt(x / 2)
}
+
return NoneOpt[int]()
}
### fn/slice_test.go
@@ -664,7 +664,7 @@ func BenchmarkMapVsForEachConc(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
- for i := 0; i < b.N; i++ {
+ for range b.N {
Map(s, inc)
}
})
@@ -677,7 +677,7 @@ func BenchmarkMapVsForEachConc(b *testing.B) {
b.ResetTimer()
b.ReportAllocs()
- for i := 0; i < b.N; i++ {
+ for range b.N {
ForEachConc(s, inc)
}
})
### kvdb/postgres_bucket_bench_test.go
@@ -55,7 +55,7 @@ func BenchmarkPostgresNestedBucketLookup(b *testing.B) {
}
}
- for i := 0; i < numBenchKeys; i++ {
+ for i := range numBenchKeys {
key := fmt.Sprintf("key%08d", i)
val := fmt.Sprintf("value%08d", i)
err := bucket.Put([]byte(key), []byte(val))
@@ -75,7 +75,7 @@ func BenchmarkPostgresNestedBucketLookup(b *testing.B) {
name := fmt.Sprintf("depth=%d/reads=%d", depth, reads)
b.Run(name, func(b *testing.B) {
- for i := 0; i < b.N; i++ {
+ for range b.N {
err := View(f.Db, read, func() {})
require.NoError(b, err)
}
@@ -87,7 +87,7 @@ func BenchmarkPostgresNestedBucketLookup(b *testing.B) {
// readNested reads the given number of keys from the bucket at the given
// path, resolving the path again for each of them.
func readNested(tx walletdb.ReadTx, path [][]byte, reads int) error {
- for i := 0; i < reads; i++ {
+ for i := range reads {
bucket := tx.ReadBucket(path[0])
for _, key := range path[1:] {
bucket = bucket.NestedReadBucket(key)
### kvdb/sqlbase/bucket_id_cache_test.go
@@ -132,7 +132,8 @@ func TestBucketLookupCached(t *testing.T) {
t.Cleanup(func() {
require.NoError(t, tx.Rollback())
})
- rwTx := tx.(*readWriteTx)
+ rwTx, ok := tx.(*readWriteTx)
+ require.True(t, ok)
apple := tx.ReadWriteBucket([]byte("apple"))
require.NotNil(t, apple)
@@ -153,9 +154,12 @@ func TestBucketLookupCached(t *testing.T) {
// A bucket that wasn't looked up before is still read from the
// database.
+ appleBucket, ok := apple.(*readWriteBucket)
+ require.True(t, ok)
+
_, err = rwTx.Exec(
"INSERT INTO "+db.table+" (parent_id, key) VALUES($1, $2)",
- *apple.(*readWriteBucket).id, []byte("pear"),
+ *appleBucket.id, []byte("pear"),
)
require.NoError(t, err)
require.NotNil(t, apple.NestedReadWriteBucket([]byte("pear")))
### kvdb/sqlbase/migration_bulk_postgres.go
@@ -90,9 +90,9 @@ func (p *postgresDB) BeginBulk(ctx context.Context) (MigrationBulkKVTx, error) {
// A bulk migration can touch millions of rows in a single transaction.
// PostgreSQL retains predicate locks until a serializable transaction
- // ends, which can make its predicate lock table consume excessive memory.
- // Read committed is sufficient because the migration owns the empty
- // destination database while loading it.
+ // ends, which can make its predicate lock table consume excessive
+ // memory. Read committed is sufficient because the migration owns the
+ // empty destination database while loading it.
tx, err := conn.BeginTx(ctx, &sql.TxOptions{
Isolation: sql.LevelReadCommitted,
})
### kvdb/sqlbase/readwrite_bucket.go
@@ -487,8 +487,9 @@ func (b *readWriteBucket) ForAll(cb func(k, v []byte) error) error {
return err
}
- // SQLite decodes an empty BLOB into nil. Preserve the distinction
- // between empty leaf values and the SQL NULL used for buckets.
+ // SQLite decodes an empty BLOB into nil. Preserve the
+ // distinction between empty leaf values and the SQL NULL used
+ // for buckets.
if isBucket == 0 && value == nil {
value = []byte{}
}
### kvdb/sqlite/db_test.go
@@ -85,7 +85,7 @@ func TestForAllPreservesEmptyValues(t *testing.T) {
// TestForAllReturnsIterationError verifies that a failure encountered after a
// query starts is returned instead of being mistaken for normal exhaustion.
func TestForAllReturnsIterationError(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
db := newTestDB(t, ctx)
err := db.Update(func(tx walletdb.ReadWriteTx) error {
@@ -95,7 +95,8 @@ func TestForAllReturnsIterationError(t *testing.T) {
}
for _, key := range []string{"one", "two", "three"} {
- if err := bucket.Put([]byte(key), []byte("value")); err != nil {
+ err := bucket.Put([]byte(key), []byte("value"))
+ if err != nil {
return err
}
}
@@ -107,9 +108,10 @@ func TestForAllReturnsIterationError(t *testing.T) {
var count int
err = db.View(func(tx walletdb.ReadTx) error {
bucket := tx.ReadBucket([]byte("top"))
- forAllBucket := bucket.(interface {
+ forAllBucket, ok := bucket.(interface {
ForAll(func(k, v []byte) error) error
})
+ require.True(t, ok)
return forAllBucket.ForAll(func(_, _ []byte) error {
count++
### kvdb/sqlite_test.go
@@ -85,8 +85,6 @@ func TestSqlite(t *testing.T) {
}
for _, test := range tests {
- test := test
-
t.Run(test.name, func(t *testing.T) {
t.Parallel()
### queue/back_pressure.go
@@ -142,11 +142,11 @@ func (q *BackpressureQueue[T]) TryEnqueue(item T) bool {
// available.
func (q *BackpressureQueue[T]) Dequeue(ctx context.Context) fn.Result[T] {
select {
-
case item, ok := <-q.ch:
if !ok {
return fn.Err[T](ErrQueueClosed)
}
+
return fn.Ok(item)
case <-ctx.Done():
### queue/back_pressure_test.go
@@ -37,8 +37,8 @@ func (m *queueMachine[T]) Enqueue(t *rapid.T) {
if errors.Is(err, ErrItemDropped) {
actualDrop = true
} else if err != nil {
- // If Enqueue with background context returns an error other than
- // ErrItemDropped, it's unexpected.
+ // If Enqueue with background context returns an error other
+ // than ErrItemDropped, it's unexpected.
m.tb.Fatalf("Enqueue with background context returned "+
"unexpected error: %v", err)
}
@@ -70,8 +70,8 @@ func (m *queueMachine[T]) Dequeue(t *rapid.T) {
result := m.queue.Dequeue(ctx)
require.True(
- m.tb, result.IsErr(), "dequeue "+
- "should return error on empty queue with timeout",
+ m.tb, result.IsErr(), "dequeue should return error "+
+ "on empty queue with timeout",
)
require.ErrorIs(
m.tb, result.Err(),
@@ -198,7 +198,7 @@ func TestBackpressureQueueEnqueueCancellation(t *testing.T) {
// Fill the queue to its capacity. The predicate always returns
// false, so no drops expected.
for i := range capacity {
- err := q.Enqueue(context.Background(), i)
+ err := q.Enqueue(t.Context(), i)
require.NoError(
rt, err, "enqueue failed during setup: %v", err,
)
@@ -208,9 +208,9 @@ func TestBackpressureQueueEnqueueCancellation(t *testing.T) {
"should be full after setup",
)
- // Attempt to enqueue one more item with an immediately cancelled
- // context.
- ctx, cancel := context.WithCancel(context.Background())
+ // Attempt to enqueue one more item with an immediately
+ // cancelled context.
+ ctx, cancel := context.WithCancel(t.Context())
cancel()
err := q.Enqueue(ctx, 999)
@@ -250,7 +250,7 @@ func TestBackpressureQueueDequeueCancellation(t *testing.T) {
// Attempt to dequeue from the empty queue with an immediately
// cancelled context.
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
cancel()
result := q.Dequeue(ctx)
@@ -300,12 +300,11 @@ func TestBackpressureQueueComposedPredicate(t *testing.T) {
for i := range minThresh {
// All items aren't 42, and queue is not full enough for RED to
// drop.
- err := q.Enqueue(context.Background(), i)
+ err := q.Enqueue(t.Context(), i)
require.NoErrorf(t, err, "enqueue S1 setup "+
"item %d (qLen before: %d) should not be dropped. "+
"Predicate was redCheck(%d) || customPred(%d,%d)",
i, len(q.ch)-1, len(q.ch)-1, len(q.ch)-1, i)
-
}
currentLen := len(q.ch)
@@ -314,7 +313,7 @@ func TestBackpressureQueueComposedPredicate(t *testing.T) {
// Enqueue item 42. customValuePredicate is true, so composedPredicate
// is true. Item 42 should be dropped regardless of what redCheck
// decides.
- err = q.Enqueue(context.Background(), 42)
+ err = q.Enqueue(t.Context(), 42)
require.ErrorIs(
t, err, ErrItemDropped,
"item 42 should have been dropped by composed predicate",
@@ -336,7 +335,7 @@ func TestBackpressureQueueComposedPredicate(t *testing.T) {
"for S2 test",
)
- err = q.Enqueue(context.Background(), 100)
+ err = q.Enqueue(t.Context(), 100)
// Expect drop because queue is full (len=capacity), so
// redCheck(capacity) is true. customValuePredicate(capacity, 100)
@@ -406,7 +405,7 @@ func TestBackpressureQueueLenAndReceiveChan(t *testing.T) {
require.Equal(t, 0, q.Len())
for i := range 3 {
- require.NoError(t, q.Enqueue(context.Background(), i))
+ require.NoError(t, q.Enqueue(t.Context(), i))
}
require.Equal(t, 3, q.Len())
@@ -427,7 +426,7 @@ func TestBackpressureQueueClose(t *testing.T) {
q := NewBackpressureQueue(10, neverDrop)
for i := range 3 {
- require.NoError(t, q.Enqueue(context.Background(), i))
+ require.NoError(t, q.Enqueue(t.Context(), i))
}
q.Close()
@@ -464,10 +463,10 @@ func TestBackpressureQueueEnqueueAfterClose(t *testing.T) {
})
q := NewBackpressureQueue(5, neverDrop)
- require.NoError(t, q.Enqueue(context.Background(), 1))
+ require.NoError(t, q.Enqueue(t.Context(), 1))
q.Close()
- err := q.Enqueue(context.Background(), 2)
+ err := q.Enqueue(t.Context(), 2)
require.ErrorIs(t, err, ErrQueueClosed)
}
### queue/circular_buf_test.go
@@ -205,7 +205,8 @@ func TestLatest(t *testing.T) {
func TestCircularBufferConcurrentAccess(t *testing.T) {
// Arrange: Create a small wrapping buffer and two finite workers behind
// one start gate. The writer repeatedly wraps the storage while the
- // reader exercises every public observation method against those writes.
+ // reader exercises every public observation method against those
+ // writes.
const (
bufferSize = 8
iterations = 1000
@@ -221,7 +222,7 @@ func TestCircularBufferConcurrentAccess(t *testing.T) {
defer workers.Done()
<-start
- for i := 0; i < iterations; i++ {
+ for i := range iterations {
buffer.Add(i)
}
}()
@@ -230,7 +231,7 @@ func TestCircularBufferConcurrentAccess(t *testing.T) {
defer workers.Done()
<-start
- for i := 0; i < iterations; i++ {
+ for range iterations {
buffer.List()
buffer.Latest()
buffer.Total()
### sqldb/interfaces.go
@@ -4,7 +4,6 @@ import (
"context"
"database/sql"
"fmt"
- "math"
"math/rand"
prand "math/rand"
"time"
@@ -197,13 +196,26 @@ func randRetryDelay(initialRetryDelay, maxRetryDelay time.Duration,
attempt int) time.Duration {
halfDelay := initialRetryDelay / 2
- randDelay := rand.Int63n(int64(initialRetryDelay)) //nolint:gosec
+
+ // Cap every attempt, including the first, at maxRetryDelay. Check the
+ // operands before adding them so calculating the jittered delay cannot
+ // overflow time.Duration.
+ if halfDelay >= maxRetryDelay {
+ return maxRetryDelay
+ }
+
+ randDelay := time.Duration(
+ rand.Int63n(int64(initialRetryDelay)), //nolint:gosec
+ )
+ if randDelay >= maxRetryDelay-halfDelay {
+ return maxRetryDelay
+ }
// 50% plus 0%-100% gives us the range of 50%-150%.
- initialDelay := halfDelay + time.Duration(randDelay)
+ initialDelay := halfDelay + randDelay
// If this is the first attempt, we just return the initial delay.
- if attempt == 0 {
+ if attempt <= 0 {
return initialDelay
}
@@ -212,15 +224,15 @@ func randRetryDelay(initialRetryDelay, maxRetryDelay time.Duration,
// attempt. If we double something n times, that's the same as
// multiplying the value with 2^n. We limit the power to 32 to avoid
// overflows.
- factor := time.Duration(math.Pow(2, min(float64(attempt), 32)))
- actualDelay := initialDelay * factor
+ factor := int64(1) << min(attempt, 32)
- // Cap the delay at the maximum configured value.
- if actualDelay > maxRetryDelay {
+ // Compare against the divided maximum because multiplying first could
+ // overflow before we get a chance to cap the result.
+ if int64(initialDelay) > int64(maxRetryDelay)/factor {
return maxRetryDelay
}
- return actualDelay
+ return time.Duration(int64(initialDelay) * factor)
}
// MakeTx is a function that creates a new transaction. It returns a Tx and an
### sqldb/interfaces_test.go
@@ -0,0 +1,69 @@
+package sqldb
+
+import (
+ "math"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+// TestRandRetryDelay verifies that retry delays stay within their jitter range
+// and are capped without overflowing for large retry settings.
+func TestRandRetryDelay(t *testing.T) {
+ t.Parallel()
+
+ t.Run("initial jitter", func(t *testing.T) {
+ delay := randRetryDelay(
+ DefaultRetryDelay, DefaultMaxRetryDelay, 0,
+ )
+
+ require.GreaterOrEqual(
+ t, delay, DefaultRetryDelay/2,
+ )
+ require.LessOrEqual(
+ t, delay, DefaultRetryDelay*3/2,
+ )
+ })
+
+ t.Run("uncapped exponential backoff", func(t *testing.T) {
+ delay := randRetryDelay(
+ DefaultRetryDelay, DefaultMaxRetryDelay, 2,
+ )
+
+ require.GreaterOrEqual(t, delay, DefaultRetryDelay*2)
+ require.Less(t, delay, DefaultRetryDelay*6)
+ })
+
+ t.Run("exponential backoff reaches maximum", func(t *testing.T) {
+ delay := randRetryDelay(
+ DefaultRetryDelay, DefaultMaxRetryDelay, 6,
+ )
+
+ require.Equal(t, DefaultMaxRetryDelay, delay)
+ })
+
+ t.Run("large initial delay is capped", func(t *testing.T) {
+ delay := randRetryDelay(
+ DefaultMaxRetryDelay*4, DefaultMaxRetryDelay, 0,
+ )
+
+ require.Equal(t, DefaultMaxRetryDelay, delay)
+ })
+
+ t.Run("large retry count does not overflow", func(t *testing.T) {
+ delay := randRetryDelay(
+ DefaultMaxRetryDelay, DefaultMaxRetryDelay, 32,
+ )
+
+ require.Equal(t, DefaultMaxRetryDelay, delay)
+ })
+
+ t.Run("jitter addition does not overflow", func(t *testing.T) {
+ delay := randRetryDelay(
+ time.Duration(math.MaxInt64), DefaultMaxRetryDelay, 0,
+ )
+
+ require.Equal(t, DefaultMaxRetryDelay, delay)
+ })
+}
### sqldb/migrations.go
@@ -408,7 +408,7 @@ func ApplyMigrations(ctx context.Context, db *BaseDB,
migrator MigrationExecutor, migrations []MigrationConfig) error {
// Ensure that the migrations are sorted by version.
- for i := 0; i < len(migrations); i++ {
+ for i := range migrations {
if migrations[i].Version != i+1 {
return fmt.Errorf("migration version %d is out of "+
"order. Expected %d", migrations[i].Version,
@@ -420,7 +420,7 @@ func ApplyMigrations(ctx context.Context, db *BaseDB,
return db.WithTx(tx)
})
- currentVersion := 0
+ var currentVersion int
version, err := db.GetDatabaseVersion(ctx)
if !errors.Is(err, sql.ErrNoRows) {
if err != nil {
### sqldb/migrations_test.go
@@ -2,6 +2,7 @@ package sqldb
import (
"database/sql"
+ "errors"
"fmt"
"path/filepath"
"strings"
@@ -114,10 +115,12 @@ func testInvoiceExpiryMigration(t *testing.T, makeDB makeMigrationTestDB) {
// AMP invoices.
err = migrate(TargetVersion(4))
- invoices, err := db.FilterInvoicesByAddIndex(ctxb, sqlc.FilterInvoicesByAddIndexParams{
- AddIndexGet: 1,
- NumLimit: 100,
- })
+ invoices, err := db.FilterInvoicesByAddIndex(
+ ctxb, sqlc.FilterInvoicesByAddIndexParams{
+ AddIndexGet: 1,
+ NumLimit: 100,
+ },
+ )
const (
// 1 day in seconds.
@@ -289,7 +292,7 @@ func TestCustomMigration(t *testing.T) {
require.NoError(t, err)
version, _, err := sqlMigrate.Version()
- if err != migrate.ErrNilVersion {
+ if !errors.Is(err, migrate.ErrNilVersion) {
require.NoError(t, err)
}
@@ -311,7 +314,7 @@ func TestCustomMigration(t *testing.T) {
// Run the migration 3 times to test that the migrations
// are idempotent.
- for i := 0; i < 3; i++ {
+ for range 3 {
db, err = NewSqliteStore(&SqliteConfig{
SkipMigrations: false,
}, dbFileName)
@@ -400,7 +403,7 @@ func TestCustomMigration(t *testing.T) {
// Run the migration 3 times to test that the migrations
// are idempotent.
- for i := 0; i < 3; i++ {
+ for range 3 {
cfg.SkipMigrations = false
db, err = NewPostgresStore(cfg)
require.NoError(t, err)
@@ -517,7 +520,7 @@ func TestMigrationSucceedsAfterDirtyStateMigrationFailure19RC1(t *testing.T) {
require.False(t, dirty)
// Set the schema version to the failing version and
- // make make the version dirty which essentially tells
+ // make the version dirty which essentially tells
// golang-migrate that the migration failed.
require.NoError(
t, db.SetSchemaVersion(failingSchemaVersion, true),
@@ -588,7 +591,7 @@ func TestMigrationSucceedsAfterDirtyStateMigrationFailure19RC1(t *testing.T) {
require.False(t, dirty)
// Set the schema version to the failing version and
- // make make the version dirty which essentially tells
+ // make the version dirty which essentially tells
// golang-migrate that the migration failed.
require.NoError(
t, db.SetSchemaVersion(failingSchemaVersion, true),
@@ -650,7 +653,7 @@ func TestMigrationConfigConsistency(t *testing.T) {
expectedPrefix := fmt.Sprintf("%06d_", version)
require.True(t,
len(f.Name()) > len(expectedPrefix) &&
- f.Name()[:len(expectedPrefix)] == expectedPrefix,
+ strings.HasPrefix(f.Name(), expectedPrefix),
"schema migration file %q should use 6-digit "+
"zero-padded prefix %q", f.Name(),
expectedPrefix)
@@ -699,13 +702,15 @@ func TestMigrationConfigConsistency(t *testing.T) {
" file exists in the embedded FS",
m.Name, m.Version, m.SchemaVersion,
m.SchemaVersion)
- require.Equal(t, strings.TrimSuffix(fileName, ".up.sql"),
+ require.Equal(t,
+ strings.TrimSuffix(fileName, ".up.sql"),
m.Name, "migration %q (version %d) has "+
- "SchemaVersion=%d but its name does not "+
- "match embedded file %q",
+ "SchemaVersion=%d but its name does "+
+ "not match embedded file %q",
m.Name, m.Version, m.SchemaVersion, fileName)
- if existing, ok := seenSchemaVersions[m.SchemaVersion]; ok {
+ existing, ok := seenSchemaVersions[m.SchemaVersion]
+ if ok {
t.Fatalf("duplicate schema version %d: "+
"%q and %q", m.SchemaVersion,
existing, m.Name)
@@ -721,5 +726,4 @@ func TestMigrationConfigConsistency(t *testing.T) {
"(migrations must be sequential)",
m.Name, m.Version, i+1)
}
-
}
### sqldb/paginate.go
@@ -252,7 +252,7 @@ type CollectFunc[T any, ID any] func(T) (ID, error)
// - extractPageCursor: extracts cursor from paginated item for next page
// - collectFunc: extracts identifier from paginated item
// - batchDataFunc: batch loads shared data from collected IDs for one page
-// - processItem: processes each item with the shared batch data
+// - processItem: processes each item with the shared batch data.
func ExecuteCollectAndBatchWithSharedDataQuery[C any, T any, I any, D any](
ctx context.Context, cfg *QueryConfig, initialCursor C,
pageQueryFunc PagedQueryFunc[C, T],
### sqldb/postgres_fixture.go
@@ -152,7 +152,7 @@ func NewTestPostgresDB(t testing.TB, fixture *TestPgFixture) *PostgresStore {
require.NoError(t, err)
require.NoError(t, store.ApplyAllMigrations(
- context.Background(), GetMigrations()),
+ t.Context(), GetMigrations()),
)
t.Cleanup(func() {
### sqldb/sqlc/db_custom.go
@@ -27,7 +27,7 @@ func makeQueryParams(numTotalArgs, numListArgs int) string {
b.Grow(numListArgs * 6)
diff := numTotalArgs - numListArgs
- for i := 0; i < numListArgs; i++ {
+ for i := range numListArgs {
if i > 0 {
// We don't need to check the error here because the
// WriteString method of strings.Builder always returns
@@ -174,7 +174,8 @@ type PaymentAndIntent interface {
// GetPayment returns the Payment associated with this interface.
GetPayment() Payment
- // GetPaymentIntent returns the PaymentIntent associated with this payment.
+ // GetPaymentIntent returns the PaymentIntent associated with this
+ // payment.
GetPaymentIntent() PaymentIntent
}
@@ -194,6 +195,7 @@ func (r FilterPaymentsRow) GetPaymentIntent() PaymentIntent {
if !r.IntentType.Valid {
return PaymentIntent{}
}
+
return PaymentIntent{
IntentType: r.IntentType.Int16,
IntentPayload: r.IntentPayload,
@@ -216,6 +218,7 @@ func (r FetchPaymentRow) GetPaymentIntent() PaymentIntent {
if !r.IntentType.Valid {
return PaymentIntent{}
}
+
return PaymentIntent{
IntentType: r.IntentType.Int16,
IntentPayload: r.IntentPayload,
@@ -236,6 +239,7 @@ func (r FetchPaymentsByIDsRow) GetPaymentIntent() PaymentIntent {
if !r.IntentType.Valid {
return PaymentIntent{}
}
+
return PaymentIntent{
IntentType: r.IntentType.Int16,
IntentPayload: r.IntentPayload,
### sqldb/sqlc/db_custom_test.go
@@ -28,7 +28,7 @@ func BenchmarkMakeQueryParams(b *testing.B) {
c.listArgs,
)
b.Run(name, func(b *testing.B) {
- for i := 0; i < b.N; i++ {
+ for range b.N {
_ = makeQueryParams(
c.totalArgs, c.listArgs,
)
### sqldb/sqlite.go
@@ -240,7 +240,7 @@ func NewTestSqliteDB(t testing.TB) *SqliteStore {
require.NoError(t, err)
require.NoError(t, sqlDB.ApplyAllMigrations(
- context.Background(), GetMigrations()),
+ t.Context(), GetMigrations()),
)
t.Cleanup(func() {
### sqldb/sqlite_bench_test.go
@@ -51,10 +51,10 @@ func BenchmarkSqliteMaxConns(b *testing.B) {
require.NoError(b, err)
require.NoError(b, setupStore.ApplyAllMigrations(
- context.Background(), GetMigrations(),
+ b.Context(), GetMigrations(),
))
- ctx := context.Background()
+ ctx := b.Context()
// Insert test invoices. We use a predictable hash per invoice so we
// can look them up deterministically during the benchmark.
@@ -129,10 +129,10 @@ func BenchmarkSqliteMaxConnsConcurrentReads(b *testing.B) {
require.NoError(b, err)
require.NoError(b, setupStore.ApplyAllMigrations(
- context.Background(), GetMigrations(),
+ b.Context(), GetMigrations(),
))
- ctx := context.Background()
+ ctx := b.Context()
hashes := make([][]byte, numInvoices)
for i := range numInvoices {
### sqldb/sqlite_test.go
@@ -13,6 +13,11 @@ import (
//
// TODO(elle): once we've updated to using sqldbv2, we can remove this since
// then we will have access to the DatabaseType on the BaseDB struct at runtime.
+//
+// NOTE: The only users of this constant are built with the test_db_sqlite or
+// test_db_postgres build tags, so it appears unused in the default build.
+//
+//nolint:unused
const isSQLite = true
// NewTestDB is a helper function that creates an SQLite database for testing.
### sqldb/v2/config_test.go
@@ -28,8 +28,6 @@ func TestSqliteConfigMaxConns(t *testing.T) {
}
for _, testCase := range testCases {
- testCase := testCase
-
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()
@@ -71,8 +69,6 @@ func TestSqliteConfigMaxIdleConns(t *testing.T) {
}
for _, testCase := range testCases {
- testCase := testCase
-
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()
### sqldb/v2/interfaces.go
@@ -4,7 +4,6 @@ import (
"context"
"database/sql"
"fmt"
- "math"
"math/rand"
"time"
)
@@ -219,13 +218,26 @@ func randRetryDelay(initialRetryDelay, maxRetryDelay time.Duration,
attempt int) time.Duration {
halfDelay := initialRetryDelay / 2
- randDelay := rand.Int63n(int64(initialRetryDelay)) //nolint:gosec
+
+ // Cap every attempt, including the first, at maxRetryDelay. Check the
+ // operands before adding them so calculating the jittered delay cannot
+ // overflow time.Duration.
+ if halfDelay >= maxRetryDelay {
+ return maxRetryDelay
+ }
+
+ randDelay := time.Duration(
+ rand.Int63n(int64(initialRetryDelay)), //nolint:gosec
+ )
+ if randDelay >= maxRetryDelay-halfDelay {
+ return maxRetryDelay
+ }
// 50% plus 0%-100% gives us the range of 50%-150%.
- initialDelay := halfDelay + time.Duration(randDelay)
+ initialDelay := halfDelay + randDelay
// If this is the first attempt, we just return the initial delay.
- if attempt == 0 {
+ if attempt <= 0 {
return initialDelay
}
@@ -234,15 +246,15 @@ func randRetryDelay(initialRetryDelay, maxRetryDelay time.Duration,
// attempt. If we double something n times, that's the same as
// multiplying the value with 2^n. We limit the power to 32 to avoid
// overflows.
- factor := time.Duration(math.Pow(2, min(float64(attempt), 32)))
- actualDelay := initialDelay * factor
+ factor := int64(1) << min(attempt, 32)
- // Cap the delay at the maximum configured value.
- if actualDelay > maxRetryDelay {
+ // Compare against the divided maximum because multiplying first could
+ // overflow before we get a chance to cap the result.
+ if int64(initialDelay) > int64(maxRetryDelay)/factor {
return maxRetryDelay
}
- return actualDelay
+ return time.Duration(int64(initialDelay) * factor)
}
// MakeTx is a function that creates a new transaction. It returns a Tx and an
@@ -271,17 +283,17 @@ type OnBackoff func(retry int, delay time.Duration)
func executeTxAttempt(tx Tx, txBody TxBody, rollbackTx RollbackTx,
waitBeforeRetry func(int) bool, attempt int) (bool, error) {
- // Rollback is safe to call even if the tx is already closed, so if the tx
- // commits successfully, this is a no-op.
+ // Rollback is safe to call even if the tx is already closed, so if the
+ // tx commits successfully, this is a no-op.
defer func() {
_ = tx.Rollback()
}()
if bodyErr := txBody(tx); bodyErr != nil {
log.Tracef("Error in txBody: %v", bodyErr)
- // Roll back the transaction, then attempt a random backoff and try
- // again if the error was a serialization error.
+ // Roll back the transaction, then attempt a random backoff and
+ // try again if the error was a serialization error.
if err := rollbackTx(tx); err != nil {
return false, MapSQLError(err)
}
@@ -298,8 +310,8 @@ func executeTxAttempt(tx Tx, txBody TxBody, rollbackTx RollbackTx,
if commitErr := tx.Commit(); commitErr != nil {
log.Tracef("Failed to commit tx: %v", commitErr)
- // Roll back the transaction, then attempt a random backoff and try
- // again if the error was a serialization error.
+ // Roll back the transaction, then attempt a random backoff and
+ // try again if the error was a serialization error.
if err := rollbackTx(tx); err != nil {
return false, MapSQLError(err)
}
@@ -344,7 +356,7 @@ func ExecuteSQLTransactionWithRetry(ctx context.Context, makeTx MakeTx,
}
}
- for i := 0; i < opts.numRetries; i++ {
+ for i := range opts.numRetries {
tx, err := makeTx()
if err != nil {
dbErr := MapSQLError(err)
@@ -367,7 +379,8 @@ func ExecuteSQLTransactionWithRetry(ctx context.Context, makeTx MakeTx,
tx, txBody, rollbackTx, waitBeforeRetry, i,
)
if retry {
- // Transient serialization error, discard this attempt and retry.
+ // Transient serialization error, discard this attempt
+ // and retry.
continue
}
if err != nil {
@@ -402,6 +415,7 @@ func (t *TransactionExecutor[Q]) ExecTx(ctx context.Context,
}
reset()
+
return txBody(t.createQuery(sqlTx))
}
### sqldb/v2/interfaces_test.go
@@ -3,7 +3,9 @@ package sqldb
import (
"context"
"database/sql"
+ "math"
"testing"
+ "time"
"github.com/stretchr/testify/require"
)
@@ -46,3 +48,65 @@ func TestTransactionExecutorBackend(t *testing.T) {
require.Equal(t, BackendTypePostgres, executor.Backend())
}
+
+// TestRandRetryDelay verifies that retry delays stay within their jitter range
+// and are capped without overflowing for large retry settings.
+func TestRandRetryDelay(t *testing.T) {
+ t.Parallel()
+
+ t.Run("initial jitter", func(t *testing.T) {
+ delay := randRetryDelay(
+ DefaultInitialRetryDelay, DefaultMaxRetryDelay, 0,
+ )
+
+ require.GreaterOrEqual(
+ t, delay, DefaultInitialRetryDelay/2,
+ )
+ require.LessOrEqual(
+ t, delay, DefaultInitialRetryDelay*3/2,
+ )
+ })
+
+ t.Run("uncapped exponential backoff", func(t *testing.T) {
+ delay := randRetryDelay(
+ DefaultInitialRetryDelay, DefaultMaxRetryDelay, 2,
+ )
+
+ require.GreaterOrEqual(
+ t, delay, DefaultInitialRetryDelay*2,
+ )
+ require.Less(t, delay, DefaultInitialRetryDelay*6)
+ })
+
+ t.Run("exponential backoff reaches maximum", func(t *testing.T) {
+ delay := randRetryDelay(
+ DefaultInitialRetryDelay, DefaultMaxRetryDelay, 8,
+ )
+
+ require.Equal(t, DefaultMaxRetryDelay, delay)
+ })
+
+ t.Run("large initial delay is capped", func(t *testing.T) {
+ delay := randRetryDelay(
+ DefaultMaxRetryDelay*4, DefaultMaxRetryDelay, 0,
+ )
+
+ require.Equal(t, DefaultMaxRetryDelay, delay)
+ })
+
+ t.Run("large retry count does not overflow", func(t *testing.T) {
+ delay := randRetryDelay(
+ DefaultMaxRetryDelay, DefaultMaxRetryDelay, 32,
+ )
+
+ require.Equal(t, DefaultMaxRetryDelay, delay)
+ })
+
+ t.Run("jitter addition does not overflow", func(t *testing.T) {
+ delay := randRetryDelay(
+ time.Duration(math.MaxInt64), DefaultMaxRetryDelay, 0,
+ )
+
+ require.Equal(t, DefaultMaxRetryDelay, delay)
+ })
+}
### sqldb/v2/migrations.go
@@ -90,8 +90,8 @@ type MigrationSet struct {
func (m MigrationSet) validate() error {
if len(m.Descriptors) == 0 {
if m.LatestMigrationVersion != 0 {
- return fmt.Errorf("latest migration version %d requires "+
- "at least one descriptor",
+ return fmt.Errorf("latest migration version %d "+
+ "requires at least one descriptor",
m.LatestMigrationVersion)
}
@@ -101,9 +101,9 @@ func (m MigrationSet) validate() error {
for i, descriptor := range m.Descriptors {
expectedVersion := i + 1
if descriptor.Version != expectedVersion {
- return fmt.Errorf("migration descriptor version %d is out "+
- "of order, expected %d", descriptor.Version,
- expectedVersion)
+ return fmt.Errorf("migration descriptor version %d "+
+ "is out of order, expected %d",
+ descriptor.Version, expectedVersion)
}
}
@@ -161,14 +161,6 @@ type migrateOptions struct {
programmaticMigrs map[uint]migrate.ProgrammaticMigrEntry
}
-// defaultMigrateOptions returns a new migrateOptions instance with default
-// settings.
-func defaultMigrateOptions() *migrateOptions {
- return &migrateOptions{
- programmaticMigrs: make(map[uint]migrate.ProgrammaticMigrEntry),
- }
-}
-
// MigrateOpt is a functional option that can be passed to migrate related
// methods to modify behavior.
type MigrateOpt func(*migrateOptions)
@@ -222,7 +214,7 @@ func (m *migrationLogger) Printf(format string, v ...interface{}) {
}
}
-// Verbose should return true when verbose logging output is wanted
+// Verbose should return true when verbose logging output is wanted.
func (m *migrationLogger) Verbose() bool {
return m.log.Level() <= btclog.LevelDebug
}
### sqldb/v2/migrations_test.go
@@ -88,8 +88,6 @@ func TestMigrationSetValidate(t *testing.T) {
}
for _, testCase := range testCases {
- testCase := testCase
-
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()
### sqldb/v2/paginate.go
@@ -252,7 +252,7 @@ type CollectFunc[T any, ID any] func(T) (ID, error)
// - extractPageCursor: extracts cursor from paginated item for next page
// - collectFunc: extracts identifier from paginated item
// - batchDataFunc: batch loads shared data from collected IDs for one page
-// - processItem: processes each item with the shared batch data
+// - processItem: processes each item with the shared batch data.
func ExecuteCollectAndBatchWithSharedDataQuery[C any, T any, I any, D any](
ctx context.Context, cfg *QueryConfig, initialCursor C,
pageQueryFunc PagedQueryFunc[C, T],
### sqldb/v2/postgres.go
@@ -292,6 +292,7 @@ func (s *PostgresStore) executeMigrations(target MigrationTarget,
// Populate the database with our set of schemas based on our embedded
// in-memory file system.
postgresFS := newReplacerFS(set.SQLFiles, postgresSchemaReplacements)
+
return applyMigrations(
postgresFS, driver, set.SQLFileDirectory, dbName, target, opts,
)
### sqldb/v2/postgres_fixture.go
@@ -3,7 +3,6 @@
package sqldb
import (
- "context"
"crypto/rand"
"database/sql"
"encoding/hex"
@@ -186,7 +185,7 @@ func NewTestPostgresDB(t testing.TB, fixture *TestPgFixture,
t.Logf("Creating new Postgres DB '%s' for testing", dbName)
_, err := fixture.db.ExecContext(
- context.Background(), "CREATE DATABASE "+dbName,
+ t.Context(), "CREATE DATABASE "+dbName,
)
require.NoError(t, err)
@@ -215,7 +214,7 @@ func NewTestPostgresDBWithVersion(t testing.TB, fixture *TestPgFixture,
dbName := RandomDBName(t)
_, err := fixture.db.ExecContext(
- context.Background(), "CREATE DATABASE "+dbName,
+ t.Context(), "CREATE DATABASE "+dbName,
)
require.NoError(t, err)
### sqldb/v2/postgres_fixture_test.go
@@ -41,8 +41,6 @@ func TestSanitizeDockerName(t *testing.T) {
}
for _, testCase := range testCases {
- testCase := testCase
-
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()
### sqldb/v2/postgres_internal_test.go
@@ -18,28 +18,32 @@ func TestEnsureRequiredSSLMode(t *testing.T) {
expected string
}{
{
- name: "ssl disabled",
- dsn: "postgres://user:pass@localhost/db?sslmode=disable",
+ name: "ssl disabled",
+ dsn: "postgres://user:pass@localhost/db?" +
+ "sslmode=disable",
requireSSL: true,
- expected: "postgres://user:pass@localhost/db?sslmode=require",
+ expected: "postgres://user:pass@localhost/db?" +
+ "sslmode=require",
},
{
- name: "ssl not requested",
- dsn: "postgres://user:pass@localhost/db?sslmode=disable",
+ name: "ssl not requested",
+ dsn: "postgres://user:pass@localhost/db?" +
+ "sslmode=disable",
requireSSL: false,
- expected: "postgres://user:pass@localhost/db?sslmode=disable",
+ expected: "postgres://user:pass@localhost/db?" +
+ "sslmode=disable",
},
{
- name: "strict mode preserved",
- dsn: "postgres://user:pass@localhost/db?sslmode=verify-full",
+ name: "strict mode preserved",
+ dsn: "postgres://user:pass@localhost/db?" +
+ "sslmode=verify-full",
requireSSL: true,
- expected: "postgres://user:pass@localhost/db?sslmode=verify-full",
+ expected: "postgres://user:pass@localhost/db?" +
+ "sslmode=verify-full",
},
}
for _, testCase := range testCases {
- testCase := testCase
-
t.Run(testCase.name, func(t *testing.T) {
t.Parallel()
### sqldb/v2/sqlite.go
@@ -219,6 +219,7 @@ func (s *SqliteStore) backupAndMigrate(mig *migrate.Migrate,
"migration attempt and backup creation "+
"(current_db_version=%v, max_migration_version=%v)",
currentDbVersion, maxMigrationVersion)
+
return nil
}
@@ -238,6 +239,7 @@ func (s *SqliteStore) backupAndMigrate(mig *migrate.Migrate,
}
log.Infof("Applying migrations to database")
+
return mig.Up()
}
@@ -284,6 +286,7 @@ func (s *SqliteStore) executeMigrations(target MigrationTarget,
// Populate the database with our set of schemas based on our embedded
// in-memory file system.
sqliteFS := newReplacerFS(set.SQLFiles, sqliteSchemaReplacements)
+
return applyMigrations(
sqliteFS, driver, set.SQLFileDirectory, "sqlite", target, opts,
)
### sqldb/v2/sqlutils.go
@@ -48,6 +48,7 @@ func SQLPtrInt32[T constraints.Integer](num *T) sql.NullInt32 {
if num == nil {
return sql.NullInt32{}
}
+
return sql.NullInt32{
Int32: int32(*num),
Valid: true,
@@ -83,6 +84,7 @@ func SQLPtrInt64[T constraints.Integer](num *T) sql.NullInt64 {
if num == nil {
return sql.NullInt64{}
}
+
return sql.NullInt64{
Int64: int64(*num),
Valid: true,
@@ -148,6 +150,7 @@ func ExtractSqlInt64Ptr[T constraints.Integer](num sql.NullInt64) *T {
return nil
}
val := T(num.Int64)
+
return &val
}
@@ -164,6 +167,7 @@ func ExtractSqlInt32Ptr[T constraints.Integer](num sql.NullInt32) *T {
return nil
}
val := T(num.Int32)
+
return &val
}
@@ -174,6 +178,7 @@ func ExtractOptSqlInt32[T constraints.Integer](num sql.NullInt32) fn.Option[T] {
}
result := T(num.Int32)
+
return fn.Some(result)
}
### tor/cmd_onion.go
@@ -218,6 +218,7 @@ func (c *Controller) prepareKeyparam(cfg AddOnionConfig) (string, error) {
if !bytes.HasPrefix(
privateKey, []byte(V3KeyParam+":"),
) {
+
return "", ErrNonV3OnionKey
}
keyParam = string(privateKey)
### tor/cmd_onion_test.go
@@ -194,8 +194,9 @@ func TestPrepareAddOnion(t *testing.T) {
name: "empty target IP and ports",
targetIPAddress: "",
cfg: AddOnionConfig{VirtualPort: 9735},
- expectedCmd: "ADD_ONION NEW:ED25519-V3 Port=9735,9735 ",
- expectedErr: nil,
+ expectedCmd: "ADD_ONION NEW:ED25519-V3 " +
+ "Port=9735,9735 ",
+ expectedErr: nil,
},
{
name: "specified target IP and empty ports",Why this scored 19/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.