@@ -56,7 +56,12 @@ func (r *Runner) Run(ctx context.Context, _ string, logs io.Writer) error {
56
56
bytesPerTick = r .cfg .BytesPerSecond / r .cfg .TicksPerSecond
57
57
)
58
58
59
+ // Set a deadline for stopping the text.
60
+ start := time .Now ()
61
+ deadlineCtx , cancel := context .WithDeadline (ctx , start .Add (r .cfg .Duration ))
62
+ defer cancel ()
59
63
logger .Debug (ctx , "connect to workspace agent" , slog .F ("agent_id" , agentID ))
64
+
60
65
conn , err := r .client .WorkspaceAgentReconnectingPTY (ctx , codersdk.WorkspaceAgentReconnectingPTYOpts {
61
66
AgentID : agentID ,
62
67
Reconnect : reconnect ,
@@ -74,11 +79,6 @@ func (r *Runner) Run(ctx context.Context, _ string, logs io.Writer) error {
74
79
_ = conn .Close ()
75
80
}()
76
81
77
- // Set a deadline for stopping the text.
78
- start := time .Now ()
79
- deadlineCtx , cancel := context .WithDeadline (ctx , start .Add (r .cfg .Duration ))
80
- defer cancel ()
81
-
82
82
// Wrap the conn in a countReadWriter so we can monitor bytes sent/rcvd.
83
83
crw := countReadWriter {ReadWriter : conn , ctx : deadlineCtx }
84
84
@@ -112,7 +112,7 @@ func (r *Runner) Run(ctx context.Context, _ string, logs io.Writer) error {
112
112
close (wch )
113
113
}()
114
114
115
- // Wait for both our reads and writes to be finished .
115
+ // Write until the context is canceled .
116
116
if wErr := <- wch ; wErr != nil {
117
117
return xerrors .Errorf ("write to pty: %w" , wErr )
118
118
}
@@ -138,7 +138,7 @@ func (*Runner) Cleanup(context.Context, string) error {
138
138
139
139
// drainContext drains from src until it returns io.EOF or ctx times out.
140
140
func drainContext (ctx context.Context , src io.Reader , bufSize int64 ) error {
141
- errCh := make (chan error )
141
+ errCh := make (chan error , 1 )
142
142
done := make (chan struct {})
143
143
go func () {
144
144
tmp := make ([]byte , bufSize )
@@ -149,6 +149,9 @@ func drainContext(ctx context.Context, src io.Reader, bufSize int64) error {
149
149
return
150
150
default :
151
151
_ , err := io .CopyN (buf , src , 1 )
152
+ if ctx .Err () != nil {
153
+ return // context canceled while we were copying.
154
+ }
152
155
if err != nil {
153
156
errCh <- err
154
157
close (errCh )
0 commit comments