Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds a stream interceptor to keep state between the send and receive calls #437

Merged
merged 1 commit into from
May 5, 2024

Conversation

nadinelyab
Copy link
Contributor

Adds an new option WithStreamInterceptorProviderFunc where a StreamInterceptorProviderFunc can be specified. With this option a new Stream Interceptor will be created for each new stream created. The Stream Interceptor's Send and Recv functions will be called when a message is sent or received. Unlike the StreamRecvMsgInterceptFunc and StreamMessageProviderFunc, the StreamInterceptor can keep state that both Send and Recv functions may need access to.

Here is an example of how to use the Stream Interceptor:
`

    type ABCStreamInterceptor struct {
	MsgRcvCount  int
	MsgSendCount int
            MsgChan 	 chan int
}

func (s *ABCStreamInterceptor) Send(callData *CallData) (*dynamic.Message, error) {
	defer func() { s.MsgSendCount++ }()
	switch s.MsgSendCount {
	case 0:
		return dynamic.AsDynamicMessage(&exampleapi.Request{
			Num: 1,
		})
	case 1:
		num := <-s.MsgChan
		return dynamic.AsDynamicMessage(&exampleapi.Request{
			Num: num,
		})
	default:
		return nil, fmt.Errorf("unknown msg send")
	}
}

func (s *ABCStreamInterceptor) Recv(msg *dynamic.Message, err error) error {
	if msg == nil {
		return err
	}
	s.MsgRcvCount++

	reply := exampleapi.Response{}
	err = msg.ConvertTo(reply)
	if err != nil {
		return err
	}

	switch s.MsgRcvCount {
	case 0:
		s.MsgChan <- reply.Num
		return nil
	case 1:
		return runner.ErrEndStream
	default:
		return fmt.Errorf("unknown msg recv")
	}
}

WithStreamInterceptorProviderFunc(func NewABCInterceptor() StreamInterceptor {
	return &ABCStreamInterceptor{
			MsgChan:          make(chan exampleapi.response, 1),
		}
	}
})`

@nadinelyab
Copy link
Contributor Author

@bojand let me know if you have some time to review. Thank you so much!

@bojand
Copy link
Owner

bojand commented Apr 26, 2024

Hello, thanks for the PR. I'll try and take a look at this soon.

@bojand bojand merged commit 6bc85c8 into bojand:master May 5, 2024
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants