Workspace update subscriptions and VPN tunnels could close a channel
while another goroutine was still sending on it, panicking with `send on
closed channel`. VPN senders could also block forever once nothing read
the channel.
- `coderd`: `sub.Close` no longer closes the updates channel, so a
pubsub callback still running cannot send on a closed channel.
- `vpn`: after Stop, the tunnel no longer closes the shared send
channel. The writer exits after writing the Stop response, so Stop is
the final frame, and its exit is what ends the senders below.
- `vpn`: a speaker send context ends when the speaker is canceled or the
writer exits, for example on a write error. RPCs, RPC replies, updates
and logs wait on it, so they return instead of blocking on a channel
nothing reads. Before, an update holding the updater mutex could block a
Stop the tunnel had already read. The updater context derives from it,
so the updater also stops after Stop when Start never succeeded.
- `vpn`: RPC response channels are buffered, so delivering a response no
longer deadlocks against a caller canceled at the same moment. That
deadlock exists on main for a canceled caller context, and the send
context adds a cancellation at shutdown. A response received before EOF
or writer exit is returned instead of an error.
<details>
<summary>Decisions and regression evidence</summary>
- Nothing observes the subscription channel closing: its only reader,
`WorkspaceUpdates` in `tailnet/service.go`, also stops on its stream
context and calls `Close` itself.
- The tunnel does not cancel its speaker after Stop. Senders return once
the writer has finished the Stop response rather than when it is handed
over, and a request the manager sends after Stop stays parked until
`Tunnel.Close`, as on main.
- `updater.stop` is unchanged: it cancels after closing the conn, so
logs the conn emits while closing reach the manager (the tunnel is the
only log sink with `UseAsLogger` on macOS).
`TestTunnel_StopForwardsCloseLogs` guards that ordering.
- RPCs wait on the send context directly instead of relying on
`recvLoopDone`. The receive loop cannot exit while it is handing a
request to a busy `requestLoop`, and closing a blocking file descriptor
may not interrupt its read. `recvFromSerdes` still delivers requests
after the writer exits, so a Stop it has already read is not dropped.
When only the writer has exited, RPCs return `io.ErrUnexpectedEOF`, as
for EOF. Every RPC return removes its response channel, so RPCs that
fail after the writer exits do not accumulate entries.
- Against main's production code:
- `TestWorkspaceUpdatesClose/{QueryInFlight,CallbackAfterClose}` and
`TestTunnel_StopConcurrentSenders` panic with `send on closed channel`.
- `TestSpeaker_ResponseDuringCancellation` deadlocks.
- `TestSerdes_StopClosesAfterResponse` receives a frame after Stop.
- `TestTunnel_StopAfterWriterExits` and
`TestSpeaker_RPCAfterWriterExits` stay blocked after the writer exits.
- `TestSpeaker_ResponseBeforeEOF`,
`TestSpeaker_ResponseBeforeWriterExits` and
`TestTunnel_StopForwardsCloseLogs` pass on main. They guard ordering the
fix depends on: each fails when that ordering is changed or the matching
part of the fix is removed.
- The regression tests pass 50 runs with `-race`. The `vpn` and
`tailnet` race suites pass.
</details>
> This PR was created with the help of Coder Agents for @mafredri and
will be reviewed by a human.
444 lines
12 KiB
Go
444 lines
12 KiB
Go
package coderd_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"slices"
|
|
"strings"
|
|
"testing"
|
|
"testing/synctest"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/coder/coder/v2/coderd"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/dbauthz"
|
|
"github.com/coder/coder/v2/coderd/database/pubsub"
|
|
"github.com/coder/coder/v2/coderd/rbac"
|
|
"github.com/coder/coder/v2/coderd/rbac/policy"
|
|
"github.com/coder/coder/v2/coderd/wspubsub"
|
|
"github.com/coder/coder/v2/tailnet"
|
|
"github.com/coder/coder/v2/tailnet/proto"
|
|
"github.com/coder/coder/v2/testutil"
|
|
)
|
|
|
|
func TestWorkspaceUpdates(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ws1ID := uuid.UUID{0x01}
|
|
ws1IDSlice := tailnet.UUIDToByteSlice(ws1ID)
|
|
agent1ID := uuid.UUID{0x02}
|
|
agent1IDSlice := tailnet.UUIDToByteSlice(agent1ID)
|
|
ws2ID := uuid.UUID{0x03}
|
|
ws2IDSlice := tailnet.UUIDToByteSlice(ws2ID)
|
|
ws3ID := uuid.UUID{0x04}
|
|
ws3IDSlice := tailnet.UUIDToByteSlice(ws3ID)
|
|
agent2ID := uuid.UUID{0x05}
|
|
agent2IDSlice := tailnet.UUIDToByteSlice(agent2ID)
|
|
ws4ID := uuid.UUID{0x06}
|
|
ws4IDSlice := tailnet.UUIDToByteSlice(ws4ID)
|
|
agent3ID := uuid.UUID{0x07}
|
|
agent3IDSlice := tailnet.UUIDToByteSlice(agent3ID)
|
|
|
|
ownerID := uuid.UUID{0x08}
|
|
memberRole, err := rbac.RoleByName(rbac.RoleMember())
|
|
require.NoError(t, err)
|
|
ownerSubject := rbac.Subject{
|
|
FriendlyName: "member",
|
|
ID: ownerID.String(),
|
|
Roles: rbac.Roles{memberRole},
|
|
Scope: rbac.ScopeAll,
|
|
}
|
|
|
|
t.Run("Basic", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitShort)
|
|
|
|
db := &mockWorkspaceStore{
|
|
orderedRows: []database.GetWorkspacesAndAgentsByOwnerIDRow{
|
|
// Gains agent2
|
|
{
|
|
ID: ws1ID,
|
|
Name: "ws1",
|
|
JobStatus: database.ProvisionerJobStatusRunning,
|
|
Transition: database.WorkspaceTransitionStart,
|
|
Agents: []database.AgentIDNamePair{
|
|
{
|
|
ID: agent1ID,
|
|
Name: "agent1",
|
|
},
|
|
},
|
|
},
|
|
// Changes status
|
|
{
|
|
ID: ws2ID,
|
|
Name: "ws2",
|
|
JobStatus: database.ProvisionerJobStatusRunning,
|
|
Transition: database.WorkspaceTransitionStart,
|
|
},
|
|
// Is deleted
|
|
{
|
|
ID: ws3ID,
|
|
Name: "ws3",
|
|
JobStatus: database.ProvisionerJobStatusSucceeded,
|
|
Transition: database.WorkspaceTransitionStop,
|
|
Agents: []database.AgentIDNamePair{
|
|
{
|
|
ID: agent3ID,
|
|
Name: "agent3",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
}
|
|
|
|
ps := &mockPubsub{
|
|
cbs: map[string]pubsub.ListenerWithErr{},
|
|
}
|
|
|
|
updateProvider := coderd.NewUpdatesProvider(testutil.Logger(t), ps, db, &mockAuthorizer{})
|
|
t.Cleanup(func() {
|
|
_ = updateProvider.Close()
|
|
})
|
|
|
|
sub, err := updateProvider.Subscribe(dbauthz.As(ctx, ownerSubject), ownerID)
|
|
require.NoError(t, err)
|
|
t.Cleanup(func() {
|
|
_ = sub.Close()
|
|
})
|
|
|
|
update := testutil.TryReceive(ctx, t, sub.Updates())
|
|
slices.SortFunc(update.UpsertedWorkspaces, func(a, b *proto.Workspace) int {
|
|
return strings.Compare(a.Name, b.Name)
|
|
})
|
|
slices.SortFunc(update.UpsertedAgents, func(a, b *proto.Agent) int {
|
|
return strings.Compare(a.Name, b.Name)
|
|
})
|
|
require.Equal(t, &proto.WorkspaceUpdate{
|
|
UpsertedWorkspaces: []*proto.Workspace{
|
|
{
|
|
Id: ws1IDSlice,
|
|
Name: "ws1",
|
|
Status: proto.Workspace_STARTING,
|
|
},
|
|
{
|
|
Id: ws2IDSlice,
|
|
Name: "ws2",
|
|
Status: proto.Workspace_STARTING,
|
|
},
|
|
{
|
|
Id: ws3IDSlice,
|
|
Name: "ws3",
|
|
Status: proto.Workspace_STOPPED,
|
|
},
|
|
},
|
|
UpsertedAgents: []*proto.Agent{
|
|
{
|
|
Id: agent1IDSlice,
|
|
Name: "agent1",
|
|
WorkspaceId: ws1IDSlice,
|
|
},
|
|
{
|
|
Id: agent3IDSlice,
|
|
Name: "agent3",
|
|
WorkspaceId: ws3IDSlice,
|
|
},
|
|
},
|
|
DeletedWorkspaces: []*proto.Workspace{},
|
|
DeletedAgents: []*proto.Agent{},
|
|
}, update)
|
|
|
|
// Update the database
|
|
db.orderedRows = []database.GetWorkspacesAndAgentsByOwnerIDRow{
|
|
{
|
|
ID: ws1ID,
|
|
Name: "ws1",
|
|
JobStatus: database.ProvisionerJobStatusRunning,
|
|
Transition: database.WorkspaceTransitionStart,
|
|
Agents: []database.AgentIDNamePair{
|
|
{
|
|
ID: agent1ID,
|
|
Name: "agent1",
|
|
},
|
|
{
|
|
ID: agent2ID,
|
|
Name: "agent2",
|
|
},
|
|
},
|
|
},
|
|
{
|
|
ID: ws2ID,
|
|
Name: "ws2",
|
|
JobStatus: database.ProvisionerJobStatusRunning,
|
|
Transition: database.WorkspaceTransitionStop,
|
|
},
|
|
{
|
|
ID: ws4ID,
|
|
Name: "ws4",
|
|
JobStatus: database.ProvisionerJobStatusRunning,
|
|
Transition: database.WorkspaceTransitionStart,
|
|
},
|
|
}
|
|
publishWorkspaceEvent(t, ps, ownerID, &wspubsub.WorkspaceEvent{
|
|
Kind: wspubsub.WorkspaceEventKindStateChange,
|
|
WorkspaceID: ws1ID,
|
|
})
|
|
|
|
update = testutil.TryReceive(ctx, t, sub.Updates())
|
|
slices.SortFunc(update.UpsertedWorkspaces, func(a, b *proto.Workspace) int {
|
|
return strings.Compare(a.Name, b.Name)
|
|
})
|
|
require.Equal(t, &proto.WorkspaceUpdate{
|
|
UpsertedWorkspaces: []*proto.Workspace{
|
|
{
|
|
// Changed status
|
|
Id: ws2IDSlice,
|
|
Name: "ws2",
|
|
Status: proto.Workspace_STOPPING,
|
|
},
|
|
{
|
|
// New workspace
|
|
Id: ws4IDSlice,
|
|
Name: "ws4",
|
|
Status: proto.Workspace_STARTING,
|
|
},
|
|
},
|
|
UpsertedAgents: []*proto.Agent{
|
|
{
|
|
Id: agent2IDSlice,
|
|
Name: "agent2",
|
|
WorkspaceId: ws1IDSlice,
|
|
},
|
|
},
|
|
DeletedWorkspaces: []*proto.Workspace{
|
|
{
|
|
Id: ws3IDSlice,
|
|
Name: "ws3",
|
|
Status: proto.Workspace_STOPPED,
|
|
},
|
|
},
|
|
DeletedAgents: []*proto.Agent{
|
|
{
|
|
Id: agent3IDSlice,
|
|
Name: "agent3",
|
|
WorkspaceId: ws3IDSlice,
|
|
},
|
|
},
|
|
}, update)
|
|
})
|
|
|
|
t.Run("Resubscribe", func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitShort)
|
|
|
|
db := &mockWorkspaceStore{
|
|
orderedRows: []database.GetWorkspacesAndAgentsByOwnerIDRow{
|
|
{
|
|
ID: ws1ID,
|
|
Name: "ws1",
|
|
JobStatus: database.ProvisionerJobStatusRunning,
|
|
Transition: database.WorkspaceTransitionStart,
|
|
Agents: []database.AgentIDNamePair{
|
|
{
|
|
ID: agent1ID,
|
|
Name: "agent1",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
}
|
|
|
|
ps := &mockPubsub{
|
|
cbs: map[string]pubsub.ListenerWithErr{},
|
|
}
|
|
|
|
updateProvider := coderd.NewUpdatesProvider(testutil.Logger(t), ps, db, &mockAuthorizer{})
|
|
t.Cleanup(func() {
|
|
_ = updateProvider.Close()
|
|
})
|
|
|
|
sub, err := updateProvider.Subscribe(dbauthz.As(ctx, ownerSubject), ownerID)
|
|
require.NoError(t, err)
|
|
t.Cleanup(func() {
|
|
_ = sub.Close()
|
|
})
|
|
|
|
expected := &proto.WorkspaceUpdate{
|
|
UpsertedWorkspaces: []*proto.Workspace{
|
|
{
|
|
Id: ws1IDSlice,
|
|
Name: "ws1",
|
|
Status: proto.Workspace_STARTING,
|
|
},
|
|
},
|
|
UpsertedAgents: []*proto.Agent{
|
|
{
|
|
Id: agent1IDSlice,
|
|
Name: "agent1",
|
|
WorkspaceId: ws1IDSlice,
|
|
},
|
|
},
|
|
DeletedWorkspaces: []*proto.Workspace{},
|
|
DeletedAgents: []*proto.Agent{},
|
|
}
|
|
|
|
update := testutil.TryReceive(ctx, t, sub.Updates())
|
|
slices.SortFunc(update.UpsertedWorkspaces, func(a, b *proto.Workspace) int {
|
|
return strings.Compare(a.Name, b.Name)
|
|
})
|
|
require.Equal(t, expected, update)
|
|
|
|
resub, err := updateProvider.Subscribe(dbauthz.As(ctx, ownerSubject), ownerID)
|
|
require.NoError(t, err)
|
|
t.Cleanup(func() {
|
|
_ = resub.Close()
|
|
})
|
|
|
|
update = testutil.TryReceive(ctx, t, resub.Updates())
|
|
slices.SortFunc(update.UpsertedWorkspaces, func(a, b *proto.Workspace) int {
|
|
return strings.Compare(a.Name, b.Name)
|
|
})
|
|
require.Equal(t, expected, update)
|
|
})
|
|
}
|
|
|
|
func TestWorkspaceUpdatesClose(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
for _, stage := range []string{"QueryInFlight", "CallbackAfterClose"} {
|
|
t.Run(stage, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
synctest.Test(t, func(t *testing.T) {
|
|
// If Close closed the channel, a send would race the canceled
|
|
// context. Repeat so either selection is exercised.
|
|
for range 32 {
|
|
ownerID := uuid.New()
|
|
db := &mockWorkspaceStore{}
|
|
ps := &mockPubsub{cbs: map[string]pubsub.ListenerWithErr{}}
|
|
provider := coderd.NewUpdatesProvider(testutil.Logger(t), ps, db, &mockAuthorizer{})
|
|
ctx := dbauthz.As(t.Context(), rbac.Subject{ID: ownerID.String()})
|
|
sub, err := provider.Subscribe(ctx, ownerID)
|
|
require.NoError(t, err)
|
|
|
|
queryRelease := make(chan struct{})
|
|
var queryContext context.Context
|
|
db.getWorkspaces = func(ctx context.Context, _ uuid.UUID) ([]database.GetWorkspacesAndAgentsByOwnerIDRow, error) {
|
|
queryContext = ctx
|
|
if stage == "QueryInFlight" {
|
|
<-queryRelease
|
|
}
|
|
// A query can return successfully even as its context is canceled.
|
|
return []database.GetWorkspacesAndAgentsByOwnerIDRow{{ID: uuid.New()}}, nil
|
|
}
|
|
msg, err := json.Marshal(wspubsub.WorkspaceEvent{Kind: wspubsub.WorkspaceEventKindStateChange})
|
|
require.NoError(t, err)
|
|
// Pubsub unsubscribe does not join an already-dispatched callback.
|
|
callback := ps.cbs[wspubsub.WorkspaceEventChannel(ownerID)]
|
|
callbackDone := make(chan struct{})
|
|
invoke := func() {
|
|
defer close(callbackDone)
|
|
callback(context.Background(), msg, nil)
|
|
}
|
|
|
|
if stage != "CallbackAfterClose" {
|
|
// Leave the initial update buffered so sending cannot proceed.
|
|
go invoke()
|
|
synctest.Wait()
|
|
}
|
|
closeDone := make(chan error, 1)
|
|
go func() { closeDone <- sub.Close() }()
|
|
if stage == "QueryInFlight" {
|
|
<-queryContext.Done()
|
|
}
|
|
close(queryRelease)
|
|
require.NoError(t, <-closeDone)
|
|
if stage == "CallbackAfterClose" {
|
|
go invoke()
|
|
}
|
|
<-callbackDone
|
|
|
|
// Closing preserves the buffered update.
|
|
initial, ok := <-sub.Updates()
|
|
require.True(t, ok)
|
|
require.NotNil(t, initial)
|
|
require.NoError(t, provider.Close())
|
|
}
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
func publishWorkspaceEvent(t *testing.T, ps pubsub.Pubsub, ownerID uuid.UUID, event *wspubsub.WorkspaceEvent) {
|
|
msg, err := json.Marshal(event)
|
|
require.NoError(t, err)
|
|
ps.Publish(wspubsub.WorkspaceEventChannel(ownerID), msg)
|
|
}
|
|
|
|
type mockWorkspaceStore struct {
|
|
orderedRows []database.GetWorkspacesAndAgentsByOwnerIDRow
|
|
getWorkspaces func(context.Context, uuid.UUID) ([]database.GetWorkspacesAndAgentsByOwnerIDRow, error)
|
|
}
|
|
|
|
// GetAuthorizedWorkspacesAndAgentsByOwnerID implements coderd.UpdatesQuerier.
|
|
func (m *mockWorkspaceStore) GetWorkspacesAndAgentsByOwnerID(ctx context.Context, ownerID uuid.UUID) ([]database.GetWorkspacesAndAgentsByOwnerIDRow, error) {
|
|
if m.getWorkspaces != nil {
|
|
return m.getWorkspaces(ctx, ownerID)
|
|
}
|
|
return m.orderedRows, nil
|
|
}
|
|
|
|
// GetWorkspaceByAgentID implements coderd.UpdatesQuerier.
|
|
func (*mockWorkspaceStore) GetWorkspaceByAgentID(context.Context, uuid.UUID) (database.Workspace, error) {
|
|
return database.Workspace{}, nil
|
|
}
|
|
|
|
var _ coderd.UpdatesQuerier = (*mockWorkspaceStore)(nil)
|
|
|
|
type mockPubsub struct {
|
|
cbs map[string]pubsub.ListenerWithErr
|
|
}
|
|
|
|
// Close implements pubsub.Pubsub.
|
|
func (*mockPubsub) Close() error {
|
|
panic("unimplemented")
|
|
}
|
|
|
|
// Publish implements pubsub.Pubsub.
|
|
func (m *mockPubsub) Publish(event string, message []byte) error {
|
|
cb, ok := m.cbs[event]
|
|
if !ok {
|
|
return nil
|
|
}
|
|
cb(context.Background(), message, nil)
|
|
return nil
|
|
}
|
|
|
|
func (*mockPubsub) Subscribe(string, pubsub.Listener) (cancel func(), err error) {
|
|
panic("unimplemented")
|
|
}
|
|
|
|
func (m *mockPubsub) SubscribeWithErr(event string, listener pubsub.ListenerWithErr) (func(), error) {
|
|
m.cbs[event] = listener
|
|
return func() {}, nil
|
|
}
|
|
|
|
var _ pubsub.Pubsub = (*mockPubsub)(nil)
|
|
|
|
type mockAuthorizer struct{}
|
|
|
|
func (*mockAuthorizer) Authorize(context.Context, rbac.Subject, policy.Action, rbac.Object) error {
|
|
return nil
|
|
}
|
|
|
|
// Prepare implements rbac.Authorizer.
|
|
func (*mockAuthorizer) Prepare(context.Context, rbac.Subject, policy.Action, string) (rbac.PreparedAuthorized, error) {
|
|
//nolint:nilnil
|
|
return nil, nil
|
|
}
|
|
|
|
var _ rbac.Authorizer = (*mockAuthorizer)(nil)
|