trpc.group/trpc-go/trpc-go@v1.0.3/rpcz/spanstore.go (about) 1 // 2 // 3 // Tencent is pleased to support the open source community by making tRPC available. 4 // 5 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 6 // All rights reserved. 7 // 8 // If you have downloaded a copy of the tRPC source code from Tencent, 9 // please note that tRPC source code is licensed under the Apache 2.0 License, 10 // A copy of the Apache 2.0 License is included in this file. 11 // 12 // 13 14 package rpcz 15 16 import ( 17 "sync" 18 ) 19 20 // spanStore stores spans that has ended its life. 21 type spanStore struct { 22 sync.RWMutex // protects everything below. 23 idSpans map[SpanID]*span 24 spans *spanArray 25 } 26 27 // insert adds a span to spanStore. 28 func (ss *spanStore) insert(s *span) { 29 ss.Lock() 30 defer ss.Unlock() 31 32 if ss.spans.full() { 33 expiredSpan := ss.spans.front() 34 ss.spans.dequeue() 35 36 delete(ss.idSpans, expiredSpan.id) 37 38 putSpanToPool(expiredSpan) 39 } 40 41 ss.spans.enqueue(s) 42 ss.idSpans[s.ID()] = s 43 } 44 45 // query returns a ReadOnlySpan converted from span whose SpanID equals id. 46 func (ss *spanStore) query(id SpanID) (*ReadOnlySpan, bool) { 47 ss.RLock() 48 defer ss.RUnlock() 49 s, ok := ss.idSpans[id] 50 if !ok { 51 return nil, false 52 } 53 return s.convertedToReadOnlySpan(), true 54 } 55 56 // batchQuery returns #num ReadOnlySpan converted from span that is newly inserted to spanStore. 57 func (ss *spanStore) batchQuery(num int) (spans []*ReadOnlySpan) { 58 ss.RLock() 59 ss.spans.doBackward(func(s *span) bool { 60 if num <= 0 { 61 return false 62 } 63 num-- 64 spans = append(spans, s.convertedToReadOnlySpan()) 65 return true 66 }) 67 ss.RUnlock() 68 return spans 69 } 70 71 func newSpanStore(capacity uint32) *spanStore { 72 return &spanStore{ 73 idSpans: make(map[SpanID]*span), 74 spans: newSpanArray(capacity), 75 } 76 }