MCPcopy Create free account
hub / github.com/wavetermdev/waveterm / WriterChan

Function WriterChan

pkg/util/iochan/iochan.go:62–102  ·  view source on GitHub ↗

WriterChan reads from a channel and writes the data to an io.Writer

(ctx context.Context, w io.Writer, ch <-chan wshrpc.RespOrErrorUnion[iochantypes.Packet], callback func(), cancel context.CancelCauseFunc)

Source from the content-addressed store, hash-verified

60
61// WriterChan reads from a channel and writes the data to an io.Writer
62func WriterChan(ctx context.Context, w io.Writer, ch <-chan wshrpc.RespOrErrorUnion[iochantypes.Packet], callback func(), cancel context.CancelCauseFunc) {
63 go func() {
64 defer func() {
65 if ctx.Err() != nil {
66 utilfn.DrainChannelSafe(ch, "WriterChan")
67 }
68 callback()
69 }()
70 sha256Hash := sha256.New()
71 for {
72 select {
73 case <-ctx.Done():
74 return
75 case resp, ok := <-ch:
76 if !ok {
77 return
78 }
79 if resp.Error != nil {
80 cancel(resp.Error)
81 return
82 }
83 if _, err := sha256Hash.Write(resp.Response.Data); err != nil {
84 cancel(fmt.Errorf("WriterChan: error writing to sha256 hash: %v", err))
85 return
86 }
87 // The checksum is sent as the last packet
88 if resp.Response.Checksum != nil {
89 localChecksum := sha256Hash.Sum(nil)
90 if !bytes.Equal(localChecksum, resp.Response.Checksum) {
91 cancel(fmt.Errorf("WriterChan: checksum mismatch"))
92 }
93 return
94 }
95 if _, err := w.Write(resp.Response.Data); err != nil {
96 cancel(fmt.Errorf("WriterChan: write error: %v", err))
97 return
98 }
99 }
100 }
101 }()
102}

Callers 1

TestIochan_BasicFunction · 0.92

Calls 3

DrainChannelSafeFunction · 0.92
ErrMethod · 0.80
WriteMethod · 0.65

Tested by 1

TestIochan_BasicFunction · 0.74