|
| 1 | +// Copyright 2023 The Go Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +//go:build go1.21 |
| 6 | + |
| 7 | +package quic |
| 8 | + |
| 9 | +import ( |
| 10 | + "context" |
| 11 | + "errors" |
| 12 | + "fmt" |
| 13 | + "path/filepath" |
| 14 | + "runtime" |
| 15 | + "sync" |
| 16 | +) |
| 17 | + |
| 18 | +// asyncTestState permits handling asynchronous operations in a synchronous test. |
| 19 | +// |
| 20 | +// For example, a test may want to write to a stream and observe that |
| 21 | +// STREAM frames are sent with the contents of the write in response |
| 22 | +// to MAX_STREAM_DATA frames received from the peer. |
| 23 | +// The Stream.Write is an asynchronous operation, but the test is simpler |
| 24 | +// if we can start the write, observe the first STREAM frame sent, |
| 25 | +// send a MAX_STREAM_DATA frame, observe the next STREAM frame sent, etc. |
| 26 | +// |
| 27 | +// We do this by instrumenting points where operations can block. |
| 28 | +// We start async operations like Write in a goroutine, |
| 29 | +// and wait for the operation to either finish or hit a blocking point. |
| 30 | +// When the connection event loop is idle, we check a list of |
| 31 | +// blocked operations to see if any can be woken. |
| 32 | +type asyncTestState struct { |
| 33 | + mu sync.Mutex |
| 34 | + notify chan struct{} |
| 35 | + blocked map[*blockedAsync]struct{} |
| 36 | +} |
| 37 | + |
| 38 | +// An asyncOp is an asynchronous operation that results in (T, error). |
| 39 | +type asyncOp[T any] struct { |
| 40 | + v T |
| 41 | + err error |
| 42 | + |
| 43 | + caller string |
| 44 | + state *asyncTestState |
| 45 | + donec chan struct{} |
| 46 | + cancelFunc context.CancelFunc |
| 47 | +} |
| 48 | + |
| 49 | +// cancel cancels the async operation's context, and waits for |
| 50 | +// the operation to complete. |
| 51 | +func (a *asyncOp[T]) cancel() { |
| 52 | + select { |
| 53 | + case <-a.donec: |
| 54 | + return // already done |
| 55 | + default: |
| 56 | + } |
| 57 | + a.cancelFunc() |
| 58 | + <-a.state.notify |
| 59 | + select { |
| 60 | + case <-a.donec: |
| 61 | + default: |
| 62 | + panic(fmt.Errorf("%v: async op failed to finish after being canceled", a.caller)) |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +var errNotDone = errors.New("async op is not done") |
| 67 | + |
| 68 | +// result returns the result of the async operation. |
| 69 | +// It returns errNotDone if the operation is still in progress. |
| 70 | +// |
| 71 | +// Note that unlike a traditional async/await, this doesn't block |
| 72 | +// waiting for the operation to complete. Since tests have full |
| 73 | +// control over the progress of operations, an asyncOp can only |
| 74 | +// become done in reaction to the test taking some action. |
| 75 | +func (a *asyncOp[T]) result() (v T, err error) { |
| 76 | + select { |
| 77 | + case <-a.donec: |
| 78 | + return a.v, a.err |
| 79 | + default: |
| 80 | + return v, errNotDone |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +// A blockedAsync is a blocked async operation. |
| 85 | +// |
| 86 | +// Currently, the only type of blocked operation is one waiting on a gate. |
| 87 | +type blockedAsync struct { |
| 88 | + g *gate |
| 89 | + donec chan struct{} // closed when the operation is unblocked |
| 90 | +} |
| 91 | + |
| 92 | +type asyncContextKey struct{} |
| 93 | + |
| 94 | +// runAsync starts an asynchronous operation. |
| 95 | +// |
| 96 | +// The function f should call a blocking function such as |
| 97 | +// Stream.Write or Conn.AcceptStream and return its result. |
| 98 | +// It must use the provided context. |
| 99 | +func runAsync[T any](ts *testConn, f func(context.Context) (T, error)) *asyncOp[T] { |
| 100 | + as := &ts.asyncTestState |
| 101 | + if as.notify == nil { |
| 102 | + as.notify = make(chan struct{}) |
| 103 | + as.blocked = make(map[*blockedAsync]struct{}) |
| 104 | + } |
| 105 | + _, file, line, _ := runtime.Caller(1) |
| 106 | + ctx := context.WithValue(context.Background(), asyncContextKey{}, true) |
| 107 | + ctx, cancel := context.WithCancel(ctx) |
| 108 | + a := &asyncOp[T]{ |
| 109 | + state: as, |
| 110 | + caller: fmt.Sprintf("%v:%v", filepath.Base(file), line), |
| 111 | + donec: make(chan struct{}), |
| 112 | + cancelFunc: cancel, |
| 113 | + } |
| 114 | + go func() { |
| 115 | + a.v, a.err = f(ctx) |
| 116 | + close(a.donec) |
| 117 | + as.notify <- struct{}{} |
| 118 | + }() |
| 119 | + ts.t.Cleanup(func() { |
| 120 | + if _, err := a.result(); err == errNotDone { |
| 121 | + ts.t.Errorf("%v: async operation is still executing at end of test", a.caller) |
| 122 | + a.cancel() |
| 123 | + } |
| 124 | + }) |
| 125 | + // Wait for the operation to either finish or block. |
| 126 | + <-as.notify |
| 127 | + return a |
| 128 | +} |
| 129 | + |
| 130 | +// waitAndLockGate replaces gate.waitAndLock in tests. |
| 131 | +func (as *asyncTestState) waitAndLockGate(ctx context.Context, g *gate) error { |
| 132 | + if g.lockIfSet() { |
| 133 | + // Gate can be acquired without blocking. |
| 134 | + return nil |
| 135 | + } |
| 136 | + if err := ctx.Err(); err != nil { |
| 137 | + // Context has already expired. |
| 138 | + return err |
| 139 | + } |
| 140 | + if ctx.Value(asyncContextKey{}) == nil { |
| 141 | + // Context is not one that we've created, and hasn't expired. |
| 142 | + // This probably indicates that we've tried to perform a |
| 143 | + // blocking operation without using the async test harness here, |
| 144 | + // which may have unpredictable results. |
| 145 | + panic("blocking async point with unexpected Context") |
| 146 | + } |
| 147 | + // Record this as a pending blocking operation. |
| 148 | + as.mu.Lock() |
| 149 | + b := &blockedAsync{ |
| 150 | + g: g, |
| 151 | + donec: make(chan struct{}), |
| 152 | + } |
| 153 | + as.blocked[b] = struct{}{} |
| 154 | + as.mu.Unlock() |
| 155 | + // Notify the creator of the operation that we're blocked, |
| 156 | + // and wait to be woken up. |
| 157 | + as.notify <- struct{}{} |
| 158 | + select { |
| 159 | + case <-b.donec: |
| 160 | + case <-ctx.Done(): |
| 161 | + return ctx.Err() |
| 162 | + } |
| 163 | + return nil |
| 164 | +} |
| 165 | + |
| 166 | +// wakeAsync tries to wake up a blocked async operation. |
| 167 | +// It returns true if one was woken, false otherwise. |
| 168 | +func (as *asyncTestState) wakeAsync() bool { |
| 169 | + as.mu.Lock() |
| 170 | + var woken *blockedAsync |
| 171 | + for w := range as.blocked { |
| 172 | + if w.g.lockIfSet() { |
| 173 | + woken = w |
| 174 | + delete(as.blocked, woken) |
| 175 | + break |
| 176 | + } |
| 177 | + } |
| 178 | + as.mu.Unlock() |
| 179 | + if woken == nil { |
| 180 | + return false |
| 181 | + } |
| 182 | + close(woken.donec) |
| 183 | + <-as.notify // must not hold as.mu while blocked here |
| 184 | + return true |
| 185 | +} |
0 commit comments