dynamic_channel_buffer.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2021-2022 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. "sync/atomic"
  17. "github.com/lf-edge/ekuiper/pkg/api"
  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, 1024),
  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. // fmt.Println("out loud")
  56. b.buffer = b.buffer[1:]
  57. case value := <-b.In:
  58. // fmt.Printf("in loud with length %d\n", len(b.In))
  59. b.buffer = append(b.buffer, value)
  60. case <-b.done:
  61. return
  62. }
  63. } else {
  64. select {
  65. case value := <-b.In:
  66. // fmt.Printf("in quiet with length %d \n", len(b.In))
  67. b.buffer = append(b.buffer, value)
  68. case <-b.done:
  69. return
  70. }
  71. }
  72. }
  73. }
  74. func (b *DynamicChannelBuffer) GetLength() int {
  75. return len(b.buffer)
  76. }
  77. func (b *DynamicChannelBuffer) Close() {
  78. b.done <- true
  79. }