How to use XRate method of metrics Package

Best K6 code snippet using metrics.XRate

processor.go

Source:processor.go Github

copy

Full Screen

1package gc2import (3 "bytes"4 "context"5 "crypto/ed25519"6 "encoding/base64"7 "sync"8 "time"9 "github.com/golang/protobuf/proto"10 "github.com/kinecosystem/agora-common/metrics"11 "github.com/kinecosystem/agora-common/retry"12 "github.com/kinecosystem/agora-common/retry/backoff"13 "github.com/kinecosystem/agora-common/solana"14 "github.com/kinecosystem/agora-common/solana/token"15 "github.com/kinecosystem/agora-common/taskqueue"16 "github.com/kinecosystem/agora-common/taskqueue/model/task"17 "github.com/mr-tron/base58"18 "github.com/pkg/errors"19 "github.com/prometheus/client_golang/prometheus"20 "github.com/sirupsen/logrus"21 "github.com/stellar/go/strkey"22 xrate "golang.org/x/time/rate"23 "google.golang.org/grpc/codes"24 "google.golang.org/grpc/status"25 gcpb "github.com/kinecosystem/agora/pkg/gc/proto"26 "github.com/kinecosystem/agora/pkg/solanautil"27 "github.com/kinecosystem/agora/pkg/transaction/history"28)29const (30 GCQueueName = "garbage-collector-queue"31)32var (33 zeroAccount ed25519.PublicKey = make([]byte, ed25519.PublicKeySize)34 processedCounter = prometheus.NewCounter(prometheus.CounterOpts{35 Namespace: "agora",36 Name: "offline_gc_processed",37 Help: "Number of account processed for garbage collection (offline collector)",38 })39 successCounter = prometheus.NewCounter(prometheus.CounterOpts{40 Namespace: "agora",41 Name: "offline_gc_success",42 Help: "Number of successfully garbage collected accounts (offline collector)",43 })44 failureCounter = prometheus.NewCounter(prometheus.CounterOpts{45 Namespace: "agora",46 Name: "offline_gc_failures",47 Help: "Number of failures while garbage collecting accounts (offline collector)",48 })49)50type Processor struct {51 log *logrus.Entry52 processor taskqueue.Processor53 hist history.Reader54 sc solana.Client55 tc *token.Client56 subsidizer ed25519.PrivateKey57 mu sync.RWMutex58 checkHistory bool59 localLimiter *xrate.Limiter60}61func NewProcessor(62 queueCtr taskqueue.ProcessorCtor,63 hist history.Reader,64 sc solana.Client,65 tc *token.Client,66 subsidizer ed25519.PrivateKey,67 localLimiter *xrate.Limiter,68) (p *Processor, err error) {69 p = &Processor{70 log: logrus.WithField("type", "gc/processor"),71 hist: hist,72 sc: sc,73 tc: tc,74 subsidizer: subsidizer,75 localLimiter: localLimiter,76 }77 p.processor, err = queueCtr(p.queueHandler)78 if err != nil {79 return nil, err80 }81 return p, nil82}83func (p *Processor) queueHandler(ctx context.Context, msg *task.Message) error {84 log := p.log.WithField("method", "queueHandler")85 item := &gcpb.QueueRequest_QueueItem{}86 if msg.TypeName != proto.MessageName(item) {87 log.WithField("type_name", msg.TypeName).Warn("Unsupported message type")88 return errors.New("unsupported message type")89 }90 if err := proto.Unmarshal(msg.RawValue, item); err != nil {91 log.WithField("raw_value", base64.StdEncoding.EncodeToString(msg.RawValue)).Warn("Invalid raw value")92 return errors.New("invalid account key")93 }94 account := item.Key95 log.WithField("account", strkey.MustEncode(strkey.VersionByteAccountID, account)).Trace("Processing")96 // Using a local limiter allows us to more efficiently rate limit our97 // processing without propagating errors up to the task processor, which98 // would in turn increase the receive count of a task, potentially putting99 // the message into the DLQ.100 //101 // In the event that we have more than one migrator (which would primarily102 // occur due to reaching a bottleneck with one limiter), we can re-tune the103 // local rate limiters, and use a global rate limiter as a backup.104 //105 // Note: since the throughput is likely to be bottlenecked by IO / submission106 // times, we can most likely run on a single migrator with high concurrency.107 p.mu.RLock()108 localLimiter := p.localLimiter109 p.mu.RUnlock()110 if err := localLimiter.Wait(ctx); err != nil {111 log.WithError(err).Warn("failed to wait for local limiter")112 return errors.Wrap(err, "failed to wait for local limiter")113 }114 _, err := retry.Retry(115 func() error {116 closed, err := p.maybeCloseAccount(account)117 if err == nil && closed {118 successCounter.Inc()119 }120 return err121 },122 retry.Limit(3),123 retry.NonRetriableErrors(context.Canceled),124 retry.BackoffWithJitter(backoff.BinaryExponential(100*time.Millisecond), 5*time.Second, 0.1),125 )126 if err != nil {127 failureCounter.Inc()128 log.WithError(err).Warn("failed to migrate account")129 } else {130 processedCounter.Inc()131 }132 return err133}134func (p *Processor) maybeCloseAccount(account ed25519.PublicKey) (bool, error) {135 a, err := p.tc.GetAccount(account, solana.CommitmentSingle)136 if err == token.ErrAccountNotFound || err == token.ErrInvalidTokenAccount {137 return false, nil138 } else if err != nil {139 return false, errors.Wrap(err, "failed to load account")140 }141 if a.Amount != 0 || !bytes.Equal(a.CloseAuthority, p.subsidizer.Public().(ed25519.PublicKey)) {142 return false, nil143 }144 p.mu.Lock()145 checkHistory := p.checkHistory146 p.mu.Unlock()147 if checkHistory {148 entries, err := p.hist.GetAccountTransactions(context.Background(), strkey.MustEncode(strkey.VersionByteAccountID, account), &history.ReadOptions{149 Limit: 1,150 })151 if err != nil {152 return false, errors.Wrapf(err, "failed to load transactions for account: %s", base58.Encode(account))153 }154 if len(entries) > 0 {155 return false, nil156 }157 }158 tx := solana.NewTransaction(159 p.subsidizer.Public().(ed25519.PublicKey),160 token.CloseAccount(161 account,162 p.subsidizer.Public().(ed25519.PublicKey),163 p.subsidizer.Public().(ed25519.PublicKey),164 ),165 )166 bh, err := p.sc.GetRecentBlockhash()167 if err != nil {168 return false, errors.Wrap(err, "failed to get recent blockhash")169 }170 tx.SetBlockhash(bh)171 if err := tx.Sign(p.subsidizer); err != nil {172 return false, errors.Wrap(err, "failed to sign close transaction")173 }174 // Choose single for better throughput. It's not critical if it fails later on.175 _, stat, err := p.sc.SubmitTransaction(tx, solana.CommitmentSingle)176 if err != nil {177 return false, errors.Wrapf(err, "failed to submit close for account: %s", base58.Encode(account))178 } else if stat.ErrorResult != nil {179 // The account doesn't exist, or is not a token account. Either way, we can mark it as180 // successfully processed.181 if solanautil.IsInvalidAccountDataError(stat.ErrorResult) {182 return false, nil183 }184 return false, errors.Wrapf(stat.ErrorResult, "failed to submit close for account: %s", base58.Encode(account))185 }186 return true, nil187}188func (p *Processor) Queue(ctx context.Context, req *gcpb.QueueRequest) (*gcpb.VoidResponse, error) {189 tasks := make([]*task.Message, len(req.Items))190 for i := 0; i < len(req.Items); i++ {191 if len(req.Items[i].Key) != ed25519.PublicKeySize || bytes.Equal(req.Items[i].Key, zeroAccount) {192 return nil, status.Errorf(codes.InvalidArgument, "empty key at %d", i)193 }194 raw, err := proto.Marshal(req.Items[i])195 if err != nil {196 return nil, status.Errorf(codes.InvalidArgument, "failed to marshal item")197 }198 tasks[i] = &task.Message{199 TypeName: proto.MessageName(req.Items[i]),200 RawValue: raw,201 }202 }203 if err := p.processor.SubmitBatch(ctx, tasks); err != nil {204 return nil, status.Errorf(codes.Internal, "failed to submit batch: %v", err)205 }206 return &gcpb.VoidResponse{}, nil207}208func (p *Processor) SetState(_ context.Context, req *gcpb.SetStateRequest) (*gcpb.VoidResponse, error) {209 switch req.State {210 case gcpb.SetStateRequest_RUNNING:211 p.processor.Start()212 case gcpb.SetStateRequest_STOPPED:213 p.processor.Pause()214 default:215 return nil, status.Error(codes.InvalidArgument, "")216 }217 return &gcpb.VoidResponse{}, nil218}219func (p *Processor) SetRateLimit(_ context.Context, req *gcpb.SetRateLimitRequest) (*gcpb.VoidResponse, error) {220 p.mu.Lock()221 defer p.mu.Unlock()222 p.localLimiter = xrate.NewLimiter(xrate.Limit(req.Rate), 1)223 return &gcpb.VoidResponse{}, nil224}225func (p *Processor) SetHistoryCheck(_ context.Context, req *gcpb.SetHistoryCheckRequest) (*gcpb.VoidResponse, error) {226 p.mu.Lock()227 defer p.mu.Unlock()228 p.checkHistory = req.Enabled229 return &gcpb.VoidResponse{}, nil230}231func (p *Processor) Shutdown() {232 p.processor.Shutdown()233}234func init() {235 processedCounter = metrics.Register(processedCounter).(prometheus.Counter)236 successCounter = metrics.Register(successCounter).(prometheus.Counter)237 failureCounter = metrics.Register(failureCounter).(prometheus.Counter)238}...

Full Screen

Full Screen

metrics.go

Source:metrics.go Github

copy

Full Screen

...148 Named: map[string]interface{}{149 "Counter": mi.XCounter,150 "Gauge": mi.XGauge,151 "Trend": mi.XTrend,152 "Rate": mi.XRate,153 },154 }155}156// XCounter is a counter constructor157func (mi *ModuleInstance) XCounter(call goja.ConstructorCall, rt *goja.Runtime) *goja.Object {158 v, err := mi.newMetric(call, metrics.Counter)159 if err != nil {160 common.Throw(rt, err)161 }162 return v163}164// XGauge is a gauge constructor165func (mi *ModuleInstance) XGauge(call goja.ConstructorCall, rt *goja.Runtime) *goja.Object {166 v, err := mi.newMetric(call, metrics.Gauge)167 if err != nil {168 common.Throw(rt, err)169 }170 return v171}172// XTrend is a trend constructor173func (mi *ModuleInstance) XTrend(call goja.ConstructorCall, rt *goja.Runtime) *goja.Object {174 v, err := mi.newMetric(call, metrics.Trend)175 if err != nil {176 common.Throw(rt, err)177 }178 return v179}180// XRate is a rate constructor181func (mi *ModuleInstance) XRate(call goja.ConstructorCall, rt *goja.Runtime) *goja.Object {182 v, err := mi.newMetric(call, metrics.Rate)183 if err != nil {184 common.Throw(rt, err)185 }186 return v187}...

Full Screen

Full Screen

XRate

Using AI Code Generation

copy

Full Screen

1type Metrics struct {2}3func (m Metrics) XRate() int {4}5func (m Metrics) YRate() int {6}7func (m Metrics) ZRate() int {8}9import "metrics"10func main() {11 m := metrics.Metrics{}12}13import "metrics"14func main() {15 m := metrics.Metrics{}16}17 /usr/local/Cellar/go/1.7.1/libexec/src/metrics (from $GOROOT)18 /Users/username/go/src/metrics (from $GOPATH)19 /usr/local/Cellar/go/1.7.1/libexec/src/metrics (from $GOROOT)20 /Users/username/go/src/metrics (from $GOPATH)21type Metrics struct {22}23func (m Metrics) X

Full Screen

Full Screen

XRate

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 scope, closer := tally.NewRootScope(tally.ScopeOptions{4 Reporter: tally.NewNoopReporter(),5 }, 1*time.Second)6 defer closer.Close()7 m := metrics.New(scope)8 m.XRate("foo", 10)9 m.XRate("bar", 20)10 time.Sleep(2 * time.Second)11}12import (13type Metrics struct {14}15func New(scope tally.Scope) *Metrics {16 return &Metrics{17 }18}19func (m *Metrics) XRate(name string, value int64) {20 m.scope.Tagged(map[string]string{"name": name}).Gauge("xrate").Update(float64(value))21}

Full Screen

Full Screen

XRate

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m := metrics.New()4 m.Add("1", 1)5 m.Add("2", 2)6 m.Add("3", 3)7 m.Add("4", 4)8 m.Add("5", 5)9 m.Add("6", 6)10 m.Add("7", 7)11 m.Add("8", 8)12 m.Add("9", 9)13 m.Add("10", 10)14 m.Add("11", 11)15 m.Add("12", 12)16 m.Add("13", 13)17 m.Add("14", 14)18 m.Add("15", 15)19 m.Add("16", 16)20 m.Add("17", 17)21 m.Add("18", 18)22 m.Add("19", 19)23 m.Add("20", 20)24 m.Add("21", 21)25 m.Add("22", 22)26 m.Add("23", 23)27 m.Add("24", 24)28 m.Add("25", 25)29 m.Add("26", 26)30 m.Add("27", 27)31 m.Add("28", 28)32 m.Add("29", 29)33 m.Add("30", 30)34 m.Add("31", 31)35 m.Add("32", 32)36 m.Add("33", 33)37 m.Add("34", 34)38 m.Add("35", 35)39 m.Add("36", 36)40 m.Add("37", 37)41 m.Add("38", 38)42 m.Add("39", 39)43 m.Add("40", 40)44 m.Add("41", 41)45 m.Add("42", 42)46 m.Add("43", 43)47 m.Add("44", 44)48 m.Add("45", 45)49 m.Add("46", 46)50 m.Add("47", 47)51 m.Add("48", 48)52 m.Add("49", 49)53 m.Add("50", 50)54 m.Add("51", 51)55 m.Add("52", 52)56 m.Add("53", 53)57 m.Add("54", 54)58 m.Add("55", 55)59 m.Add("56", 56)60 m.Add("57", 57)61 m.Add("58", 58)62 m.Add("59", 59)63 m.Add("60",

Full Screen

Full Screen

XRate

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m := metrics.NewMeter()4 t := metrics.NewTimer()5 c := metrics.NewCounter()6 h := metrics.NewHistogram(metrics.NewUniformSample(1028))7 m.Mark(1)8 t.Time(func() { time.Sleep(1 * time.Second) })9 c.Inc(1)10 h.Update(1)11 fmt.Println("meter rate:", m.Rate1())12 fmt.Println("timer rate:", t.Rate1())13 fmt.Println("counter rate:", c.Rate1())14 fmt.Println("histogram rate:", h.Rate1())15}16import (17func main() {18 m := metrics.NewMeter()19 t := metrics.NewTimer()20 c := metrics.NewCounter()21 h := metrics.NewHistogram(metrics.NewUniformSample(1028))22 m.Mark(1)23 t.Time(func() { time.Sleep(1 * time.Second) })24 c.Inc(1)25 h.Update(1)26 fmt.Println("meter rate:", m.Rate1())27 fmt.Println("timer rate

Full Screen

Full Screen

XRate

Using AI Code Generation

copy

Full Screen

1func XRate() {2}3import "metrics"4func main() {5metrics.XRate()6}7import "metrics"8func main() {9metrics.XRate()10}11import "metrics"12func main() {13metrics.XRate()14}15In this tutorial, I have explained how to create a module in Go. I have also explained the usage of the go mod init command. I have also explained how to import a module in Go. I have also explained how to use the go get command to download a module. I have also explained how to use the go mod tidy command to clean up the go.mod file. I have also explained how to use the go mod vendor command to vendor the dependencies. I have also explained how to use the go mod download command to download the dependencies. I have also explained how to use the go mod verify command to verify the dependencies. I have also explained how to use the go mod graph command to view the dependency graph. I have also explained how to use the go mod edit command to edit the go.mod file. I have also explained how to use the go mod why command to explain why a dependency is needed. I have also explained how to use the go mod help command to view the help for go mod. I have also explained how to use the go mod init command to initialize a module. I have also explained how to use the go mod tidy command to clean up the go.mod file. I have also explained how to use the go mod vendor command to vendor the dependencies. I have also explained how to use the go mod download command to download the dependencies. I have also explained how to use the go mod verify command to verify the dependencies. I have also explained how to use the go mod graph command to view the dependency graph. I have also explained how to use the go mod edit command to edit the go.mod

Full Screen

Full Screen

XRate

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 metrics := NewMetrics()4 metrics.Start()5 time.Sleep(2 * time.Second)6 metrics.Stop()7 fmt.Println(metrics.XRate())8}9import (10func main() {11 metrics := NewMetrics()12 metrics.Start()13 time.Sleep(2 * time.Second)14 metrics.Stop()15 fmt.Println(metrics.XRate())16}17import (18func main() {19 metrics := NewMetrics()20 metrics.Start()21 time.Sleep(2 * time.Second)22 metrics.Stop()23 fmt.Println(metrics.XRate())24}25import (26func main() {27 metrics := NewMetrics()28 metrics.Start()29 time.Sleep(2 * time.Second)30 metrics.Stop()31 fmt.Println(metrics.XRate())32}33import (34func main() {35 metrics := NewMetrics()36 metrics.Start()37 time.Sleep(2 * time.Second)38 metrics.Stop()39 fmt.Println(metrics.XRate())40}41import (42func main() {

Full Screen

Full Screen

XRate

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m := metrics.New()4 xrate := m.NewXRate("xrate")5 xrate.SetInterval(1)6 xrate.Update(10)7 fmt.Println(xrate.Rate())8}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run K6 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful