github.com/cloudwego/localsession@v0.0.2/stubs.go (about) 1 // Copyright 2023 CloudWeGo Authors 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 localsession 15 16 import ( 17 "strconv" 18 _ "unsafe" 19 20 "github.com/modern-go/gls" 21 ) 22 23 //go:nocheckptr 24 func goID() uint64 { 25 return uint64(gls.GoID()) 26 } 27 28 type labelMap map[string]string 29 30 //go:linkname setPprofLabel runtime/pprof.runtime_setProfLabel 31 func setPprofLabel(m *labelMap) 32 33 //go:linkname getPproLabel runtime/pprof.runtime_getProfLabel 34 func getPproLabel() *labelMap 35 36 const Pprof_Label_Session_ID = "go_session_id" 37 38 func transmitSessionID(id SessionID) { 39 m := getPproLabel() 40 41 var n labelMap 42 if m == nil { 43 n = make(labelMap) 44 } else { 45 n = make(labelMap, len(*m)) 46 for k, v := range *m { 47 if k != Pprof_Label_Session_ID { 48 n[k] = v 49 } 50 } 51 } 52 53 n[Pprof_Label_Session_ID] = strconv.FormatInt(int64(id), 10) 54 setPprofLabel(&n) 55 } 56 57 func getSessionID() (SessionID, bool) { 58 m := getPproLabel() 59 if m == nil { 60 return 0, false 61 } 62 if v, ok := (*m)[Pprof_Label_Session_ID]; !ok { 63 return 0, false 64 } else { 65 id, err := strconv.ParseInt(v, 10, 64) 66 if err != nil { 67 return 0, false 68 } 69 return SessionID(id), true 70 } 71 } 72 73 func clearSessionID() { 74 m := getPproLabel() 75 if m == nil { 76 return 77 } 78 if _, ok := (*m)[Pprof_Label_Session_ID]; !ok { 79 return 80 } 81 n := make(labelMap, len(*m)) 82 for k, v := range *m { 83 if k != Pprof_Label_Session_ID { 84 n[k] = v 85 } 86 } 87 setPprofLabel(&n) 88 }