dynamic_channel_buffer.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2021 EMQ Technologies Co., Ltd.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package node
  15. import (
  16. "github.com/lf-edge/ekuiper/pkg/api"
  17. "sync/atomic"
  18. )
  19. type DynamicChannelBuffer struct {
  20. limit int64
  21. In chan api.SourceTuple
  22. Out chan api.SourceTuple
  23. buffer []api.SourceTuple
  24. done chan bool
  25. }
  26. func NewDynamicChannelBuffer() *DynamicChannelBuffer {
  27. buffer := &DynamicChannelBuffer{
  28. In: make(chan api.SourceTuple),
  29. Out: make(chan api.SourceTuple),
  30. buffer: make([]api.SourceTuple, 0),
  31. limit: 102400,
  32. done: make(chan bool, 1),
  33. }
  34. go buffer.run()
  35. return buffer
  36. }
  37. func (b *DynamicChannelBuffer) SetLimit(limit int) {
  38. if limit > 0 {
  39. atomic.StoreInt64(&b.limit, int64(limit))
  40. }
  41. }
  42. func (b *DynamicChannelBuffer) run() {
  43. for {
  44. l := len(b.buffer)
  45. if int64(l) >= atomic.LoadInt64(&b.limit) {
  46. select {
  47. case b.Out <- b.buffer[0]:
  48. b.buffer = b.buffer[1:]
  49. case <-b.done:
  50. return
  51. }
  52. } else if l > 0 {
  53. select {
  54. case b.Out <- b.buffer[0]:
  55. b.buffer = b.buffer[1:]
  56. case value := <-b.In:
  57. b.buffer = append(b.buffer, value)
  58. case <-b.done:
  59. return
  60. }
  61. } else {
  62. select {
  63. case value := <-b.In:
  64. b.buffer = append(b.buffer, value)
  65. case <-b.done:
  66. return
  67. }
  68. }
  69. }
  70. }
  71. func (b *DynamicChannelBuffer) GetLength() int {
  72. return len(b.buffer)
  73. }
  74. func (b *DynamicChannelBuffer) Close() {
  75. b.done <- true
  76. }