dubbo.apache.org/dubbo-go/v3@v3.1.1/filter/active/filter.go (about) 1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package active 19 20 import ( 21 "context" 22 "strconv" 23 "sync" 24 ) 25 26 import ( 27 "github.com/dubbogo/gost/log/logger" 28 ) 29 30 import ( 31 "dubbo.apache.org/dubbo-go/v3/common/constant" 32 "dubbo.apache.org/dubbo-go/v3/common/extension" 33 "dubbo.apache.org/dubbo-go/v3/filter" 34 "dubbo.apache.org/dubbo-go/v3/protocol" 35 invocation2 "dubbo.apache.org/dubbo-go/v3/protocol/invocation" 36 ) 37 38 const ( 39 dubboInvokeStartTime = "dubboInvokeStartTime" 40 ) 41 42 var ( 43 once sync.Once 44 active *activeFilter 45 ) 46 47 func init() { 48 extension.SetFilter(constant.ActiveFilterKey, newActiveFilter) 49 } 50 51 // Filter tracks the requests status 52 type activeFilter struct{} 53 54 func newActiveFilter() filter.Filter { 55 if active == nil { 56 once.Do(func() { 57 active = &activeFilter{} 58 }) 59 } 60 return active 61 } 62 63 // Invoke starts to record the requests status 64 func (f *activeFilter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result { 65 invocation.(*invocation2.RPCInvocation).SetAttachment(dubboInvokeStartTime, strconv.FormatInt(protocol.CurrentTimeMillis(), 10)) 66 protocol.BeginCount(invoker.GetURL(), invocation.MethodName()) 67 return invoker.Invoke(ctx, invocation) 68 } 69 70 // OnResponse update the active count base on the request result. 71 func (f *activeFilter) OnResponse(ctx context.Context, result protocol.Result, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result { 72 startTime, err := strconv.ParseInt(invocation.(*invocation2.RPCInvocation).GetAttachmentWithDefaultValue(dubboInvokeStartTime, "0"), 10, 64) 73 if err != nil { 74 result.SetError(err) 75 logger.Errorf("parse dubbo_invoke_start_time to int64 failed") 76 return result 77 } 78 elapsed := protocol.CurrentTimeMillis() - startTime 79 protocol.EndCount(invoker.GetURL(), invocation.MethodName(), elapsed, result.Error() == nil) 80 return result 81 }