stream.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. Copyright The containerd Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package ttrpc
  14. import (
  15. "context"
  16. "sync"
  17. )
  18. type streamID uint32
  19. type streamMessage struct {
  20. header messageHeader
  21. payload []byte
  22. }
  23. type stream struct {
  24. id streamID
  25. sender sender
  26. recv chan *streamMessage
  27. closeOnce sync.Once
  28. recvErr error
  29. recvClose chan struct{}
  30. }
  31. func newStream(id streamID, send sender) *stream {
  32. return &stream{
  33. id: id,
  34. sender: send,
  35. recv: make(chan *streamMessage, 1),
  36. recvClose: make(chan struct{}),
  37. }
  38. }
  39. func (s *stream) closeWithError(err error) error {
  40. s.closeOnce.Do(func() {
  41. if err != nil {
  42. s.recvErr = err
  43. } else {
  44. s.recvErr = ErrClosed
  45. }
  46. close(s.recvClose)
  47. })
  48. return nil
  49. }
  50. func (s *stream) send(mt messageType, flags uint8, b []byte) error {
  51. return s.sender.send(uint32(s.id), mt, flags, b)
  52. }
  53. func (s *stream) receive(ctx context.Context, msg *streamMessage) error {
  54. select {
  55. case <-s.recvClose:
  56. return s.recvErr
  57. default:
  58. }
  59. select {
  60. case <-s.recvClose:
  61. return s.recvErr
  62. case s.recv <- msg:
  63. return nil
  64. case <-ctx.Done():
  65. return ctx.Err()
  66. }
  67. }
  68. type sender interface {
  69. send(uint32, messageType, uint8, []byte) error
  70. }