github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/services/metrics/service.go (about) 1 /* 2 * Copyright 2023 Wang Min Xiang 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 */ 17 18 package metrics 19 20 import ( 21 "github.com/aacfactory/errors" 22 "github.com/aacfactory/fns/services" 23 ) 24 25 var ( 26 endpointName = []byte("metrics") 27 reportFnName = []byte("report") 28 ) 29 30 func New(reporter Reporter) services.Service { 31 return &service{ 32 Abstract: services.NewAbstract(string(endpointName), true, reporter), 33 } 34 } 35 36 type service struct { 37 services.Abstract 38 } 39 40 func (svc *service) Construct(options services.Options) (err error) { 41 err = svc.Abstract.Construct(options) 42 if err != nil { 43 return 44 } 45 var reporter Reporter 46 has := false 47 components := svc.Abstract.Components() 48 for _, component := range components { 49 reporter, has = component.(Reporter) 50 if has { 51 break 52 } 53 } 54 if reporter == nil { 55 err = errors.Warning("metrics: service need reporter component") 56 return 57 } 58 svc.AddFunction(&reportFn{ 59 reporter: reporter, 60 }) 61 return 62 } 63 64 type reportFn struct { 65 reporter Reporter 66 } 67 68 func (fn *reportFn) Name() string { 69 return string(reportFnName) 70 } 71 72 func (fn *reportFn) Internal() bool { 73 return true 74 } 75 76 func (fn *reportFn) Readonly() bool { 77 return false 78 } 79 80 func (fn *reportFn) Handle(r services.Request) (v interface{}, err error) { 81 if !r.Param().Valid() { 82 return 83 } 84 param, paramErr := services.ValueOfParam[Metric](r.Param()) 85 if paramErr != nil { 86 return 87 } 88 fn.reporter.Report(r, param) 89 return 90 }