Skip to content

Commit 4835fdf

Browse files
committed
fn: Add new Req type to abstract the pattern of remote processing.
It is common throughout the codebase to send data to a remote goroutine for processing. Typically, along with the data we are processing, we also send a one-shot channel where we intend to listen for the response. This type encapsulates that pattern.
1 parent b7c59b3 commit 4835fdf

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

fn/req.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package fn
2+
3+
// Req is a type to encapsulate RPC-like calls wherein we send some data
4+
// structure as a request, as well as a channel to receive the response on where
5+
// the remote goroutine will send the result.
6+
//
7+
// NOTE: This construct should only be used for request/response patterns for
8+
// which there is only a single response for the request.
9+
type Req[Input any, Output any] struct {
10+
// Request is the data we are sending to the remote goroutine for
11+
// processing.
12+
Request Input
13+
14+
// Response is the channel on which we will receive the result of the
15+
// remote computation.
16+
Response chan<- Output
17+
}
18+
19+
// NewReq is the base constructor of the Req type. It returns both the packaged
20+
// Req object as well as the receive side of the response channel that we will
21+
// listen on for the response.
22+
func NewReq[Input, Output any](input Input) (
23+
Req[Input, Output], <-chan Output) {
24+
25+
// Always buffer the response channel so that the goroutine doing the
26+
// processing job does not block if the original requesting routine
27+
// takes an unreasonably long time to read the response.
28+
responseChan := make(chan Output, 1)
29+
30+
return Req[Input, Output]{
31+
Request: input,
32+
Response: responseChan,
33+
}, responseChan
34+
}

0 commit comments

Comments
 (0)