github.com/matrixorigin/matrixone@v1.2.0/pkg/common/morpc/cache.go (about) 1 // Copyright 2023 Matrix Origin 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 15 package morpc 16 17 import ( 18 "sync" 19 20 "github.com/matrixorigin/matrixone/pkg/common/moerr" 21 ) 22 23 type cache struct { 24 sync.RWMutex 25 closed bool 26 queue []Message 27 } 28 29 func newCache() MessageCache { 30 return &cache{} 31 } 32 33 func (c *cache) Add(value Message) error { 34 c.Lock() 35 defer c.Unlock() 36 if c.closed { 37 return moerr.NewInvalidStateNoCtx("cache is closed") 38 } 39 c.queue = append(c.queue, value) 40 return nil 41 } 42 43 func (c *cache) Len() (int, error) { 44 c.RLock() 45 defer c.RUnlock() 46 if c.closed { 47 return 0, moerr.NewInvalidStateNoCtx("cache is closed") 48 } 49 return len(c.queue), nil 50 } 51 52 func (c *cache) Pop() (Message, bool, error) { 53 c.Lock() 54 defer c.Unlock() 55 if c.closed { 56 return nil, false, moerr.NewInvalidStateNoCtx("cache is closed") 57 } 58 59 if len(c.queue) == 0 { 60 return nil, false, nil 61 } 62 v := c.queue[0] 63 c.queue[0] = nil 64 c.queue = c.queue[1:] 65 return v, true, nil 66 } 67 68 func (c *cache) Close() { 69 c.Lock() 70 defer c.Unlock() 71 for idx := range c.queue { 72 c.queue[idx] = nil 73 } 74 c.closed = true 75 }