tractor.dev/toolkit-go@v0.0.0-20241010005851-214d91207d07/duplex/interop/service.go (about) 1 package interop 2 3 import ( 4 "context" 5 "errors" 6 "io" 7 "log" 8 9 "tractor.dev/toolkit-go/duplex/rpc" 10 ) 11 12 type InteropService struct{} 13 14 func (s InteropService) Unary(resp rpc.Responder, call *rpc.Call) { 15 var params any 16 if err := call.Receive(¶ms); err != nil { 17 log.Println(err) 18 return 19 } 20 ctx := context.Background() 21 var ret any 22 _, err := call.Caller.Call(ctx, "UnaryCallback", params, &ret) 23 if err != nil { 24 log.Println(err) 25 return 26 } 27 if err := resp.Return(ret); err != nil { 28 log.Println(err) 29 } 30 } 31 32 func (s InteropService) Stream(resp rpc.Responder, call *rpc.Call) { 33 var params any 34 if err := call.Receive(¶ms); err != nil { 35 log.Println(err) 36 return 37 } 38 ctx := context.Background() 39 var ret any 40 stream, err := call.Caller.Call(ctx, "StreamCallback", params, &ret) 41 if err != nil { 42 log.Println(err) 43 return 44 } 45 ch, err := resp.Continue(ret) 46 if err != nil { 47 log.Println(err) 48 return 49 } 50 defer ch.Close() 51 defer stream.Close() 52 go func() { 53 var v any 54 var err error 55 for { 56 err = call.Receive(&v) 57 if err != nil { 58 break 59 } 60 err = stream.Send(v) 61 if err != nil { 62 break 63 } 64 } 65 stream.CloseWrite() 66 }() 67 var v any 68 for { 69 err = stream.Receive(&v) 70 if err != nil { 71 break 72 } 73 err = resp.Send(v) 74 if err != nil { 75 break 76 } 77 } 78 } 79 80 func (s InteropService) Bytes(resp rpc.Responder, call *rpc.Call) { 81 var params any 82 if err := call.Receive(¶ms); err != nil { 83 log.Println(err) 84 return 85 } 86 ctx := context.Background() 87 var ret any 88 stream, err := call.Caller.Call(ctx, "BytesCallback", params, &ret) 89 if err != nil { 90 log.Println(err) 91 return 92 } 93 ch, err := resp.Continue(ret) 94 if err != nil { 95 log.Println(err) 96 return 97 } 98 defer ch.Close() 99 defer stream.Close() 100 go func() { 101 io.Copy(stream.Channel, call) 102 stream.Channel.CloseWrite() 103 }() 104 io.Copy(ch, stream.Channel) 105 } 106 107 func (s InteropService) Error(resp rpc.Responder, call *rpc.Call) { 108 var text string 109 if err := call.Receive(&text); err != nil { 110 log.Println(err) 111 return 112 } 113 if err := resp.Return(errors.New(text)); err != nil { 114 log.Println(err) 115 } 116 }