package telegram

import (
	
	
	
	

	
	
	

	

	
)

// meterName is the name of the meter of Client.
const meterName = "github.com/gotd/td/telegram"

// Values of metric attributes.
const (
	poolKindMigrate = "migrate" // FILE_MIGRATE/STATS_MIGRATE pools (invokeSub).
	poolKindFile    = "file"    // FileDC pools.
	poolKindCDN     = "cdn"     // CDN pools.

	restartTimeout   = "timeout"
	restartMigration = "migration"
)

// durationBuckets are histogram buckets in seconds, from a fast RPC to a slow
// pool creation.
var durationBuckets = metric.WithExplicitBucketBoundaries( // nolint:gochecknoglobals
	0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60,
)

// clientMetrics are OpenTelemetry instruments of Client.
//
// Attributes are low-cardinality only: DC IDs, kinds, states, results, and
// TL method names of timed out requests. No peers or message content.
type clientMetrics struct {
	connState      metric.Int64Counter
	connDead       metric.Int64Counter
	reconnects     metric.Int64Counter
	restarts       metric.Int64Counter
	migrations     metric.Int64Counter
	authLost       metric.Int64Counter
	restricted     metric.Int64Counter
	requestTimeout metric.Int64Counter
	poolCreated    metric.Int64Counter
	poolDuration   metric.Float64Histogram
	poolEvicted    metric.Int64Counter
	fileMigrations metric.Int64Counter
	invokeDuration metric.Float64Histogram
	pools          metric.Int64ObservableGauge

	meter metric.Meter

	// Pre-built attributes of hot paths, as slices to pass without
	// allocation.
	invokeOK       []metric.RecordOption
	invokeCanceled []metric.RecordOption
	invokeError    []metric.RecordOption
	// rpcCodes caches attributes of RPC error codes: int -> []metric.RecordOption.
	rpcCodes sync.Map
}

// newClientMetrics creates instruments of Client. A nil provider means no
// metrics.
func ( metric.MeterProvider) (*clientMetrics, error) {
	if  == nil {
		 = noop.NewMeterProvider()
	}
	 := .Meter(meterName)
	 := &clientMetrics{
		meter:          ,
		invokeOK:       resultOptions(attribute.String("result", "ok")),
		invokeCanceled: resultOptions(attribute.String("result", "canceled")),
		invokeError:    resultOptions(attribute.String("result", "error")),
	}

	var  error
	 := func(, ,  string) metric.Int64Counter {
		,  := .Int64Counter(, metric.WithUnit(), metric.WithDescription())
		 = errors.Join(, )
		return 
	}
	 := func(,  string) metric.Float64Histogram {
		,  := .Float64Histogram(,
			metric.WithUnit("s"), metric.WithDescription(), durationBuckets,
		)
		 = errors.Join(, )
		return 
	}

	.connState = ("gotd.client.connection.state", "{event}",
		"Primary connection state changes, by DC and state.")
	.connDead = ("gotd.client.connection.dead", "{connection}",
		"Dead connections, by DC and kind (primary, data, cdn).")
	.reconnects = ("gotd.client.connection.reconnects", "{reconnect}",
		"Primary connection reconnects after the connection stopped, by DC.")
	.restarts = ("gotd.client.connection.restarts", "{restart}",
		"Primary connection restarts requested by the client, by reason (timeout, migration). "+
			"Each restart is also counted in gotd.client.connection.reconnects.")
	.migrations = ("gotd.client.migrations", "{migration}",
		"Primary DC migrations, by target DC.")
	.authLost = ("gotd.client.auth.lost", "{event}",
		"Lost authorizations of an authorized client, by RPC error type (reason) and kind "+
			"(banned, deleted, revoked, unregistered, expired, key_invalid).")
	.restricted = ("gotd.client.account.restricted", "{error}",
		"Errors telling that the account is restricted, by RPC error type: "+
			"FROZEN_METHOD_INVALID, FROZEN_PARTICIPANT_MISSING, PHONE_NUMBER_BANNED.")
	.requestTimeout = ("gotd.client.request.timeouts", "{request}",
		"Requests without response in Options.RequestTimeout, by result (resent, failed) and method.")
	.poolCreated = ("gotd.client.pool.created", "{pool}",
		"Cached DC pools created, by DC, kind (file, migrate) and result.")
	.poolDuration = ("gotd.client.pool.create.duration",
		"Duration of cached DC pool creation, with authorization transfer, by kind and result.")
	.poolEvicted = ("gotd.client.pool.evicted", "{pool}",
		"Cached DC pools dropped after an unauthorized error, by DC and kind.")
	.fileMigrations = ("gotd.client.file.migrations", "{redirect}",
		"FILE_MIGRATE redirects followed, by target DC and source (primary, file).")
	.invokeDuration = ("gotd.client.invoke.duration",
		"Duration of Client.Invoke, with middlewares, by result (ok, rpc_error with code, canceled, error).")

	,  := .Int64ObservableGauge("gotd.client.pools",
		metric.WithUnit("{pool}"),
		metric.WithDescription("Open cached pools, by kind (file, migrate, cdn)."),
	)
	 = errors.Join(, )
	.pools = 

	if  != nil {
		return nil, 
	}
	return , nil
}

var (
	noopMetricsOnce sync.Once      // nolint:gochecknoglobals
	noopMetrics     *clientMetrics // nolint:gochecknoglobals
)

// noopClientMetrics returns shared metrics that record nothing.
func () *clientMetrics {
	noopMetricsOnce.Do(func() {
		,  := newClientMetrics(noop.NewMeterProvider())
		if  != nil {
			// Noop instruments never fail.
			panic()
		}
		noopMetrics = 
	})
	return noopMetrics
}

// meters returns instruments of the client, or noop ones for a client
// created without NewClient (tests).
func ( *Client) () *clientMetrics {
	if .metrics == nil {
		return noopClientMetrics()
	}
	return .metrics
}

// resultOptions returns record options with given attributes.
func ( ...attribute.KeyValue) []metric.RecordOption {
	return []metric.RecordOption{metric.WithAttributeSet(attribute.NewSet(...))}
}

// invokeResult returns attributes of an Invoke result.
func ( *clientMetrics) ( context.Context,  error) []metric.RecordOption {
	if  == nil {
		return .invokeOK
	}
	if ,  := tgerr.As();  {
		if ,  := .rpcCodes.Load(.Code);  {
			return .([]metric.RecordOption)
		}
		 := resultOptions(
			attribute.String("result", "rpc_error"),
			attribute.Int("code", .Code),
		)
		.rpcCodes.Store(.Code, )
		return 
	}
	if .Err() != nil || errors.Is(, context.Canceled) || errors.Is(, context.DeadlineExceeded) {
		return .invokeCanceled
	}
	return .invokeError
}

// dcAttrs returns attributes with DC ID.
func ( int,  ...attribute.KeyValue) metric.MeasurementOption {
	return metric.WithAttributes(append(, attribute.Int("dc", ))...)
}

// now returns current time of the client clock.
func ( *Client) () time.Time {
	if .clock == nil {
		return time.Now()
	}
	return .clock.Now()
}

// registerPoolsGauge starts reporting open pools until the returned function
// is called.
func ( *Client) () func() {
	 := .meters()
	 := metric.WithAttributeSet(attribute.NewSet(attribute.String("kind", poolKindFile)))
	 := metric.WithAttributeSet(attribute.NewSet(attribute.String("kind", poolKindMigrate)))
	 := metric.WithAttributeSet(attribute.NewSet(attribute.String("kind", poolKindCDN)))
	,  := .meter.RegisterCallback(func( context.Context,  metric.Observer) error {
		.ObserveInt64(.pools, int64(.filePools.len()), )
		.ObserveInt64(.pools, int64(.subConns.len()), )
		.ObserveInt64(.pools, int64(.cdnPools.count()), )
		return nil
	}, .pools)
	if  != nil {
		.log.Warn(context.Background(), "Register pools gauge", log.Error())
		return func() {}
	}
	return func() { _ = .Unregister() }
}